Psinyee
Psinyee

Reputation: 195

PHP Array to select mysql

I have a whole list of package and I want the user to select using the checkbox and compare the packages. After the user select, I'll use the packages_id which I get from the checkbox array to display all the package data to a .PDF file. How do I separate the array and inject to the mysql select?

output of $_POST['compare']: [14,15,16]

Mysql query:

$packages=mysql_query(" 
select * 
from package 
where id in (" . implode(',', $_POST['compare']) . ") 
LIMIT 4");

Upvotes: 0

Views: 176

Answers (2)

maček
maček

Reputation: 77778

This should work for you

mysql_query("
    select *
    from package
    where id in (" . implode(',', $_POST['compare']) . ")
");

Take proper care to sanitize and validate your inputs

Upvotes: 2

phpmeh
phpmeh

Reputation: 1792

If I understand your question right, you are wanting help with the query.

if( empty( $_POST['compare'] ) )
     // stop execution because they didn't pick anything    

$packages = mysql_query(   
     " SELECT * FROM package WHERE id = '". 
        implode( "' OR id = '", $_POST['compare'] )
        ."'" );

Take a look at https://www.php.net/implode Until you make the change to PDO, this is the best thing ever for writing queries.

You should be aware that you are not sanitizing your query at all. Even though you think you are controlling the value of the checkbox and what goes into the query, it is very easy to fake form data. Therefore, you need to implement a security check.

An easy way to do that would be:

foreach( $_POST['compare'] as $compare ){
    $sql[] = sanitize( $compare );   
}

Obviously you would need a sanitize function. Those are easy to find on SO. And then you can use the $sql instead of $_POST['compare'] in your query.

Upvotes: 0

Related Questions