Dropdown box getting values from mySQL shows blanbk entries - javascript

I'm using the template from this mySQL x AJAX tutorial (http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html) to create dependent dropdowns.
How the code should work:
Coach selects what activity group ($activity) he wants to browse from box one.
Box two the populates with a list of players($username) who are part of that activity.
It does the above, but the entries show up blank as opposed to printing the name - see screenshot attached. Below is the piece
<?php
if($_POST['activity'])
{
$activity=$_POST['activity'];
$sql=mysql_query("SELECT id AND username FROM player WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$username=$row['username'];
$activity=$row['activity'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
I've messed around with the number of entries in the db, and the blank values change respectively (when changed to 5 people being in group, 5 blank spaces show, etc.)
It's really odd because of the fact it appears to be working, just not showing the names.
Any ideas?
Cheers.

Try fixing your query. You are ANDing the values id and username
SELECT id, username FROM player WHERE activity='$activity'

You forgot to isset your $_POST['activity'].

Related

use data return from php / database to create new form

I did some research already but can't find a good solution to this. I am sure it's simple, but I could use some help.
I am using HTML -> Javascript -> PHP to get info back from a database.
My goal is to have the data return, but have it add check boxes at the end of each row where if the person check it, it will add them to another table.
In my example, it will return a list of cards and if the person uses the check box it will add each card they checked to a "have" list. For my code provided below, it's a "display all" so I didn't use any javascript. I put it straight from html to php. I figure if I can get the most simple example working, adding the js to my other search display will be easy.
HTML
<fieldset>
<form action="display_all.php" method="post">
Order by: <select name="order_all" id="order_all">
<option value="parallel">Parallel</option>
<option value="faction">Faction</option>
</select>
<input type="submit" value="display all cards">
</form>
</fieldset>
PHP (to save space I cut out some of the standard code)
$order_all = $_POST['order_all'];
// Create SQL statement
$query = "SELECT * FROM cards ORDER BY $order_all ASC";
// Execute SQL statement
if (!($result = # mysql_query ($query, $connection)))
showerror();
// Display results
while ($row = # mysql_fetch_array($result)) {
echo "<tr><td>{$row["parallel"]}</td>
<td>{$row["faction"]}</td>
<td>{$row["in_set"]}</td>
<td>{$row["card_name"]}</td>
<td>{$row["color"]}</td>
<td>{$row["number_in_set"]}</td>
<td>{$row["rarity"]}</td>
<td>{$row["sold_out"]}</td>
<td>{$row["series"]}</td>
</tr>";
}
I tried adding different things to the while { } at the end of the PHP file but I don't really know the proper way to do that. Based on what I saw around, people suggest doing this in javascript and creating a function for it. Start with my ajax call and callback? I planned on linking my checkboxes to the ID of each card (which is stored in the database, but not printed) I figure they will just be linked to query insert commands. Like if check [ insert command ] and form submit? idk looking for some suggestions, I am still new to using databases in this sort of way.
FOUND A SOLUTION TO MY PROBLEM, well sorta.
It was a bunch of little things. I haven't added functionality, but I at least got the checkbox to show up.
while ($row = # mysql_fetch_array($result)) {
echo"
<tr>
<td>{$row["parallel"]}</td>
<td>{$row["faction"]}</td>
<td>{$row["in_set"]}</td>
<td>{$row["card_name"]}</td>
<td>{$row["color"]}</td>
<td>{$row["number_in_set"]}</td>
<td>{$row["rarity"]}</td>
<td>{$row["sold_out"]}</td>
<td>{$row["series"]}</td>
";
echo'<td><input type="checkbox" value="submit" id="{$row["id"]}/></td>';
echo"</tr>";
}
Your code is paradise for SQL injection! You have to check user input, at least escaping with mysql_real_escape_string or
Switch to newer, better and safer mysqli (or PDO) interface and use prepared statements. I recommend mysqli anyway.
Note: in this particular case is best to use switch with options.
To question: why don't you get checkbox value from post and then take actions, but I'm not sure what are you asking.

Selecting values of select dropdown using javascript code

I have a form.php which adds username selected from dropdown select, and user payments received into database. After inserting values by going to add_form.php, it comes back to form.php. I have sent the username from add_form.php to form.php by using below code
$result=mysql_query($sql);
if($result==1){
echo '<script language="javascript">';
echo 'alert("Payment added successfully");';
echo 'window.open("form.php?name='.$name.'", "_self");';
echo '</script>';
}
Now problem is that, how can I use this get parameter to select the passed value into dropdown automatically? I want the end user of the application to select a name once and add multiple payments, i.e., selected name should be there even after payment is added into db
I am not sure what you want but if filling up the select with options dynamically (with some js variables) is what you want then you can try something like.
$("#id_something").empty();
$("#id_something").append('<option selected="selected" value='+somejsvariable+'>'+someotherjsvariable+'</option>');
Hope it helps.

Select specific row in <select> list after return from SQL query

I have this rather tricky problem to solve whereby I have used the following to display a list of named shops with ID number for selection from a drop down list when creating a new employee record. This works well at this point. A piece of javascript splits the displayed text from the the user selection and sends the shop ID number off with the new employee details to be inserted into the employee table in the database. I am using a hidden shopID text box to store the number as can be seen in the javascript.
Here is the code PHP first then javascript:
$result = mysqli_query($link,"SELECT shopID, shopName FROM SHOP");
echo "<br><select class='formInput' name='listbox' id='listbox' onchange='captureShopID()' tabindex=9>";
#Use onchange instead of onclick where Keyboard is used. onclick does not register changes fro keyboard
while($row = mysqli_fetch_array($result))
{
$shopID = $row['shopID'];
$shopName = $row['shopName'];
$allText = "$shopID, $shopName";
echo "<option value='$allText'>S00$shopID $shopName</option>";
}
echo "</select>";
AND (including this, because it may contain hints to a solution for my problem)
<script>
function captureShopID()
{
var sel = document.getElementById("listbox");
var result;
result = sel.options[sel.selectedIndex].value;
var shopNumber = result.split(',');
document.getElementById("shopID").value = shopNumber[0];
}
</script>
OK. So all good so far. What I am trying to do is use the same set up for amendments to the same record. So the update layout is similar to the one for creating the record. I have the list element again but what I would like is to have it showing the shop that the employee works at otherwise it is confusing as the list defaults to the first item in the list, in most cases not the actual shop that the employee works in.
So, instead of:
S001 London
Maybe it should be:
S003 Paris… Where the employee works.
I have tried various things but it is a tricky one. The fact that there is the option value concatenation of $shopID and $shopName may be complicating things a bit in my quest for a solution.
Pretty new to PHP and javascript (javascript pretty mysterious) and programming as a whole. Learning quickly but suffer many days of brain cell overload.
Any pointers in the right direction appreciated.
My Solution… After some outside the box tangental thinking working on some other aspects of my project.
<?php
include "../db.php";
$result = mysqli_query($link,"SELECT shopID, shopName FROM SHOP");
echo "<br><select class='formInput' name='listbox' id='listbox' onchange='captureShopID()' tabindex=9>";
#Use onchange instead of onclick where Keyboard is used. onclick does not register changes from keyboard
echo '<option>Works at:'.$shopName.'</option>';
while($row = mysqli_fetch_array($result))
{
$shopID = $row['shopID'];
$shopName = $row['shopName'];
$allText = "$shopID, $shopName";
echo "<option value='$allText'>S00$shopID $shopName</option>";
}
echo "</select>";
?>
I achieved what I wanted by adding the extra to the top of the list outside the loop to act as the default item listed:
echo 'Works at:'.$shopName.'';
This has the result of presenting the update employee record so that shop from their record is what you see in the menu like so:
Works at: London Southwark
And the list pops up to show the other shop options
Works at: London Southwark
S001 DISTRIBUTION CENTRAL Paris
S002 Paris Montmartre
S003 London Southwark
S004 Roma Trastevere
and so on.
Not exactly what I initially intended but just as good
I am aiming for a clean and spasre interface without too many labels and this solution makes the list element self explanatory.
If any one has a good suggestion for the thread title please post as this one is quite useful.

Can CSS or JS effect the submission of a form?

I have a large form spread over 3 tabs. The tabs are controlled by JS which simply changes the css property display: block to display:none depending what tab you click on.
This form also submits data to 3 different tables via php. When i submit my form at the end of the the 3rd tab some of my data is missing in a table that accepts multiple rows (the other two tables only accept a single row) In this section of the form I let the user add as many "Rooms" as they need. The rooms are just a few selection boxes, and the extra selection boxes are also added with JS. When i submit my form only the first "room" is added to the table.
I am positive every thing is working as if I remove the tabs it works perfectly or even if i add all three sections of the form to one tab it works. Below is the PHP that inputs the rooms and loops depending how many there are. Sorry this is a very large form so i dont want to just stick it all in, but it is all very simple and all working. Please let me know if I should add any other part of my code if that helps.
$level = $_POST['level'];
$room_type = $_POST['room_type'];
$width = $_POST['width'];
$length = $_POST['length'];
$num_rooms = count($level);
for($x=0;$x<$num_rooms;$x++)
{
$room_insert = mysqli_query($dbcon, "INSERT INTO listing_rooms (Listing_ID, Level, Type, Length, Width) VALUES ('$listing_id', '$level[$x]', '$room_type[$x]', '$length[$x]', '$width[$x]')") or die(mysql_error());
}
To trigger this I have an if(isset()) just above this. Thanks for any help.
This is the JS that shows and hides the tabs...
function showHideTab(tab_id) {
if (tab_id == 'details_tab'){
document.getElementById('listing_details').style.display='block';
document.getElementById('listing_info').style.display='none';
document.getElementById('photo_upload').style.display='none';
}else if (tab_id == 'info_tab') {
document.getElementById('listing_info').style.display='block';
document.getElementById('listing_details').style.display='none';
document.getElementById('photo_upload').style.display='none';
}
else if (tab_id == 'upload_tab') {
document.getElementById('photo_upload').style.display='block';
document.getElementById('listing_info').style.display='none';
document.getElementById('listing_details').style.display='none';
}
}
As I thought this was a very simple error. As i said I have 3 divs being shown or hidden by JS. My issue was I had my opening FORM tag inside my first div!
I still dont know why everything other then the array of "rooms" worked fine regardless of where the opening form tag was, and even the array held the first value?

Get random data from database,

I have a little problem, I've got this database with these fields.
Table Data{
ID
Name,
Text,
Location,
imagepath
}
And now I want the put these values into my fields, the data is just strings.
<h3><!-- Text value here --> - <!-- Name value here --></h3>
<p> <!-- Location data here --> </p>
And I also got this JS script that generates new fields, when the user clicks on a button.
$('.Next').click(function(e) {
e.preventDefault();
Slide.appendSlide('<!-- HTML DATA HERE NAME AND TEXT & LOCATION VALUES -->')});
I want the ID to be random, and I don't want the user to get the same data twice.
How should i approach this? I've tried a getdata.php but failed.
Thank you so much! Happy holidays!
Honestly i would look at saving the page id to $_session['visited']. Then each time they view a page append that to the session variable comma separated
$_session['visited'] .= ",".$page_id;
Then your sql will be.
EDITED
Ok so let make this code safe
$ph = explode(",",$_session['visited']);
foreach($ph as $check){
if (!isnumeric($check)){
echo "Not numeric, possible injection";
exit;
}
}
$parmcount=count($ph);
$inclause=implode(',',array_fill(0,$parmcount,'?'))
$sql='SELECT * FROM table WHERE ID NOT IN (%s)';
$preparesql=sprintf($sql,$inclause);
$st=$db->prepare($preparesql);
$st->execute($parms);
Or alternative just save all viewed ids as an array in the first place.

Categories