A simple mysql query to check if a row exists

I want to show the user whether he liked the image or not. for this i create php code

$userid=$_COOKIE['userid'];
$sql = "SELECT * FROM likes WHERE `user_id`='{$userid}'"; 
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
if($row){
echo "unlike";
}
else{
echo "like";
}

I can’t do it for everything like “tags”, “promotions”, “comments”, “favorites” ... many Isn’t there anything easier than that? For example,$row_check=mysqli_check_exist($table,$column_name,$userid);

+4
source share
4 answers

There are many ways to do this in fact, but if you are going to use any additional information, then we or not, the user liked what select * is a bad idea. The reason is because you are asking the database to return the value of each column in this table.

, , , , , . , , , , , , .

.

$userid=$_COOKIE['userid'];
$sql = "SELECT count(user_id) as total FROM likes WHERE `user_id`='{$userid}'"; 
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);

if( $row ['total'] > 0){
    echo "unlike";
}
else{
    echo "like";
}

, .

+2

mysql fetch

$num_row = mysqli_num_rows($query);

if($num_row>0)
{
//add your code
} 
else
{
//add your code
}
+3

mysqli_num_rows ($ query), > 0

+1

,

mysqli_num_rows($query);

This will return the number (s) of available records.

So just put a check like this:

$userid=$_COOKIE['userid'];
$sql = "SELECT * FROM likes WHERE `user_id`='{$userid}'"; 
$query = mysqli_query($conn, $sql);
$count = mysqli_num_rows($query); 


if($count>0){
echo "unlike";
}
else{
echo "like";
}
0
source

All Articles