检查是否存在具有给定值的行 [英] Check if a row with given values exists
问题描述
我有一个查询供用户在我的应用程序中创建关注者/关注关系:
I have a query for users to create a follower / following relationship within my application:
INSERT INTO following(IdUser,followingID) VALUES('%d','%d')", $id, $followingId
要查询两个用户之间是否存在关系的查询是什么?
What would be the query to check if a relationship between two users already exists?
或者,如何检查两个用户之间的关系是否不存在?
Or, how do I check if a relationship between two users doesn't exist?
通常,我将结果返回到iOS应用程序中,如下所示:
Typically, I return the results in an iOS application like so:
if (!$result['error']) {
// if no error occured, print out the JSON data of the
// fetched photo data
print json_encode($result);
} else {
//there was an error, print out to the iPhone app
errorJson('Follow is broken');
}
任何帮助将不胜感激.
推荐答案
您必须为此进行交易.
首先执行选择.
SELECT * FROM following where idUser = $id AND followingID = $followingId
现在,如果上面的查询选择了一个或多个行,则已经存在一个关系,如果没有行(零行),那么就没有关系.对于这两种情况,都应采取相应的措施.
Now if above query selects one or more rows then there already exists a relation and if no row (zero rows) then there is no relation. For both situations take action accordingly.
确保根据PHP和SQL语法使用查询.如果ID为char或varchar,则在查询中应将它们用单逗号或双逗号括起来.
Make sure to use the query according to PHP and SQL syntax. If ID's are char or varchar then in query these should be surrounded by single or double commas.
赞: 如果ID为varchar或char,则
Like this: if ID's are varchar or char then
$query = "SELECT * FROM following where idUser = '".$id."' AND followingID = '". $followingId."'";
以及ID是否为int或任何其他数字值(根据表的列)
and if ID's are int or any other digit values (according to column of table)
$query = "SELECT * FROM following where idUser = ".$id." AND followingID = ". $followingId."";
还要确保我使用的列名和表名正确.
Also make sure the column names and table name I've used are correct.
现在让我们首先执行查询
Now let's first execute the query
$result = mysql_query($query); // this method works but is not preferred. better if insert query here instead of variable $query
现在,让我们检查一下已选择了多少行并采取适当的措施.
Now let's check how many rows it has selected and take appropriate action.
if(mysql_num_rows($result) > 0){
//do something here or show error because relation already exists
}
else{
//relation already do not exists. so you can insert the record here
}
注意::自PHP 5.5.0起不推荐使用mysql_query和mysql_num_rows函数.因为我很早以前就用php编写代码,所以我现在记得这些.您可以在php网站上找到替代方法.但是这些功能仍然有效. http://php.net/manual/zh/function.mysql-query.php 和 http://php.net/manual/en/function.mysql-num -rows.php
NOTE: the functions mysql_query and mysql_num_rows are deprecated as of PHP 5.5.0. Because I coded in php long ago, so I remember these right now. Alternate you can find on php website. But these functions still work. http://php.net/manual/en/function.mysql-query.php and http://php.net/manual/en/function.mysql-num-rows.php
这篇关于检查是否存在具有给定值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!