In this code when i selected multiple values from dropdown it is stoing in a single row but i like to apply value in each row so please anybody help me.
Actual result:
id game
1. cricket,football,tennis
Expecting result:
id game
1 cricket
2 football
code -
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$query=mysql_connect('localhost','root','');
mysql_select_db("freeze",$query);
$choice=$_POST['game'];
$choice1=implode(',',$choice);
mysql_query("insert into tb values('','$choice1')");
}
?>
<form method="post" action="multipleselect.php">
Select your favourite game:<br/>
<select name="game[]" multiple="multiple">
<option>Football</option>
<option>Volleyball</option>
<option>Badminton</option>
<option>Cricket</option>
<option>Cricket1</option>
<option>Cricket2</option>
<option>Cricket3</option>
<option>Cricket34</option>
</select>
<input type="submit" name="submit">
</form>
</body>
</html>
First of all, please don't use mysql_* as it's deprecated, use mysqli_ or PDO instead.
now if you just want the values of options then do it like this
<select name="game[]" multiple="multiple">
<option value="1">Football</option>
<option value="2">Volleyball</option>
...
</select>
this way it'll give you 1,2,..... Hope that's what you're looking for.
and if you're looking for query like this
INSERT INTO tb (`game`) VALUES ('Football'),('Volleyball')
assuming that id field is auto-incremented, then change the code as follows:
html code
<select name="game[]" multiple="multiple">
<option>Football</option>
<option>Volleyball</option>
...
</select>
php code
$choice=$_POST['game'];
$sql = "INSERT INTO tb (`game`) VALUES ";
$sqlValues= null;
foreach($choice as $ch) {
$sqlValues .= "('$ch')," ;
}
$sql.=rtrim($sqlValues, ",");
echo $sql;
this way you could get
id game
1 cricket
2 football
It is inserting them all in 1 row, because you are imploding your $_POST['game']
$choice=$_POST['game'];
$choice1=implode(',',$choice);
mysql_query("insert into tb values('','$choice1')");
You need to loop over each $_POST['game'] value
foreach($_POST['game'] as $choice){
mysql_query("insert into tb values('','$choice')");
}
note, your query is open to SQL injection, make sure to sanitize your data before inserting into your db. Also, mysql_* are deprecated, so you should update to mysqli or PDO - http://php.net/manual/en/mysqlinfo.api.choosing.php
Are there any error messages being displayed? Insert the following code just before the mysql_query statement:
echo "insert into tb values('','$choice1')";
what is being displayed?
<?php
if(isset($_POST['submit']))
{
$query=mysql_connect('localhost','root','');
mysql_select_db("freeze",$query);
$choice=$_POST['game'];
$choice1=implode(',',$choice);
foreach($choice1 as $choice)
{
mysql_query("insert into tb values('','$choice')");
}
}
?>
You just try this code i hope it works for you. If not then please reply me.
Related
I make a form, where there is ID of a shop:
<input type="text" name="shopId">
and there is a multiple choice select:
<select name="cars" multiple required>
after i get selected options, i have to pass them to a table in the database; table consists of 2 columns: shopId and car. The thing is it passes only one option and it is impossible to have a few rows added to the table like in one shop two or three models. I suppose i have to pass the data like an array or something. Can you help me, please.
$shopId = $_GET["shopId"];
$cars = $_GET["cars"];
this is a query:
$query = "INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";
I'd say given the constraints, the only option you have is to combine all the selected options into a single comma separated string (using PHP's built-in function called implode http://php.net/implode), then insert the shopID and the comma-separated-list of cars into a new row. I'd do it like this:
<?php
if ($_POST) {
$cars_string = implode(', ', $_POST['cars']);
$sql = '
INSERT INTO
`my_table` (
`shopID`,
`cars`
)
VALUES (
'. $_POST['shopID'] .',
"'. $cars_string .'"
)
';
mysql_query($sql) OR die(mysql_error());
}
?>
<form method="post" action="">
Shop ID: <input type="text" name="shopID"/> -
<select name="cars[]" multiple="multiple">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="honda">Honda</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<input type="submit" name="Submit"/>
</form>
This is the best solution given the constraints you've provided. However, I do not see the logic in only being able to add a single row per form submit. That is not a good database design, especially in the long-term.
Please notice how the <select> element has the name of name="cars[]" and pay close attention to the open/close square brackets after the word cars[]. This will allow multiple options to be passed through the form, instead of only one. This is a critical difference and it should not be overlooked, as #bart2puck mentions in his solution. Also, the most browser-friendly way to allow users to select multiple options is to use the attribute multiple="multiple" in your <select> element.
you are getting only 1 insert because you are setting the value of $_GET['cars'] to the last selected item in your multiple. to acheive what you are looking for set the select name of cars to cars[]. When you goto process this you will now have an array in $_GET data.
then loop through that to do your inserts.
$shopId = $_GET['shopId'];
foreach ($_GET['cars'] as $value)
{
$ins = "INSERT INSERT INTO shops (shopId, car) VALUES ($shopId, $value)";
}
if you can only have 1 insert, which seems odd, then do something like:
$cars = "";
foreach ($_GET['cars'] as $value)
{
$cars .= $value . ",";
}
$cars = substr($cars,0,-1); //to remove the last comma
then
$ins = "INSERT INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";
you are going to end up with a field like 'honda,mazda,toyota' and this doesn't seem very efficient.
I want to insert a option from a dynamic populated MySQL select box, into another table with other form variables. Please excuses all the newbie errors.
This is the area of my form where the select box appears:
<select class="form-control3" name="Select_Name" id="Select_Name">
<?php include('../../controllers/controller1.php') ?>
</select>
This is where it is declared in PHP:
$Select_Item1 = $_POST['Select_Item1'];
$Select_Item2 = $_POST['Select_Item2'];
$Select_Item3 = $_POST['Select_Item3'];
$Select_Item4 = $_POST['Select_Item4'];
$Select_Name = $_POST['Select_Name'];
$insert_movie = mysqli_query($con, "INSERT INTO ".$tbl_name." (Select_Item1, Select_Item2, Select_Item3, Select_Item4, Select_Name) VALUES ('". $Select_Item1."','". $Select_Item2."','". $Select_Item3."','". $Select_Item4."','".$Select_Name."')");
But when I submit the form, everything submits except the $_POST['Select_Name'];
Any help will be greatly valued. Thank you.
can you echo $_POST['Select_Name'] and see what is its value? Maybe you are not doing it right in the <?php include('../../controllers/controller1.php') ?>
Can I see what are you doing on you controller?
Also why dont you pass data from controller like a variable and do a foreach between the select command?
//codeigniter syntax
<select class="form-control3" name="Select_Name" id="Select_Name">
<?php foreach($var as $key):?>
<option value="<?=$key?>"><?=$key?></option>//sth like this
<? endforeach ?>
</select>
i am using the following multiselect box to take input from users, this then gets posted to my php form which adds it to the database, the problem is, all I am getting added is the first selection, if the user selects more than one field I still only get the first field.
If the user selects lets say internet, drawing,maths I want that to be put into the database, at the moment all that is inserted is internet, or whatever is the first thing selected in the list.
My form looks like this >>
<form action="../files/addtodb.php" method="post" style="width:800px;">
<select name="whatisdeviceusedfor[]" size="1" multiple="multiple" id="whatisdeviceusedfor[]">
<option value="games">Games</option>
<option value="takingphotos">Taking Photos</option>
<option value="maths">Maths</option>
<option value="reading">Reading</option>
<option value="drawing">Drawing</option>
<option value="internet">Internet</option>
<option value="other">Other (enter more info below)</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
The php side looks like this >>
<?php
// Implode what is device used for
$usedfor = $_POST['whatisdeviceusedfor'];
$arr = array($usedfor);
$whatisdeviceusedfor = implode(" ",$arr);
// Insert posted data into database
mysql_query("INSERT INTO itsnb_year5questionaire (whatisdeviceusedfor) VALUES '$whatisdeviceusedfor'") or die(mysql_error());
?>
you are already getting array by select so you dont need to use $arr = array($usedfor);this again
just try
$usedfor = $_POST['whatisdeviceusedfor'];
$whatisdeviceusedfor = implode(" ",$usedfor);
or
$usedfor = $_POST['whatisdeviceusedfor'];
$strings ='';
foreach ($usedfor as $item){
$strings .=' '. $item;
}
echo $strings;
and
<select name="whatisdeviceusedfor[]" size="5" multiple="multiple" id="whatisdeviceusedfor[]">
^^
||change to option you want to select
i have changed size="5" so it will select now 5 at a time ...you have only 1 so it will let only 1 select at a time
result
warning
your code is vulnerable to SQL injection also use of mysql_* function are deprecated use either PDO or MySQLi
If you have selected mutliple items via a SELECT or via CHECKBOXES, the form will return an array-like data structure. You will always need to loop over that data and store each item individually into the database or concatenate the values to a string before inserting.
first change size = "5" to see good the list
then try to make like that (its second option if you like it)
if ($_POST) {
// post data
$games = $_POST["games"];
$takingphotos = $_POST["takingphotos"];
.
...
// secure data
$games = uc($games);
$boats = uc($takingphotos);
.
...
}
// insert data into database
$query = "INSERT INTO itsnb_year5questionaire (games, takingphotos,....)
VALUES('$games','$takingphotos',......)";
mysql_query($query) or die(mysql_error());
echo 'Thanks for your select!';
Because $usedfor is contain the array you can directly use it in foreach to save the each value in the value.Try this it may help you:
<?php
$usedfor = $_POST['whatisdeviceusedfor'];
foreach($usedfor as $arr){
mysql_query('INSERT INTO itsnb_year5questionaire(whatisdeviceusedfor) VALUES("'.$arr.'"') or die(mysql_error());
}
I have a selection box and I wish to loop over to add to the database. It looks right to me but it will not enter into the database.
<select name="countylist" style="height:300px;" class="multiple" multiple="multiple" id="box2View">
<option value="11">Beer Gardens</option><option value="10">Historic Bars</option>
<option value="8">Live Music</option><option value="1">Night Clubs</option>
<option value="4">Pubs Serving Food</option><option value="6">Sports Bars</option>
</select>
SQL:
foreach($_POST["countylist[]"] as $s) {
$insertSQL = sprintf("INSERT INTO cat_pubs (pub_id, cat_id)
VALUES(LAST_INSERT_ID(),". $s . ")");
mysql_select_db($database_localhost, $localhost);
$Result1 = mysql_query($insertSQL, $localhost) or die(mysql_error());
}
Thanks
You will need to adjust the name of the select to include the array marker [] like so:
<select name="countylist[]"...
Then in PHP remove the array marker like so:
foreach($_POST["countylist"] as...
What is very important is that in PHP you check the input is actually one of the allowed values and not something the user input themselves maliciously. For selects it may be easiest to hold an array of allowed values and then check against this:
if(!in_array($s, $allowed_counties)) { /*false input, do not save in db*/}
You need to change the name of the select tag to countylist[] so that PHP knows it represents an array:
<select name="countylist[]"/>
What are you trying to do with that LAST_INSERT_ID()?
Have you done an insert before which you are now trying to refer to?
In that case, store the value in a variable because it will be overwritten after your first (new) insert.
Are you trying to have the insert take the next autoincrement?
Then just don't name the column in your insert, or put NULL in the value:
INSERT INTO cat_pubs (cat_id) VALUES(". $s . ")");
PS: You will get hacked by MySQL Injection if you just insert data from POST straight into your DB by building SQL from strings like that. Escape the string, or use a prepared statement...
Some pointers, you need to tell the POST that the value is an array with name="countylist[]" else your only get the last selected value in php.
Also if your doing multiple inserts it is always faster to build a single query for insert compared to iterating over the result and inserting on each iteration.
Your also selecting the database on each iteration which is wrong:
<?php
//connect
mysql_connect('localhost','user','pass');
//select your db
mysql_select_db('database');
//is posted
if($_SERVER['REQUEST_METHOD']=='POST'){
//build query for a single insert
$query = 'INSERT INTO cat_pubs (pub_id, cat_id) VALUES ';
foreach($_POST["countylist"] as $s) {
$query .='("","'.mysql_real_escape_string($s).'"),';
}
//trim the last ,
$query = rtrim($query,',');
}
//do query
$result = mysql_query($query) or die(mysql_error());
?>
<form method="POST" action="">
<!-- tell POST that countylist is an array -->
<select name="countylist[]" style="height:300px;" class="multiple" multiple="multiple" id="box2View">
<option value="11">Beer Gardens</option>
<option value="10">Historic Bars</option>
<option value="8">Live Music</option>
<option value="1">Night Clubs</option>
<option value="4">Pubs Serving Food</option>
<option value="6">Sports Bars</option>
</select>
<p><input type="submit" value="Submit"></p>
</form>
thats ok for an example, I have one remark:
use mysql_real_escape() like
$insertSQL = sprintf("INSERT INTO cat_pubs (pub_id, cat_id) VALUES(LAST_INSERT_ID(),". mysql_real_escape_string($s) . ")");
I have an html form with a select drop down list populated from mySQL, which correctly retrieves and displays the data in select drop down list.
BUT, I can't get the delete.php to work correctly. Here is the script for the select.php and delete.php.
<select name="name">
<?php
while ($line = mysql_fetch_array($result, MYSQL_BOTH)) {
?>
<option value="<?php echo $line['part_no'];?>"> <?php echo $line['part_no'];?> </option>
<?php
}
?>
</select>
delete.php
<?
$name = $_POST['name'];
$query = "delete from cartons_current where name = '".$name."'";
if(mysql_query($query)){
echo "deleted";}
else{
echo "fail";}
?>
Looking at the comments trailing above, it looks like the heckler's will just heckle. Some of us are still learning to program on stack, so I'm going to try to help.
Are you having column select issues - your while loop is not outputting values from the column you want the delete field match to go with?
Your sql query suggests you are polling a match against the name column, but your select dropdown seems about part_no.
Try: DELETE from cartons_current WHERE part_no=...
--
Also, as a first level prevention against SQL injection attacks, try sanitizing all your $_REQUEST field parameters (say, they're called $var) with
$var = mysql_real_escape_string($var)