I have a simple form with the following:
<form action="#" method="post" name="form1" >
<input name="criteria1" size="64">
<input name="criteria2" size="64">
<select name="criteria3[]"multiple="multiple" >
<option value="5 ">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
</form>
Now, if the user selects more then one option from criteria3, how do I insert that in a single database table field as well as insert the other two criteria in their own column?
I have tried many different ways and just get no where. My last attempt was as follows:
$values = array();
$type = explode(",", $_POST['criteria3']);
foreach ($type as $value) {
$values[] = sprintf('(%d)', $value);
}
$values = implode(',', $values);
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO table (name, date, number)
VALUES (%s, %s, '$values')",
GetSQLValueString($_POST['criteria1'], "text"),
GetSQLValueString($_POST['criteria2'], "text"));
Not really sure what is going wrong – have tried several iterations and am getting no where.
Here are the most recent errors:
Warning: explode() expects parameter 2 to be string, array given in /filename.php on line 84
Warning: Invalid argument supplied for foreach() in /filename.php on line 86
Try the following(If you want separate records corresponding to separate values for criteria3 for a single entity):
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
$arr=$_POST['criteria3'];
foreach($arr as $criteria3)
{
$sql="insert into table_name (criteria1, criteria2, criteria3) values('".$criteria1."', '".$criteria2."', '".$criteria3."')";
mysql_query($sql);
}
And if you want a single record for a single entity with multiple criteria3-values use the following code:
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
if(isset($_POST['criteria3'])) //true when at least on of the options is selected.
{
$criteria3=implode(',', $_POST['criteria3']);
}
else //i.e. when no option is selected.
{
$criteria3='';
}
$sql="insert into table_name (criteria1, criteria2, criteria3) values('".$criteria1."', '".$criteria2."', '".$criteria3."')";
mysql_query($sql);
Since I am the only one that will be inserting data - I found a crude work around until I can get the code that Rajesh provided to work - I think this is the right path if I can get it to work.Thanks to all for your input. If I could, I would give you all the up vote!
remove the explode function from $_POST['criteria3'], Because it is already array it not need of explode so you try directly
$type = $_POST['criteria3'];
foreach($type as $k => $v) {
// here do the INSERT query with value $v
}
or if you prefer this link
1).Getting data from a multiple select dropdown with PHP to insert into MySQL
hope this helpful for you :)
<form action="" method="post" name="form1" >
<input name="criteria1" size="64">
<input name="criteria2" size="64">
<select name="criteria3[]" multiple >
<option value="5 ">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
<?php
if(isset($_POST['submit']))
{
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
if(isset($_POST['criteria3']))
{
$query = "insert into table_name (criteria1, criteria2, criteria3) values";
foreach($_POST['criteria3'] as $list)
{
$query .= "('$criteria1','$criteria2','$list')";
}
echo $query;
}
}
?>
Explode only works with a string.
What you get from your form for criteria3 is an array, so you should act accordingly:
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
$criteria3 = implode(",", $_POST['criteria3']);
Here we generate a string based on the content of the table returned by your form.
We seperate each element by a comma.
Then we create the SQL query.
$sql = sprintf("INSERT INTO table (name, date, number) VALUES (%s, %s, %s);", $criteria1, $criteria2, $criteria3);
Hope this helps.
Related
Please help me, I'm inserting the array (11,7,10) into a table.
Now i want to echo this data:
click here to show table
like this structure iwant to make it
<select>
<option value="11">11- HbA1C</option>
<option value="7">10- O"Solivan Test</option>
<option value="10">7- Randam Blood Glucose</option>
</select>
/////////////////////////////////////
table==>
id name date re_doctor sex age no_ana name_pr
11 aaaa 17/04/2017 Female 11,10,7 11- HbA1C,10- O"Solivan Test,7- Randam Blood Gluco.
////////////////////////////////////////////////
my code :-
<?
$qqq=$_GET['n'];
$sql = "SELECT * FROM `profile` where id ='$qqq'"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$array1[] = $row[6]; // get the username field and add to the array above with surrounding quotes
// get the username field and add to the array above with surrounding quotes
$array3[] = $row[7]; // get the username field and add to the array above with surrounding quotes
}
?>
<select> <option>
<?
foreach($array1 as $it=>$ss){
foreach($array3 as $rr=>$vv){
if ($it==$rr) {
echo str_replace(',', '<option value="'.$ss.'">', $vv .'</option>');
}
}
}
?>
</select>
Lets say your data comes in as 11,7,10 from a multiple option or a checkbox as an array
Do a loop from the incoming form data from the array $no_ana at the user form
foreach($no_ana as $key => $value){
mysql_query("INSERT INTO table_name (id, name, date,
re_doctor, sex, age, no_ana, etc)
VALUES ($val1, $val2, $val3, $val4,
$val5, $val6, $value, $etc");
}
insert this code snippet to your script and test it out.
Here is how you do a multiple attribute
<select multiple name="name_pr[]">
<option value="11">11- HbA1C</option>
<option value="7">10- O"Solivan Test</option>
<option value="10">7 - Ramdam Blood Glocose</option>
</select>
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 have the following code used to insert a record using PHP into a MySQL database. The form element is a multiple select that works fine when only one option is selected. When I choose more than 1 option, only the last option is inserted. How do I have the form create a new row for each option selected in the multiple select?
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "InsertForm")) {
$insertSQL = sprintf("INSERT INTO emplikons (EmpNo, IconId) VALUES (%s, %s)",
GetSQLValueString($_POST['insertRecordID'], "text"),
GetSQLValueString($_POST['icons'], "int"));
mysql_select_db($database_techsterus, $techsterus);
$Result1 = mysql_query($insertSQL, $techsterus) or die(mysql_error());
This is the code of the form element. It uses a recordset to dynamically pull values from another table:
<select name="icons" size="10" multiple="multiple">
<?php
do {
?>
<option value="<?php echo $row_icons['id']?>"><?php echo $row_icons['name']?></option>
<?php
} while ($row_icons = mysql_fetch_assoc($icons));
$rows = mysql_num_rows($icons);
if($rows > 0) {
mysql_data_seek($icons, 0);
$row_icons = mysql_fetch_assoc($icons);
}
?>
</select>
add [] to the name of the select, to get an array of all selected values.
<select name="icons[]" size="10" multiple="multiple">
Then, read from $_POST / $_GET... (assuming form method="post")
$sql = '';
foreach ($_POST['icons'] as $icon) {
// no idea where to get EmpNo from, let's assume it is in $empno.
$sql .= "('$empno','$icon'),";
}
$sql = "INSERT INTO tablename (EmpNo, IconId) VALUES " . trim($sql,',');
// Now, please use mysqli_* or PDO instead of mysql_*
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) . ")");