How to insert into MySQL from an HTML select multiple
This is my code HTML:
<select name="domaine[]" id="domaine" class="validate[required]" multiple>
<option></option>
<option value="WEB">WEB</option>
<option value="Java2EE">Java2EE</option>
<option value="android">android</option>
<option value="VB.Net">VB.Net</option>
<option value="iOS">iOS</option>
<option value="C++">C++</option>
</select>
This is my php code:
try{
$cdb=new PDO('mysql:host=localhost;dbname=source', 'root','');
} catch (Exception $e){
die("erreur".$e->getMessage());
}
$cin=$_SESSION['cin'];
$rep=$cdb->prepare("insert into dev (cin,comp)values('$cin','".$_POST["domaine"]."')");
$rep->execute();
It's very nice that you're using PDO, but your code is still vulnerable. VALUES takes multiple arguments.
if (isset($_POST['domaine']) && is_array($_POST['domaine'])) {
//(?,?),(?,?),(?,?) for 3 domaine
$values = implode(',', array_fill(0, count($_POST['domaine']), '(?,?)'));
$query = "INSERT INTO dev (cin, comp) VALUES $values";
$params = array();
foreach ($_POST['domaine'] as $d) {
array_push($params, $cin, $d);
}
$rep = $cdb->prepare($query);
$rep->execute($params);
}
You could also prepare a single INSERT statement and loop over execute, but I believe this is more efficient.
$_POST["domaine"] is an array, so puting it "as is" will result as "Array" in your database record.
You need to decide which type of "array->string" method is best for your app and use it before you insert into database.
Easiest way is to use a join($sep, $_POST['domaine']) or serialize($_POST['domaine']).
foreach ( $_POST["domaine"] as $aSelectedOption){
$rep=$cdb->prepare("insert into dev (cin,comp)values('$cin','".$aSelectedOption."') ");
$rep->execute();
}
this will insert an entry for each checked option
you could also use json_encode and json_decode though i wont suggest it.
Related
I have a form with 3 select boxes: age,room,type.
<form action="results.php" method="get">
<div class="form-group">
<select name="age">
<option value>Any</option>
<option value="1">15</option>
<option value="2">25</option>
<option value="3">30</option>
<option value="4">40</option>
</select>
</div>
<div class="form-group">
<select name="room">
<option value>Any</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="form-group">
<select name="type">
<option value>Any</option>
<option value="1">Personal</option>
<option value="2">Business</option>
</select>
</div>
</form>
What i am trying to do with PDO is to make a small search.
If all variables are empty then my condition is:
$search = $db->query("SELECT * FROM table");
If 1 of them (as example the age) is not empty then i have:
if(!empty($_GET['age'])){
$age = $_GET['age'];
$search = $db->query("SELECT * FROM table WHERE age = '$age'");
}
Now, if 2 of them are npt empty i have:
if(!empty($_GET['age']) && !empty($GET['room'])){
$age = $_GET['age'];
$room = $_GET['room'];
$search = $db->query("SELECT * FROM table WHERE age = '$age' AND room = '$room'");
}
In order to avoid all possible search combinations, how can i make a search with the term if is not empty. I had made one in the past:
if(!empty($age)){
$where = "WHERE age = '$age'";
}
if(!empty($room)){
$where .= "and room = '$room'";
}
$query = "SELECT * FROM table $where";
How can i make it happen with PDO?? :/
I'd do something like this:
$param = array();
$query = 'SELECT ... FROM t WHERE 1=1';
if(!empty($_GET['age'])){
$param['age'] = $_GET['age'];
$query .= ' AND t.age = :age';
}
if(!empty($_GET['room'])){
$param['room'] = $_GET['room'];
$query .= ' AND t.room = :room';
}
if(!empty($_GET['type'])){
$param['type'] = $_GET['type'];
$query .= ' AND t.type = :type';
}
$dbh->prepare($query)->execute($param);
You might want to separate out the prepare and the execute. Check the return from the prepare before you try calling execute. Or, configure PDO can throw an exception when an error occurs, e.g.
$dbh->setAttribute(PDO::ERRMODE_EXCEPTION);
You will need to make a query builder of some kind. You will also want to use prepared statements, rather than directly injecting user-provided input into the sql query. That might look something like this:
<?php
$search = [
'age' => 42,
'room' => 'Millyway',
];
$criteria = [];
$params = [];
foreach($search as $field => $value) {
$criteria[] = "$field = :$field";
$params[$field] = $value;
}
$where = ($criteria ? ('WHERE ' . implode(' AND ', $criteria)) : '');
$query = "SELECT * FROM tablename $where";
$stmt = $db->prepare($query);
$stmt->execute($params);
while($obj = $stmt->fetchObject()) {
// iterate over your result set
}
Given search terms as key-values in $search (which can be any column and value in the table, and will need to be populated from wherever those values come from), this code will build $criteria, a set of WHERE clause fragments (using a parameterized sql parameter name, rather than injecting the value directly), and $params, the list of parameters to be passed into the (upcoming) prepared statement.
It then builds the full WHERE clause in $where, by either combining all of the $criteria that were built, or returning an empty string. This is then added directly into the query, and the query is executed using the parameters array that was built up. You then iterate over the result set like any other PDO query.
Among others, the main benefit of using parameterized SQL over injecting variables directly is that it protects you from SQL Injection attacks.
Note that there are many ways this code could be improved. You could easily put it in a function; add complexity to allow for different types of comparisons (e.g. <> or LIKE); even use it as the basis for a more complicated query builder that allows more complicated logic such as ((age = :age AND room = :room1) OR (room = :room2)); and so on. What you do is up to the needs of your application.
I am trying to post the value chosen for a dropdown menu into my database table. But for some reason its not inputting the value into the database. I am trying to post cat_id into my database. So i use the code below to geenrate my dropdown list from values i alrady have in the database. Then below i have the function that inserts the info into the database. But for some reason its not working. I am suppose to put what is in select name="" right?
<select name="cat[<?=$row['pk_id']?>]">
<?php $cat = dbConnect("SELECT * FROM category");
if(empty($row['cat_id'])){
?>
<option value="">Select Category</option>
<?php
}
?>
<?php while($cat_r = mysql_fetch_array($cat)){
if($row['cat_id'] == $cat_r['cat_id']){
?>
<option value="<?=$cat_r[cat_id]?>" selected="selected"><?=stripslashes($cat_r[cat_name])?></option>
<?php
continue;
}
?>
<option value="<?=$cat_r[cat_id]?>"><?=stripslashes($cat_r[cat_name])?></option>
<?php } ?>
</select>
Here is my insert to MySQL
dbConnect("INSERT INTO post_info(add_to_random, show_home, source, display_vote_page, cat_id) values(1,1,1,0,cat[.$row['pk_id'].])");
Did i put something wrong here for the value for cat_id? I put cat[.$row['pk_id'].]) which is the select name="" for that dropdown list.
Code ported from comment:
if($_POST and $_POST['action'] == 'submit'){
foreach($_POST as $k=>$v){
$$k = $v;
}
foreach($cat as $k=>$v){
if($v =='') continue;
dbConnect("UPDATE twit_info set cat_id=" . $v . " where pk_id =". $k );
}
if(count($pkid)>0){
$pid = implode(',',$pkid);
dbConnect("UPDATE twit_info set add_to_vote = 1, display_vote_page = 1 where pk_id in(". $pid .")");
}
}
So in your foreach loop, you are extracting all post keys into global variables via the variable variable $$k (I'll get to this in a second). In your dbConnect() call, the quoting is incorrect. You should concatenate in $cat.
dbConnect("
INSERT INTO post_info
(add_to_random, show_home, source, display_vote_page, cat_id)
values(1,1,1,0, '" . mysql_real_escape_string($cat[$row['pk_id']]) . "')" );
I have added a call to mysql_real_escape_string(). This is necessary at a minimum, to protect all your queries from SQL injection. Your other UPDATE statements are also vulnerable at this point and you MUST perform some escaping on them as well.
Regarding the extraction of $_POST into global variables - I highly recommend against this. You are in effect imitating the behavior of register_globals which is considered very dangerous. The danger comes in that it is possible for anyone to post any key to your form, in addition to the ones you actually expect to receive, potentially initializing another variable in your script to a value sent via $_POST when your script doesn't expect it.
Although I really just recommend operating on $_POST directly, rather than extracting to global variables, if you must extract them to globals, I advise you to use a whitelist of acceptable $_POST keys:
// Make an array of allowed keys
$good_keys = ('action', 'cat', 'otherformkey');
foreach($cat as $k=>$v){
// Only extract if it is one of the allowed keys
if($v =='' || !in_array($k, $good_keys) continue;
// Cast to an integer
$v = intval($v);
$k = intval($k);
// Non-integer strings will cast to zero, so don't do the db action.
if ($v > 0 && $k > 0) {
dbConnect("UPDATE twit_info set cat_id=" . $v . " where pk_id =". $k );
}
// For string values which are quoted in the SQL (unlike the int values above)
// escape them with mysql_real_escape_string()
// $v = mysql_real_escape_string($v)
}
i have a database like this
prod_id prod_name catogory_1 catogory_2 catogary_3
now i want place my filter like this
<slect id="filter for cat 1">
<option vlaue="all">all</option>
<option vlaue="caps">Caps</option>
<option vlaue="shoose">shoose</option>
<option vlaue="cloths">cloths</option>
<option vlaue="bags">bags</option>
</slect>
<slect id="filter for cat 2">
<option vlaue="all">all</option>
<option vlaue="mens">mans</option>
<option vlaue="womens">wonens</option>
<option vlaue="babys">babys</option>
</slect>
<slect id="filter for cat 3">
<option vlaue="all">all</option>
<option vlaue="large">Larg</option>
<option vlaue="midum">midum</option>
<option vlaue="small">small</option>
</slect>
<div id="display_prod_list">
here goes the list
</div>
my function
<?php
function display_product() {
$query = mysql_query("SELECT `pord_id` AS `id`, `prod_name` AS `name`,
`catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`,
`catogory_3` AS `catogory_3` FROM `porducts`");
$products = array();
while(($rows = mysql_fetch_assoc($query))!== false) {
$products[] = $rows;
}
return $pruducts;
}
?>
this function returns all products i want to change this function to return only filtered products
how can i do that? please help me. can i do this with php or i have to use jquery or something. please
tell me the best way to filter my products thanks
I don't know if this is about what you asking for, but hope it helps.
Use a WHERE clause on your MySQL query, for example:
SELECT `pord_id` AS `id`, `prod_name` AS `name`,
`catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`,
`catogory_3` AS `catogory_3`
FROM `porducts`
WHERE catogory_1 = 'caps' AND catagory_2 = 'babys';
You could build your query condition in this way:
$conditions = array();
$condition_string = '';
if ($catagory_1 != 'all') { $conditions[] = "catagory_1 = $catagory_1 "; }
if ($catagory_2 != 'all') { $conditions[] = "catagory_2 = $catagory_2 "; }
if ($catagory_3 != 'all') { $conditions[] = "catagory_3 = $catagory_3 "; }
if ($conditions) { $condition_string = ' WHERE '. implode($conditions, ' AND '); }
$sql =
"SELECT `pord_id` AS `id`, `prod_name` AS `name`,
`catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`,
`catogory_3` AS `catogory_3`
FROM `porducts` $condition_string ";
Just PHP
A standard HTML form that sumbits to the php script which executes query based on the filter values when the submit button is pressed.
The use the SQL WHERE clause to narrow down your results to products that match the criteria.
eg. WHERE catogory_1 = 'caps' AND catagory_2 = 'babys';
You will also need to put some logic in the php to prevent you from querying for a category when the filter value is 'all', as you can effectively ignore those categories.
Then output your results.
PHP & jQuery
You could use jQuery to populate the products part of the page with only the products that match the category filters when a filter is changed rather than reloading the page. A ajax request is made to the a php script that queries based on the current filters.
For example, all products are shown when your page loads at first then the "filter for category 1" is changed to "caps", using jQuery to detect a change event on the filter an ajax call to a php script that would run the following query.
SELECT `pord_id` AS `id`, `prod_name` AS `name`,
`catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`,
`catogory_3` AS `catogory_3`
FROM `porducts`
WHERE catogory_1 = 'caps';
Then build your HTML based on the results and this is sent back as the ajax response and you should use it to replace the current HTML for the products.
I'm making a simple online store like program. What can you suggest that I would do so that I can loop through the inputs I've made in my program.
I'm still using get so that I could see how the data looks like, I'll change it to post later.
This is what the url looks like, when I commit the buying of all the products added in the cart:
http://localhost/pos/php/checkout.php?ids=2;&qoh=12;&qbuys=&ids=6;&qoh=2304;&qbuys=304&ids=4;&qoh=699;&qbuys=99
This is the code that I'm using to commit only one product, it doesn't work when I had something like in the above url:
<?php
$id=$_GET['ids'];
$qtyhnd=$_GET['qoh'];
$qtytbuy=$_GET['qbuys'];
$left=$qtyhnd-$qtytbuy;
if($qtyhnd>=$qtytbuy){
$update=query_database("UPDATE prod_table SET QTYHAND='$left' WHERE PID='$id'", "onstor", $link);
}
?>
Please comment if you need more details,thanks
Either convert the parameters to array parameters (e.g. qoh[]) and then iterate in parallel, or parse the query string manually.
You have semicolons after some values maybe you should pass just the integer this are qoh and qbuys.
Apart of that you should use mysql_real_escape_string() and (int) before integer values to prevent SQL injection e.g.:
$int = (int)$_GET['price'];
$string = $_GET['val'];
mysql_real_escape_string($string);
Also if you want to pass multiple values you have to use array for them:
HTML
<input type="hidden" name="ids[]" value="1">
<input type="hidden" name="ids[]" value="2">
<input type="hidden" name="ids[]" value="3">
PHP
$ids = $_GET['ids'];
foreach($ids as $id) {
$sql = 'UPDATE table SET field=? WHERE id='.(int)$id;
....
}
You can use the $_SERVER['QUERY_STRING'] with foreach loop like this:
foreach($_SERVER['QUERY_STRING'] as $key => $value){
echo "$key - $value <br />";
}
This way you can get the values of GET and use in your database query in similar fashion using foreach loop.
I assume that PID in prod_table is of integer type. Doesn't $id variable contain "2;" instead of 2? Anyway, what kind of error do you get?
Have your url like
http://localhost/pos/php/checkout.php?ids[]=2&qoh[]=12&qbuys[]=&ids[]=6&qoh[]=2304&qbuys[]=304&ids[]=4&qoh[]=699&qbuys[]=99... using a HTML structure like infinity pointed out.
Then:
foreach ($_GET['ids'] as $k => $v) {
$id = (int)$v;
$qtyhnd = (int)$_GET['qoh'][$k];
$qtytbuy = (int)$_GET['qbuys'][$k];
$left = $qtyhnd - $qtytbuy;
if ($qtyhnd >= $qtytbuy) {
$update = query_database(
"UPDATE prod_table SET QTYHAND='$left' WHERE PID='$id'",
"onstor",
$link);
}
}
And if the database type of QTYHAND and PID are int, exclude single quotes (') from your SQL queries.
$test=$_POST['Cities'];
foreach ($test as $t){
$query .= " AND u.bostadsort = \'".$t."\'";
}
I have this for my
<select size="6" name="Cities[]" multiple="multiple">
<option value="">All</option>
<option value="1">C1</option>
<option value="2">C2</option>
<option value="3">S3</option>
<option value="4">S4</option>
<option value="5">S5</option>
</select>
But its not right at all.
What I'm trying to do is when you pick the cities(in the search form), it puts all the values into an array.
Now I would like to have it write like this, if you e.g pick 2, 4, 5
AND u.bostadsort = '2' OR u.bostadsort = '4' OR u.bostadsort = '5'
(maybe you could do this easier to, but this is the only way i know, using "OR")
So if you picked more than 1 then it should be OR, instead of the AND i got.
Maybe I done it in a wrong way, and there is a better method doing this than foreach..
How can I do this?
You could use IN instead, which lets you supply multiple values:
if (is_array($_POST['Cities']))
{
// If multiple values were selected, handle them
$cities = array();
foreach ($_POST['Cities'] as $city)
{
if (!empty($city))
{
$cities[] = mysql_real_escape_string($city);
}
}
}
elseif (!empty($_POST['Cities']))
{
// ... or was a single, non-empty value passed in?
$cities = array(mysql_real_escape_string($_POST['Cities']));
}
if (count($cities))
{
$query .= " AND u.bostadsort IN ('" . join("', '", $cities) . "')";
}
Note that I am passing each value through mysql_real_escape_string before using it in the query; this is done to prevent SQL injection. If you are not using MySQL, the other RDBMSes have similar functions.
See http://www.ideone.com/UVXuu for an example (ideone doesn't seem to have mysql enabled, so the calls to mysql_real_escape_string are removed).
Alternately, you could use PDO's prepare and execute methods:
$cities = $_POST['Cities'];
if (count($cities))
{
$query .= " AND u.bostadsort IN (?" . str_repeat(', ?', count($cities) - 1) . ")";
}
// $db is a PDO object
$stmt = $db->prepare($query);
$stmt->execute($cities);
(Of course, this solution ignores how you build the rest of your query because you don't give it in your question, so you'd want to parameterize the other parts as well.)