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().
The index of the $_POST array is always based on the value of the name attribute of any HTML input. Depends on if the form that the select is contained in has the method set to "get" or "post". If <form method="get"> then the value of the select will be located in the super global array $_GET ['taskOption'].
TableName is the specified table holding array values in the database to use MySQL WHERE IN Array. After WHERE clause, specific column name is defined from which the data is retrieved using SELECT statement and from which the IN () function includes the range of values as parameters. How WHERE IN Array works in MySQL?
The index of the $_POST array is always based on the value of the name attribute of any HTML input. Depends on if the form that the select is contained in has the method set to "get" or "post".
The MySQL SELECT Statement The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.
$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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With