简体   繁体   中英

Simple mysql Query to check if row exist

I want to show user if he liked a image or not.. for that I am creating 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 not do this for everything like 'tags', 'shares', 'comments', 'favourites' ...many Isn't there anything simpler than this...? Like say $row_check=mysqli_check_exist($table,$column_name,$userid);

use mysql fetch row method

$num_row = mysqli_num_rows($query);

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

There are a lot of ways of doing this really but if you arnt going to use any more information then weither or not the user has liked it doing select * is a bad idea. The reason why is that you are asking the database to return the value of every column in that table.

Assuming its a small database its probably not a problem no but as your database gets bigger you are puting more load on it then you need you should try and only select the columns you need and intend to use. Ok in this case the userid is probably indexed and its only one row, but if you get in the habit of doing it here you may do it else where as well.

try this instead.

$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";
}

This way we are just getting the total. simple and elegant

如果> 0,则使用mysqli_num_rows($ query)

You simply need to count the available records using

mysqli_num_rows($query);

This will return a number (count) of available records

So simple 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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM