简体   繁体   中英

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");

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

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 http://us3.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM