I have an array with values like "849" and "584" or "275" etc and am running a mySQL query against each of these values. It appears to execute fine but I receive no values returned. What am I doing wrong here?
$content = "";
foreach ($cookies_array as $key => $value){
$sql_select_recent_items = $db->query("SELECT id, name FROM products WHERE id=".$key." LIMIT 0,10");
$content .="".$sql_recent_activity_items["id"]." - ".$sql_recent_activity_items["name"]."<br>";
}
When I do a var_dump on the array, it shows correctly like:
array(10) { [0]=> string(3) "852" [1]=> string(3) "856" [2]=> string(3) "720" [3]=> string(3) "783" [4]=> string(3) "784" [5]=> string(3) "785" [6]=> string(3) "708" [7]=> string(3) "716" [8]=> string(3) "717" [9]=> string(3) "749" }
I'm assuming you are using either Mysqli or PDO as the $db.
In both case the result of query() does return a "result class" where you need to fetch the value. It doesn't return a simple array containing your result.
Mysqli fetch: http://php.net/manual/en/mysqli-result.fetch-assoc.php
PDO: http://php.net/manual/en/pdostatement.fetch.php
(There are exemples so it quite easy ;))
So using Mysqli here a sample of what should work:
$content = "";
foreach ($cookies_array as $key => $value)
{
$result = $db->query("SELECT id, name FROM products WHERE id=".$value." LIMIT 0,10");
while ($row = $result->fetch_assoc())
{
$content .="".$row["id"]." - ".$row["name"]."<br>";
}
}
NOTE1: I don't check for error, from documentation $result should be FALSE in those case. NOTE2: You MUST sanitize any parameter you append to your query ESPECIALLY if it come from the client. (A cookie is on the client part). Instead of
"SELECT id, name FROM products WHERE id=".$value." LIMIT 0,10"
it should look like
"SELECT id, name FROM products WHERE id=".$db->real_escape_string($value)." LIMIT 0,10"
NOTE3: I also recommand to batch your query for performance, you could use prepared statement ( http:// php.net/manual/en/mysqli.prepare.php and use bind_param as the sanitize your value or have multiple OR condition in your WHERE)
NOTE4: I use $value in your query instead of $key because like other told you, $key is an index ("unique value" to get back the value from your array)
Change
$sql_select_recent_items = $db->query("SELECT id, name FROM products WHERE id=".$key." LIMIT 0,10");
to
$sql_select_recent_items = $db->query("SELECT id, name FROM products WHERE id=".$value." LIMIT 0,10");
$key
is the index whereas $value
is the actual data on that index.