Constructing mysql select from $_POST array - php

This is the $_POST array from my form.
Array ( [prescribedid] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 13 )
I want to create a select for any of items in the Array. I have written this, which produces the proper SELECT, but the if() to eliminate a trailing OR makes it clunky.
$query = "SELECT * ";
$query .= "FROM prescribed WHERE ";
for($i=0; $i<count($_POST["prescribedid"]); $i++) {
$query .= "prescribedid={$_POST['prescribedid'][$i]} ";
if($i < (count($_POST["prescribedid"])-1)) {
$query .= "OR ";
}
}
It produces this:
SELECT * FROM prescribed WHERE prescribedid=1 OR prescribedid=2 OR prescribedid=3 OR prescribedid=9 OR prescribedid=13
Is there another way to group the SELECTS or write the FOR() to make it cleaner, i.e. without the last IF().

$values=implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($values)";
Sanitization is on you :)

Hi You can Use In condition. use imploade function to find comma seoarated values
$data = array('prescribedid'=>array(1,2,3,9,14));
$query = 'SELECT * FROM prescribed WHERE prescribedid IN (';
$query .= implode(',',$data['prescribedid']).')';
echo $query ;
Output
SELECT * FROM prescribed WHERE prescribedid IN (1,2,3,9,14)

Use MySQL IN clause
$ids = implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($ids)";

You can simply use IN clause here.
Refer to MySQL IN clause
$query = "SELECT * FROM prescribed WHERE prescribedid IN ".implode(',', $_POST["prescribedid"]);

Related

How to use PDO prepared statements with IN clause? [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 1 year ago.
I stored some data in a field inside MySQL in this format: 1,5,9,4
I named this field related. Now I want to use this field inside an IN clause with PDO. I stored that field contents in $related variabe. This is my next codes:
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (?) LIMIT 4";
$q = $db->prepare($sql);
$q->execute(array($related));
echo $q->rowCount();
But after executing this code, I can fetch only one record whereas I have to fetch 4 records (1,5,9,4). What did I do wrong?
using named place holders
$values = array(":val1"=>"value1", ":val2"=>"value2", ":val2"=>"value3");
$statement = 'SELECT * FROM <table> WHERE `column` in(:'.implode(', :',array_keys($values)).')';
using ??
$values = array("value1", "value2", "value3");
$statement = 'SELECT * FROM <table> WHERE `column` in('.trim(str_repeat(', ?', count($values)), ', ').')';
You need as many ? placeholders as your "IN" values.
So:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$questionmarks = "";
for($i=0;$i<count($related);$i++)
{
$questionmarks .= "?,";
}
$sql .= trim($questionmarks,",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/No4h1
(also if you want 4 records returned get rid of the LIMIT 3)
More elegantly you can use str_repeat to append your placeholders like this:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$sql .= trim(str_repeat("?,",count($related)),",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/qot2k
Also, by reading again your question i can guess that your $related variable is just a string with value comma-separated numbers like 1,40,6,99. If that's the case you need to make it an array. do: $related = explode($related,","); to make it an array of numbers. Then in your execute method pass $related as-is.

Build dynamic WHERE clause in mySQL

I have this code and it works great, if I just want to search by office name. However I need to be able to search by "Office and/or First Name and/or Last Name", any combination of the three.
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$officeName = $_POST ["officeName"];
$query = "SELECT
e.*,
e.id emp_id,
o.*
";
$query .= "FROM
employee_data e,
office o,
employee_office_pivot p
";
$query .= "WHERE
1=1
AND e.id=p.employee_id
AND p.office_id=o.id
AND o.office_name= '".$officeName."'
";
How can I build the WHERE clause, so that it will accept any of the three columns, or none if they are null.
Thanks,
Richard
Something like this?
$query .= "WHERE
1=1
AND e.id=p.employee_id
AND p.office_id=o.id
AND (o.office_name= '".mysqli_real_escape_string($officeName)."'
OR o.office_name= '".mysqli_real_escape_string($firstName)."'
OR o.office_name= '".mysqli_real_escape_string($lastName)."')
";
I used mysqli_real_escape_string() here as an example, you should use the correct and necessary precautions to avoid SQL injection in your system.
You can use arrays to dynamically construct your SQL:
/**
* The items you expect to receive from $_POST. I prefer defining these ahead of time - when feasible -
* so that you can reference them without worrying about throwing an error if they are not set.
*/
$options = array_fill_keys(array('firstName', 'lastName', 'officeName'), false);
$post = array_merge($options, $_POST);
/**
* Your base SQL query.
*/
$sql = 'SELECT ...columns... FROM ...tables... WHERE 1 = 1';
$where = array();
/**
* If $_POST items are present, sanitize and create SQL
*/
if ( $post['firstName'] ) {
$where[] = "employee_first_name = '".mysqli_real_escape_string($post['firstName'])."'";
}
if ( $post['lastName'] ) {
$where[] = "employee_last_name = '".mysqli_real_escape_string($post['lastName'])."'";
}
if ( $post['officeName'] ) {
$where[] = "office_name = '".mysqli_real_escape_string($post['officeName'])."'";
}
/**
* One or more $_POST items were found, so add them to the query
*/
if ( sizeof($where) > 0 ) {
$sql .= ' AND '.implode(' AND ', $where);
}
You can use the same technique to dynamically add columns, joined tables, etc. to the SQL. (Hint: build the entire SQL statement using an array.) You can also very easily modify this to use combinations of AND and OR.
$values = array(
'firstName' => 'someFirstName',
'lastName' => 'someLastName',
'officeName' => 'someOfficeName'
);
foreach( $values as $col => $val )
{
$where .= "$key = '$balue' ";
}
Though this is SQL injection vulnerable.

mysql SELECT a whole column or cycle through all IDs

I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";

Mysql Query from an array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
MySQL query using an array
How to use an array of values from PHP in the 'IN' clause of mysql query?
from a Post form i have an array like that
Array
(
[userid] => Array
(
[0] => 4e8329e97231c
[1] => 4e64b47849318
[2] => 4e4e415a30000
)
)
i am little struggle to retrieve the users data from mysql from this array
that should be something like this :
SELECT * FROM user_detail WHERE user_id='4e64b47849318' OR user_id='4e8329e97231c' OR user_id='4e4e415a30000'
Use implode().
$yourArray = array_map("mysql_real_escape_string", $yourArray);
$query = "SELECT * FROM user_detail WHERE user_id='";
$query .= implode($yourArray, "' OR user_id='");
$query .= "'";
Or indeed, use the SQL IN keyword:
$yourArray = array_map("mysql_real_escape_string", $yourArray);
$query = "SELECT * FROM user_detail WHERE user_id IN ('";
$query .= implode($yourArray, "','");
$query .= "')";
$clean_userid = array_map('mysql_real_escape_string', $arr['userid'])
$str_user_id = "'" . implode("', '", $clean_userid ) . "'";
$sql = "SELECT * FROM user_detail WHERE user_id IN ( $str_user_id )";
You can use the MySQL IN operator nicely here, it works like "OR" but you can essentially give it a list.
$user_id_string = implode(',', $array['userid']);
You now have a comma separated string of your user_id's.
Now query something like:
SELECT * FROM user_detail WHERE user_id IN ($user_id_string);
$criteria = "'".implode("','",$userID)."'";
$sql = "select * from user_detail where user_id in ($criteria)";
$query="SELECT * FROM user_detail
WHERE user_id='".(intval) $array['userid'][0]."'
OR user_id='".(intval) $array['userid'][1]."'
OR user_id='".(intval) $array['userid'][2]."'";
You could try
"SELECT * FROM user_detail
WHERE user_id IN ('". implode("','", $array['userid'])."')"

how to get values of array out

I have this array
$pv->orderRecordsArray = array();
foreach($order->records as $i=>$orderRecord){
$pv->orderRecordsArray[] = $orderRecord->orderRecordID;
}
// print_r($pv->orderRecordsArray) for example
// shows Array ( [0] => 46839 [1] => 46840 [2] => 46841 )
I need to use the array values from above in my sql statement below.
$sql = "
SELECT
*
FROM
table1
WHERE
orderRecordID IN (46741, 46742)
";
so infront of IN I want $pv->orderRecordsArray results.
thanks
You can use implode to generate such a list:
$sql = "SELECT *
FROM table1
WHERE orderRecordID IN (" . implode(', ', $pv->orderRecordsArray) . ")";
But you should also consider a subquery or Join of your tables.
$sql = 'SELECT *
FROM table1
WHERE orderRecordID IN ('.implode(',',$pv->orderRecordsArray).')';

Categories