How do I change this code so I don't receive the above error?
Here is the full error:
Fatal error: Call to a member function fetch_array() on a non-object in /home/bestc165/public_html/opinuo.com/stream.php on line 10
<?php
$link = mysqli_connect('localhost', 'bestc165_opinuo', 'opinuo');
$sql_string = 'SELECT * FROM debates LIMIT 2 order by ts ';
$result = mysqli_query($link,$sql_string );
while($row = $result->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
$name = $row['name'];
$text = $row['text'];
?>
<h2><?php echo $name;?></h2>
<p><?php echo $text;?></p>
<?php
}
?>
LIMIT
comes after ORDER BY
Change your query to
$sql_string = 'SELECT * FROM debates ORDER BY ts LIMIT 2';
mysqli_query
returns FALSE
on failure so your $result
is not an object but a boolean
thus your error.
Update
As mentioned in the comments, make sure to pass the database name in the connection
$link = mysqli_connect('host', 'username', 'password', 'databaseName');
Or use mysqli_select_db
mysqli_select_db($link, "databaseName");
Use this:
//Other code here
$result = mysqli_query($link, $sql_string );
while($row = mysqli_fetch_assoc($result))
{
?>
<h2><?php echo $row['name'];?></h2>
<p><?php echo $row['text'];?></p>
<?php
}
?>
No need to use extra loop
to show the output.