How do I get the ID of selected datalist - php

I have just figured out how to populate a datalist element from mysql. I need to get the associated ID that corresponds to the selected value to submit to another page. I can submit the value, but I need the ID. I hope it is a simple syntax error, but I can't figure it out.
Thanks in advnace.
<?php
require 'connect_mysqli.php';
$sql = "SELECT street FROM streets";
$result = mysqli_query($con, $sql) or die ("Error " . mysqli_error($con));
?>
<form action="new.php" name="test" method = "post">
<datalist id="street" name="streets">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['street']; ?>"><?php echo $row['street_id']; ?></option>
<?php
}
?>
</datalist>
<input type="text" name="street" id="test" autocomplete="off" list="street">
<input type="submit" value="Submit">
<?php
mysqli_close($con);
?>

Also I think you are doing wrong to submit value of street. Change it to this
<option value="<?php echo $row['street_id']; ?>"><?php echo $row['street']; ?></option>
It will display street name and submit street id And get value like this
$_post["streets"];// I haven't used datalist but if works it would be this

Look at your query:
$sql = "SELECT street FROM streets";
"I hope it is a simple syntax error"
You didn't make a syntax "error", you just didn't select the street_id column in your query, that's why it's not showing in the dropdown, in regards to $row['street_id'].
You need to add it in your query:
$sql = "SELECT street, street_id FROM streets";
N.B.: Column selection are separated by commas. You can further add to the query if you wish, but make sure there isn't a trailing comma following the last column chosen.
I.e: This would FAIL:
$sql = "SELECT street, street_id, col3, FROM streets";
However, $row['street_id'] and $row['street_ID'] are two different animals altogether here. So, make sure that that is the letter-case used. They are case-sensitive when it comes to looping over column names, and that would trigger an error when checking for them, being something to the effect of an unexisting column.
Sidenote:
I didn't see a closing </form> tag in your posted code. Make sure it's part of your real code.
Reference:
http://dev.mysql.com/doc/refman/5.7/en/select.html

You just forgot to include the street_id column in the columns you are selecting from the streets table.
Change this line:
$sql = "SELECT street FROM streets";
to this line:
$sql = "SELECT street, street_id FROM streets";

Related

php mutiselect dropdown which get data from mysql

I would like to create a multi-select drop down list of countries in my form which lets users choose more than one country and also provides the ability to remove the item they selected, if needed.
I could create a drop down list which extracts the name of the countries from a mysql table, but it lets users only select one country. I searched a lot for multi-select drop down but none of the samples that I have found get data from mysql. They had only a few options which could easily write with option value like How to access the values selected in the multiselect dropdown list in PHP?
This is my code through which only one item can be selected:
<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('imdb');
$sql2 = "SELECT country FROM countries";
$result2 = mysql_query($sql2);
echo "<select name='country'>";
while ($row = mysql_fetch_array($result2)) {
echo "<option value='" . $row['country'] . "'>" . $row['country'] . "</option>";
}
echo "</select>";
?>
Finally, I found what I was looking for. So I share it since might be useful for those with similar question.
First, as Marc said, I had to add multiple like below:
<select name="countrylist[]" multiple="multiple">
and this is the html line that I was searching for :
<option value="<?php echo $row['country'];?>"> <?php echo $row['country'];?> </option>
where country is the name of the related field in my database.
it might be worth saying that in order to insert the result in database (e.g table name = "test", field name = "q5":
<?php
mysql_connect("hostname", "user name", "user password") or die(mysql_error());
mysql_select_db("db name") or die(mysql_error());
$q5 = implode(',', $_POST['countrylist']);
if(isset($_POST['submit']))
{
$query="INSERT INTO test (q5) values ('". $q5 ."')";
mysql_query($query) or die (mysql_error() );
}
?>
It worked for me and hope will be useful for others.

Sending data from dropdownlist to database

We are having troubles with our php session.
Trying to add a patient to a database, linked to the doctor that is curing the patient.
We have a select from the existing doctors in the database. They show up in the dropdown list.
But when we are trying to send the selected doctor to the database (the php session), there is no addition to the database. All the other inputs (patient name, patient birth date, etc) are put in the database, except the data from the dropdown list.
Add_patient.php
Doctor:<br>
<select name="doctor">
<option value="">--Select--</option>
<?php
$config = parse_ini_file("divkey.ini.php", true);
include("connect/connect_mysql.php");
$opdracht = "SELECT * FROM gebruiker ORDER BY id";
$resultaat = mysql_query($opdracht);
while ($rij = mysql_fetch_array($resultaat)) {
$id = $rij['id'];
$name = $rij['name'];
$fname = $rij['fname'];
?>
<option value ="<?php $id;?>"><?php echo"$name $fname" ?></option>
<?php
} ?>
</select>
Session_add.php
$doctor = $_POST['doctor'];
# query
Our query from session_add.php works. Just the not for the $_POST['doctor'].
# query
$opdracht = "INSERT INTO patient ( `name`, `fname`, `geslacht`, `doctor`, `straatnaam`, `huisnummer`, `postcode`, `gemeente`, `telefoonnummer`, `patientnummer`, `land`, `bloedgroep`, `gsmnummer`, `geboortedatum`, `geboorteplaats`, `taal`, `nationaliteit`, `rijksregisternummer`, `huisarts` )
VALUES ('".$name."', '".$fname."', '".$geslacht."', '".$doctor."','".$straatnaam."' ,'".$huisnummer."' , '".$postcode."' , '".$gemeente."', '".$telefoonnummer."',
'".$patientnummer."','".$land."', '".$bloedgroep."', '".$gsmnummer."', '".$geboortedatum."', '".$geboorteplaats."', '".$taal."', '".$nationaliteit."','".$rijksregisternummer."', '".$huisarts."')";
# other values are not important, it's in Dutch and these values are sent to the database
# doing query
$result = mysql_query($opdracht) or die(mysql_error());
# we use or die(mysql_error())
The query is executed, a 0 (zero) is added to the database instead of the selected doctor.
<option value ="<?php echo $id;?>"><?php echo $name.$fname; ?></option>
Try this.
We found the problem, it was in the sql query. With var_dump($_POST)
I checked the values that were sent to the session, these were the right ones.
In the SQL query, there was '".$doctor."'
This was wrong, it should be '.$doctor.' (recognised as id)
Thanks for the help!

php drop-down menu from MYSQL, how to return other column value?

I'm having a input form that asks for a location. The locations are stored in a mysql db and have an id (colomn: id and column: location).
I have a drop down menu that is generated from those records in the db:
<select name="location">
<?php
$query="SELECT location FROM locations";
$result=mysql_query($query) or die;
while ($row=mysql_fetch_array($result)) {
$location=$row['location'];
echo "<option>$location</option>";
?>
</select>
This all works. When the form is sumbitted, I obviously get a POST[location] for example "Belgium".
Let's say Belgium is the location in my db and has id 5, how can I return the ID as the POST variable from the dropdown box, instead of the location. Ofcourse I want the dropdown to show the locations, and not the ID's.
Thanks in advance!
Each option can take a value and show another string so use value="my_value" for each option inside the select tag
<select name="location">
<?php
$query="SELECT id, location FROM locations";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
echo "<option value=\"" . $row['id'] . "\">" . $row['location'] . "</option>";
}
?>
</select>
now your POST['location'] will contain the db id for selected location
if you change the SQl query to include the ID of the location,
you can assign that value to the dropdown selected value.
<select name="location">
<?php
$query="SELECT id, location FROM locations";
$result=mysql_query($query) or die;
while ($row=mysql_fetch_array($result)) {
$location=$row['location'];
$id = $row['id'];
echo "<option value='".$row['id']."'>".$location."</option>";
?>
</select>
select ID from locations;
$ID=$row['ID'];
Replace ID by the ID-name of your column ofcourse.
If you say select * from locations you can do something like this:
$row['anyCOLUMNNAME']
You can choose any column you like and use that information from that particular row.
<select name="location">
<?php
// select columns you need, separate by , (comma)
$query = "SELECT `column1`, `column2` FROM `locations`;";
$result = mysql_query($query) or die;
while ($row = mysql_fetch_array($result)) {
// selected columns become accessible in $row array
// value attribute needs to be escaped here
echo '<option value="', htmlentities($row['column1']),'">',
htmlentities($row['column2']), '</option>'; // escape label too
// <option> does not accept HTML in label so it should be escaped
} // done!
?>
</select>
^ this (read comments for explanations)

Displaying user's SQL query using PHP

Please can anyone help me with this?
I have 2 tables, location and tickets and what I have built so far is a form in a div that users enter the name of the city or town where they would like to see a live music performance. This form is submitted and an SQL statement is passed querying the location table. In another div, the users search query appears in a box on the screen. What I would like to do next is to write an SQL statement that will lookup the user's query and dynamically display the relevant ticket information from the ticket table based on the location ID.
For example, the user types in 'Newcastle' as their search query, the location table finds the city of Newcastle and displays the user's result in a div called 'tickets'..I would like to display all the fields that correspond with 'Newcastle' from the ticket table.
The locationID is the primary key in the location table and has 3 other column, city, town and postcode.
The ticket table consists of ticketID being the primary key, the locationID being the foreign Key and the other fields i.e venue, tPrice, date and time. I think the problem im having is im not passing through the variable from the users query so that the ticket table can look it up and display the relevant information.
Here is the code for the form:
<div id="search">
<form name="searchForm" id="searchForm" class="searchForm" method="post">
<input type="text" name="citySearch" id="citySearch" class="citySearch" placeholder="Enter name city/town..." autofocus="autofocus" />
<input type="submit" name="ticketSearch" id="ticketSearch" class="ticketSearch" value="Search" />
</form>
</div>
Here is the code to display the user's query:
<div id="locationResult">
<?php
include( 'classes/database_connection.php' );
$cSearch = $_POST['citySearch'];
$sql = "SELECT DISTINCT city FROM location WHERE city = '$cSearch'";
mysql_query($sql) or die (mysql_error());
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$city = $row['city'];
echo $row["city"];
}
mysql_free_result($queryresult);
mysql_free_result($qResult);
mysql_close($conn);
?>
</div>
</div>
This is where I want to display the ticket results from the ticket table:
<div id="ticketsResults">
<table class="ticketResult" border="0" cellspacing="5">
<tr>
<td><b>Venue</b></td>
<td><b>Price</b></td>
<td><b>Date</b></td>
<td><b>Time</b></td>
<td><b>Street View</b></td>
</tr>
<?php
include( 'classes/database_connection.php' );
$locID = $_POST['locationID'];
$citySearch = $_POST['citySearch'];
$sQL = "SELECT locationID FROM location";
//Here is where I want it to display dynamic information rather than manually type the location
$ticketSQL = "SELECT * FROM ticket NATURAL JOIN location WHERE city = 'Newcastle' ";
mysql_query($sQL) or die (mysql_error());
$qResult = mysql_query($sQL) or die(mysql_error());
mysql_query($ticketSQL) or die (mysql_error());
$result = mysql_query($ticketSQL) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// $ticketID = $row['ticketID'];
$venue = $row['venue'];
$ticketPrice = $row['tPrice'];
$date = $row['date'];
$time= $row['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>&pound$ticketPrice</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td>Click to see</td>\n";
echo "</tr>\n";
}
mysql_free_result($qResult);
mysql_free_result($result);
mysql_close($conn);
?>
</table>
</div>
So basically, I'm wanting an SQL statement that dynamically displays the tickets according to the user's query. Sorry about the copious amount of code! Any help given is greatly appreciated.
Before you do anything else I think you should work on your coding style, specifically your indentation. A quick google search should do the trick. Next look into mysql prepared statements because currently your code is unsafe. Like jordanm said, it is subject to SQL injection.
For example, if someone entered blah' OR 'x'='x as a city name. Your query would become
SELECT DISTINCT city FROM location WHERE city = 'blah' OR 'x'='x';
Basically it allows the user to do naughty things with your query, and you don't want that.
Below is a sample of how you can avoid this using mysql prepared statements:
// basic quick raw example
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT DISTINCT city FROM location WHERE city = ?');
$stmt->bind_param('s',$city_name);
$stmt->execute();
$stmt->bind_result($city);
while ($stmt->fetch())
{
echo $city;
}
That's all I'm going to leave you with because I feel like to answer the actual question (?) I will need to write the code for you. Goodluck

PHP and MySQL help needed

I have 2 tables in my database. categories and products. in categories there are 2 fields. catid and catname. and in products also there are 3 fields. id, catid and name.
in my submit form im fetching the catname in to a sector. what i wanna do is get value of the selector and save the catid in to products table catid field. instead of categories name. can anyone explain me how to do this. Thanks in advance.
Here is the code of submit form.
include("db.php");
$result = mysql_query("SELECT * FROM categories")
or die (mysql_error());
?>
<!--SubmitForm-->
<form method="post" action="add_products.php">
<select name="cat">
<?php
while($row = mysql_fetch_array($result))
{echo "<option value='".$row[catid]."'>".$row[catname]."</option>";}
?>
</select><br/>
<input type="text" name="name" value=""><br/>
<input type="submit" value="submit"/>
</form>
add_products.php Code
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
while($row = mysql_fetch_array($result)){
$catn = $row['catid'];
}
$name = mysql_real_escape_string($_POST['name']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
?>
You already seem to have the right values, just need to put them in the correct spot, if you need the 'catid', you can just put it in the id tag of the select.
When you echo the you just need to do this,
echo "<option id='".$row[catid]."' value='".$row[cat]."'>".$row[catname]."</option>";
For more info refer to the w3school manual for , at this link.
Some unrelated, but very important things:
you should escape $cat before it goes into the query
you should always escape strings that go out to HTML with htmlspecialchars
you should always use $row['keyname'], not the deprecated $row[keyname]
Now for your question. The code seems correct on first glance, but I don't have PHP right now so I can't test it. Is there anything in particular that is not working as expected?
You already have it in??
$cat = $_POST['catid'];
If you only want to insert IF they $cat exists, then:
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
if($result)
{
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
}
?>
You are already assigning the category ID to the category name in the select menu. The variable of the select menu is $_REQUEST['cat'], which holds the ID of the selected category after submitting the form. You can save this value directly to the product table.
However, the while loop in add_products.php is of no use, since you are always assigning the last ID in the table to the variable $catn. Replace this while loop with $catn = $_REQUEST['cat'] (while cat is the name of the select menu).
seem many mistakes here:
select name="cat"
and your try to receive $cat = $_POST['catid']; the correct is $cat = $_POST['cat'];
then you tries to select by catname
$query = "SELECT * FROM categories WHERE catname='$cat'";
when you need to compare ids catid='$cat'";
and what for to assign meny times if the result is single?:
if ( ($row = mysql_fetch_array($result)) ){
$catn = $row['catid'];
}
Your select field is names 'cat', so it should be $_POST['cat'] (or better, rename the select field to 'catid'). And it alreay contains the catid, so there's no need to get it from the DB again (unless you want to make sure it does in fact exist).
Finally, you should escape the $_POST['cat'] parameter as you do the name.
So this is sufficient:
$catid = mysql_real_escape_string($_POST['cat']);
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name) VALUES ('".$catid"','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
Please also look into PDO for the best way to handle DB queries like this.
try change this
"INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
to
"INSERT INTO products(catid, name)VALUES ('".$cat."','".$name."')";

Categories