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) . ")");
Related
In a select field i have stored three different values of an array .
The $listabrand['0'] contains the ID of the record.
<select name='brands_list'>
<option value="0">Select the Brand</option>
<?php
while ($listabrand=mysqli_fetch_array($brands)){
echo '<option value="'.$listabrand['0'].','.$listabrand['1'].','.$listabrand['2'].'">
'.$listabrand['1'].'</option>';
}?>
</select>
I am implementing the DELETE Record function, selecting the value in the field 'brands_list' but at point it's difficult to me declare the ID into a variable since the brands_list field contains 3 different array values.
I put this but of course can't work because it doesn't know which value have to capture and it should be the $listabrand['0'].
$mod_id = mysqli_real_escape_string ($conn, $_REQUEST['brands_list']);
I embed the full php, it could be helpful
<?php
require '../sys/conn.php';
$mod_id = mysqli_real_escape_string ($conn, $_REQUEST['brands_list']);
if (isset($_GET['delete_brand'])){
$delquery = mysqli_query($conn,"DELETE FROM mg_terms where term_id= $mod_id");
$delquery1 = mysqli_query($conn,"DELETE FROM mg_term_taxonomy where term_id= $mod_id");
$delquery2 = mysqli_query($conn,"DELETE FROM mg_termmeta where term_id= $mod_id");
header('Location: ../pages/success.html');
}
else{header('Location: ../pages/error.html');
}
mysqli_close($conn);
?>
The question is, how to select the ID in the above condition. Suggestions?
Since you're building a comma separated string, you need to break it apart again.
There are a couple of different ways to do this.
If you just want the first part, the id, you can use strtok():
$id = strtok($_REQUEST['brands_list'], ',');
If you want all the parts, you can use explode() and list():
list($id, $part2, $part3) = explode(',', $_REQUEST['brands_list']);
Using the MVC Framework, I have made some code that is meant to add information to the Database.
In Index.php (views)
<form method="post" action="<?php echo URL;?>note/updatetopic">
<select>
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
<input type="submit" name="topic_selection" value="Choose" />
</form>
The Code above is meant to post information about what a user would like to revise.
In note.php (controllers)
public function updatetopic() {
if (isset($_POST['topic_selection'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic_selection']);
}
header('location: ' . URL . 'note');
}
The Code above is meant to get information from the code in index.php and forward it onto the note_model where it runs a function.
In note_model.php (models)
public function updatetopic($topic_selection)
{
$topic_selection = strip_tags($topic_selection);
$sql = "INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id";
$query = $this->db->prepare($sql);
$query->execute(array(':topicselected' => $topic_selection, ':user_id' => $_SESSION['user_id']));
$count = $query->rowCount();
if ($count == 1) {
return true;
} else {
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
}
// default return
return false;
}
This is meant to validate the submitted information and insert it into the database but it outputs:
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
Can someone please help me and tell me what im doing wrong? Thanks.
You are not choosing any name for your select tag:
try like this:
<select name="topic">
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
And now get the the value of yuor drop down list:
if (isset($_POST['topic'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic']);
// $_POST['topic'] == 1 or 2 depends upon selection
}
you can change it like:
<select name="topic">
<option value="coasts">Coasts</option>
<option value="Energy_Demand">Energy Demand</option>
</select>
now u'll get the real value of selected list item and can move further....
Your SQL query will not work as you have tagged mysql which does not support this kind of syntax:
INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id
Basically there is no WHERE in MySQL (MySQL Insert Where query)
You should check for duplicated either in select query, or if there are unique keys - use ON DUPLICATE KEY. Also take a look at the linked topic
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.
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.
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());
}