简单的mysql查询以检查行是否存在 [英] Simple mysql Query to check if row exist

查看:101
本文介绍了简单的mysql查询以检查行是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想告诉用户他是否喜欢图片. 为此,我正在创建php代码

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

我无法对标签",分享",评论",收藏夹"等所有内容执行此操作...很多 没有比这更简单的了吗? 就像说$row_check=mysqli_check_exist($table,$column_name,$userid);

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);

推荐答案

确实有很多方法,但是如果您打算使用更多信息,那么用户是否喜欢它,选择*是一个坏主意.原因是您要数据库返回该表中每一列的值.

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.

假设它的数据库很小,不是问题,但是随着数据库变大,您将在数据库上增加更多的负载,那么您需要尝试并仅选择所需的列并打算使用它们.好的,在这种情况下,用户ID可能已被索引并且只有一行,但是如果您习惯在这里进行操作,则也可以在其他位置进行操作.

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.

尝试此操作.

$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

这篇关于简单的mysql查询以检查行是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆