if I use the following code everything works:
function likecount($id) {
$link = mysqli_connect('localhost', 'root', '', 'printstagram');
$query = $link->query("SELECT likes FROM photos WHERE id='$id'");
$a = mysqli_fetch_row($query);
$b=$a[0];
echo $b;
}
if I use a file called dbconfig.php which has the following code:
$link = mysqli_connect('localhost', 'root', '', 'printstagram');
and then I include dbconfig.php on the php page where I use the likecount function, then uses the global keyword:
function likecount($id) {
global $link;
$query = $link->query("SELECT likes FROM photos WHERE pid='$id'");
$a = mysqli_fetch_row($query);
$b=$a[0];
echo $b;
}
I got an error:mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given.
Can someone tell me where could the error come from? The function is responsible for counting and updating the number of likes. If I use mysqli_connect every time the function is called, I will use mysqli_connect many times in a page, is that an issue? Comparing with global $link, i believe establishing a connection every time the function is called will add more pressure to the server.
I conducted some further testing, for the following code:
<?php
include('dbconfig.php');
global $link;
echo $link;
?>
I got:Catchable fatal error: Object of class mysqli could not be converted to string. Is this considered an ordinary behavior?
I conducted another testing, the following code will work smoothly(but it will establish a connection every time the function is called):
<?php
function likes2($id) {
$link = mysqli_connect('localhost', 'root', '', 'printstagram');
$query = $link->query("SELECT likes FROM photos WHERE pid='$id'");
$a = mysqli_fetch_row($query);
$b=$a[0];
echo $b;
}
?>
but the following doesn't:
<?php
$link = mysqli_connect('localhost', 'root', '', 'printstagram');
function likes2($id) {
global $link;
$query = $link->query("SELECT likes FROM photos WHERE pid='$id'");
$a = mysqli_fetch_row($query);
$b=$a[0];
echo $b;
}
?>
it gives the error: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given