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_*
Related
I have a network that I am building which groups freelancers together and allows potential customers to browse a profile containing their details.
In my database I store some values that the user will enter via a form using drop down or radio/checkbox fields. Through an edit page they can amend that data.
I'm struggling with how to get those fields pre-populated (if the value exists in the DB) with the value they've already made, probably at the time of creating their profile. I have managed to do it with the regular text/input fields by echoing out the column value as a form field value but can't figure out how to achieve it with these other fields.
UPDATE: I need to pull the value from the database and have the form fields show that as the pre-selected/default entry.
If I leave them blank it means the user will overwrite any existing data with nothing and in erase anything they've entered for that field before.
An example drop down field is below;
<div class="item-content">
<div>Experience</div>
<select class="form-control" name="profile_experience" id="profile_experience">
<option value="1">Amateur</option>
<option value="2">Semi Professional</option>
<option value="3">Professional</option>
</select>
</div>
I'm fetching the values with the following;
<?php
$id=$_SESSION['user']['id'];
$result = $db->prepare("SELECT * FROM profiles WHERE user_id= :userid");
$result->bindParam(':userid', $id);
$result->execute();
for($i=0; $currentprofile = $result->fetch(); $i++){
?>
<!--FORM HERE-->
<?php
}
?>
Retrieve and stote the stored values
<?php
$query = "SELECT id FROM Tablename WHERE YOUR_CONDITION";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$selectedOption = $row['id'];
}
else
{
$selectedOption = ''; // Your default selection of $cc
}
$profile_experience_array = array(1=>'Amateur',
2=>'Semi Professional',
3=>'Professional');
?>
The below code displays all the options of profile_experience_array. $key will check with the database value ($selectedOption) and that text will get selected by default.
<div class="item-content">
<div>Experience</div>
<select class="form-control" name="profile_experience" id="profile_experience">
<option value="0">Select</option>
<?php
foreach ($profile_experience_array as $key => $text)
{
if ($key == $selectedOption)
{
echo '<option value="'.$key.'" selected="selected">'.trim($text).'</option>';
}
else
{
echo '<option value="'.$key.'">'.trim($text).'</option>';
}
}
?>
</select>
</div>
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.
i have searched a lot, but didn't find any solution. i want to save checkbox selected options in SQL. if user selects two check boxes thay must save in MySQL with comma separated.
Kinly please help me in solving this
HTML CODE
<input name="patno" id="patno">
<input type="checkbox" name="newt[]" value="Diesel" id="type" />Diesel
<input type="checkbox" name="newt[]" value="Petrol" id="type" />Petrol
<input type="checkbox" name="newt[]" value="Electricity" id="type" />Electricity
PHP CODE
$order = "INSERT INTO tblsampo
(patno, stno, newt)
VALUES
('$smonth',
'$patno','$stno','$newt')";
$result = mysql_query($order); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
?>
Simply implode the $_POST['type'] array like so....
$types = implode(",", $_POST['type']);
Then insert that $types variable into your table...
So...
$types = implode(",", $_POST['type']);
if($types){
$order = "INSERT INTO tblsampo
(patno, stno, type)
VALUES
('$smonth',
'$patno','$stno','$types')";}
Try this
$types = implode(',',$_POST['type']);
$sql = "INSERT INTO tblsampo
(patno, stno, type)
VALUES
('$smonth',
'$patno','$stno','$types')";
mysql_query($sql)
try the following:
$newt = false;
if (isset($_POST['newt']) && !empty($_POST['newt']) && is_array($_POST['newt'])){
$newt = implode(",", $_POST['newt']);
}
then just run your query same way but check if $myTypes is not false first
if ($newt) {
//YOUR QUERY. TIP: use PDO or MySQLi instead of MySQL_* functions
}
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) . ")");
This is a continuation of the discussion at
PHP Multiple Dropdown Box Form Submit To MySQL
which ended with the words: "Once you have the variables, it is trivial to create new rows." No doubt that's generally true, but apparently not for this learner... :-D
Given the following form:
<form action="form.php" method="POST">
<select name="colors[]" multiple="yes" size="2">
<option>Red</option>
<option>Blue</option>
</select>
<input type="submit" value="Go!">
</form>
how do I create new rows? The following script
foreach($_POST['colors[]'] as $color)
{
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
}
raises the error
Warning: Invalid argument supplied for foreach() in form.php on line ...
whereas the following
$colors = $_POST['colors[]'];
for ($i = 0; $i < count($colors); $i++)
{
$color = $colors[$i];
$sql = "INSERT INTO colors SET id = '$color'";
}
raises no errors but does no row creation.
What triviality am I missing here?
Use:
foreach($_POST['colors'] as $color)
No need to specify [] here, php knows that it is an array.
Inside of your foreach loop I did not see that you are executing the query. You need to execute mysql_query with your INSERT statement.
foreach($_POST['colors'] as $color) {
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
if (!mysql_query($sql)) { // if the query encountered a problem.
die('Invalid query: ' . mysql_error());
}
}