I want to extract up to five values from an array and place them in a msql query as such:
$frontpage_hot_list_data = array();
while (@$row = mysql_fetch_array($sql_frontpage_hot_list)) {
$frontpage_hot_list_data[] = $row['id'];
}
$sql_frontpage_hot_down = mysql_query("SELECT * FROM submissions WHERE
id !='$frontpage_hot_list_data[0]' AND id !='$frontpage_hot_list_data[1]' AND
id !='$frontpage_hot_list_data[2]' AND id !='$frontpage_hot_list_data[3]' AND
id !='$frontpage_hot_list_data[4]' AND thumbnail_large=0 AND popular=1 AND
popular_datetime > '$frontpage_hot_hot_three_onlineNowTm' AND
views > '$frontpage_hot_hot_three_views' ORDER BY views DESC LIMIT 4");
The problem here appears to be when I have less than five values, I get the following error:
Notice: Undefined offset: 1 in
D:\Hosting\8847501\html\scripts\timeframes.php on line 298Notice: Undefined offset: 2 in
D:\Hosting\8847501\html\scripts\timeframes.php on line 299Notice: Undefined offset: 3 in
D:\Hosting\8847501\html\scripts\timeframes.php on line 300Notice: Undefined offset: 4 in
D:\Hosting\8847501\html\scripts\timeframes.php on line 301
Any idea how to solve this problem? Maybe placing in the query only the exact number of variables? Im lost…
You can use
implodeto create a comma-separated list of your IDs, then put this newly created list into a MySQLINexpression (UPDATE: now I see that you’re using!=in your query, so let’s make itNOT IN).Important note: I assumed here that your ids are numeric, so
implode()would produce something like1,5,133,31. If they are strings, then you have to wrap them in apostrophes first usingarray_map()for example.Also, if you expect that the array can be empty, you can add another condition that will omit the whole
id NOT IN () ANDpart when necessary.