Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing mysql select from $_POST array

Tags:

html

php

mysql

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().

like image 373
Hispanic 100 Avatar asked Aug 17 '16 07:08

Hispanic 100


People also ask

How to get the value of a select in $_post array?

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'].

How do I use where in array in MySQL?

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?

What is the index of $_post array based on?

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".

What is the use of SELECT statement in MySQL?

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.


2 Answers

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

Sanitization is on you :)

like image 167
Hanky Panky Avatar answered Sep 20 '22 17:09

Hanky Panky


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)
like image 37
Passionate Coder Avatar answered Sep 20 '22 17:09

Passionate Coder