- You should refrain from using short tags
<? as they are not supported after PHP 5.4.
- You are not connecting to MySQL (
$link undefined)
- You are using a deprecated API (
mysql_). See comments for alternatives (mysqli_ or PDO)
You should use the REQUEST_METHOD index of $_SERVER to determine whether your script has been posted.
if( $_SERVER[REQUESTED_METHOD] == 'POST' && !empty($_POST['checkbox']) ) {
... }
You need to use error handling to check for errors. If you echo $sql; you would see that the checkboxes aren't being populated:
SELECT * FROM products WHERE id=''
Your script is vulnerable to SQL injection. When you switch to current API, use binded parameters.
- Is
$_POST[checkbox] an array?
sprintf will not work as you intend it to because you are passing the entire $_POST[checkbox] array to it. You would need to iterate through it to format it. (See Ollie's answer)
Example
Assuming your HTML looks like this:
<form method="post" ...>
<input type="checkbox" name="checkbox[]" value="1" />
<input type="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" name="checkbox[]" value="3" />
<input type="submit" name="submit" />
</form>
And all three boxes are checked; it will produce this array:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Following Collie's loop:
foreach ($_POST['checkbox'] as $checkbox) {
$where[] = sprintf(" id='%s'",$checkbox);
}
$where will look like:
Array
(
[0] => id='1'
[1] => id='2'
[2] => id='3'
)
The rest of your script should work. However, you should look into using the IN operator.
That will enable you to skip the loop and just use implode:
$where = "'" . implode("', '", $_POST[checkbox]) . "'";
Which produces:
'1', '2', '3'
And combined with IN:
$sql = "SELECT ... FROM WHERE id IN ($where)";
Be aware that this is not sanitized and you're still vulnerable to injection.
mysql_*functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.$_POST['checkbox']is an array, then you need to loop over it. Otherwise, you are gettingid=Array AND id=Array... Also, seems like those should beORinstead ofAND, in which case they should be in anIN ()clause (after you sanitize against SQL injection)IN ()clause.