I have a page where I want to display articles like the one you're reading (randomly chosen articles from same subcategory). I want to use a php script but the server says I have an error. Here is my script:
$article = mysqli_query($con,"SELECT * FROM sources WHERE ID = '$ID'");
while($row = mysqli_fetch_array($article))
{
code which works perfectly
$samecat = $row['Subcategory'];
}
$samecats = explode(', ', $samecat);
foreach($samecats as $similar){
$scat[] = "Subcategory LIKE %".$similar."%";
}
echo implode(' OR ',$scat);
$samearticle = mysqli_query($con,
"SELECT *
FROM sources
WHERE (".implode(' OR ',$scat).")
AND NOT ID='$ID'
ORDER BY Rand()
LIMIT 0,3 ");
while($row2 = mysqli_fetch_array($samearticle))
{
echo "<a href='article.php?ID=".$row2['ID']."'>» "
.$row2['Headline']."</a>";
}
The connection works perfectly because it works with other components but I have bug here :(((
Any alternative solutions will be fine, but I think this way is better.
error is:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result
Here is your problem:
I simulated your code and viewed the sql you're generating. It's like this:
"SELECT *
FROM sources
WHERE (Subcategory LIKE %test% OR Subcategory LIKE %foo% OR Subcategory LIKE %bar% OR Subcategory LIKE %baz%)
AND NOT ID=''
ORDER BY Rand()
LIMIT 0,3 "
You need singlequotes around your terms like:
Subcategory LIKE '%test%'
So you need to:
$scat[] = "Subcategory LIKE '%".$similar."%'";
Really you should enable error reporting for your querying.