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.
Related
I am trying to create two dropdown menus, that will enable a selected user to be added to a selected team and submitted.
There are 3 tables users, teams and teammembers. Teammembers has 2 columns for the ID's of users and teams.
I have created some code, that selects the names and id's for both teams and users in the dropdown menu. The first problem I am encountering is only the names are showing and not the id's within the dropdown box.
Secondly, when submitting the form data is inputted into the teammembers table but both as 0 and 0 rather than the users id and team id submitted.
Does anyone know where i've gone wrong?
// cpanel-addplayer.php
<link href="default.css" rel="stylesheet" type="text/css" />
<form method="post" action="cpanel_addplayerprocessing.php">
<?
session_start();
include('../utils/dbc.php');
error_reporting(-1);
echo 'Players';
$sql = "SELECT ID, user_name FROM users";
$result = mysql_query($sql);
echo "<select name='user_name'>";
while ($row = mysql_fetch_array($result)) {
echo'<option value="'.$row['ID'].'">'.$row['user_name'].'</option>';
}
echo "</select>";
?>
<?php
echo 'Teams';
$sql = "SELECT ID, name FROM teams";
$result = mysql_query($sql);
echo "<select name='teams'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['ID'] ."'>" . $row['name'] ."</option>";
$teamid = $row['ID'];
}
echo "</select>";
?>
<input type="submit" name="submit" value="Submit">
</form>
// cpanel-addplayerprocessing.php
<?php
error_reporting(-1);
session_start();
include('../utils/dbc.php');
// escape variables for security
a
$sql="INSERT INTO teammembers (userid, teamid)
VALUES ('$userid', '$teamid')";
$result = mysql_query($sql);
if($result){
header('Location: ../thankyou.php');
}
else {
echo "ERROR";
}
mysql_close();
?>
Thanks for your help!
Use PHP concatanation to generate the SQL query
$sql="INSERT INTO teammembers (userid, teamid) VALUES ('".$userid."', '".$teamid."')";
and also print the sql before execute it and try to run the printed SQL directly in phpMyAdmin.
echo $sql;
exit;
Also check the table columns if there is space after or before the column names.
WHy is my drop down list not populating with the table data? (dropdown box is empty)
And what is used to display data upon selection of an item in that drop down - is it a "VIEW" (please do provide a study link so I can learn)
My Code
<?php
$con=mysqli_connect("localhost","root","","ismat_db");
//check connection
if(mysqli_errno($con))
{
echo "Can't Connect to mySQL:".mysqli_connect_error();
}
else
{
echo "Connected to mySQL</br>";
}
//$query = 'SELECT FirstName FROM persons';
//$result = mysqli_query($con,$query);
$query = mysqli_query($con,"SELECT 'FirstName' FROM persons");
//print_r($query);
//echo '<select name="FirstName">';
echo "<select name= 'FirstName'>";
//while($row=mysqli_fetch_array($result))
while($row=mysqli_fetch_array($query))
{
echo $row;
//echo "<option value='".$row['FirstName']."'>".'</option>';
}
echo '</select>';
?>
You had 2 errors:
I pointed the first in the comment: to print an option you must use this code:
echo "<option value='". $row['FirstName']."'>".$row['FirstName']
. '</option>';
The second is in your SQL: you are not selecting the FirstName field from the database, but a string 'FirstName' instead. That's why it is printed twice as you said. Use this SQL to get the field:
$query = mysqli_query($con,"SELECT FirstName FROM persons");
Also usually people put an id of the record and not a field, that may have possible duplicates into the value of an <option>. So, I would have used:
echo "<option value='". $row['id']."'>".$row['FirstName']
. '</option>';
selecting the id from the database together with first name.
Try this:
echo "<option value='".$row['FirstName']."'>".$row['FirstName']."</option>";
Also seems that you are having an issue with the database query. Swap your while loop with the following and see if it works
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo "<option value='".$row['FirstName']."'>".$row['FirstName']."</option>";
}
$result->free();
}
I want to use the following code to populate a drop-down list with all of the customer types:
<select name="type" id="type" class="neutral">
<?php // SQL QUERY TO RETRIEVE EVERY TYPE OF CUSTOMER
$sql = "SELECT CUST_TYPE FROM `CUSTOMER` GROUP BY `CUST_TYPE`";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){echo '<option value="'.$row.'">'.$row.'</option>';}
?>
The query works in phpMyAdmin; it gives the correct output (corporate, other, school, sports) but in the webpage it displays a drop-down list with 4 options, all containing the word "array." Please help!
Try
while($row = mysql_fetch_assoc($result)){
echo '<option value="'.$row['CUST_TYPE'].'">'.$row['CUST_TYPE'].'</option>';
}
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)
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."')";