我使用此代码检查条目是否已存在,但似乎查询始终返回true。当我在shell上使用相同的查询时,它可以正常工作。请记住,foodname是主键。
$query = "SELECT EXISTS ( SELECT * FROM Food WHERE foodname = '$food_name')";
$result = pg_query($conn,$query) or die("Query could not be executed");
if($result)
{
echo 'food already exists: ';
echo $food_name;
printf("\n");
}
else
{
echo 'new food inserted';
printf("\n");
$query = "INSERT INTO food VALUES ('$food_name','$food_price','$food_date')";
$result = pg_query($conn,$query) or die("Query could not be executed");
}
问题:我修改它就像'下载下载'所说的那样,它的工作方式也适用于Kettners的答案,但是检查一个条目是否已经存在因为它找到一对时它停止的原因是不是更快?是否有任何使用EXISTS的查询可以在这种情况下工作? Thnx的帮助。
答案:在阅读完所有内容之后,你们说下面的内容是我选择使用的内容,它可以运行并使用EXISTS。$query = "SELECT 1 FROM food WHERE EXISTS ( SELECT * FROM Food WHERE foodname = '$food_name')";
$result = pg_query($conn,$query) or die("Query could not be executed");
$row = pg_fetch_row($result);
if($row[0])
{
echo 'food already exists: ';
echo $food_name;
printf("\n");
}
else
{
echo 'new food inserted';
printf("\n");
$query = "INSERT INTO food VALUES ('$food_name','$food_price','$food_date')";
$result = pg_query($conn,$query) or die("Query could not be executed");
}
答案 0 :(得分:1)
数据库: postgresql
查询:在成功t和失败时给出结果f
输入:布尔值。
您必须更改if条件。
if($result == 't'){
// Your code here
}else {
// Your code here
}
修改:
$result = pg_query($conn, "Your Query");
$rows = pg_num_rows($result);
if($rows != -1){
// Success
}else {
// Fail
}
答案 1 :(得分:1)
试试这个:
$query="SELECT * FROM Food WHERE foodname = '$food_name'";
$result = pg_query($conn,$query) or die("Query could not be executed");
if(pg_num_rows($result )>=1){
echo 'food already exists: ';
echo $food_name;
printf("\n");
}
else{
echo 'new food inserted';
printf("\n");
$query = "INSERT INTO food VALUES ('$food_name','$food_price','$food_date')";
$result = pg_query($conn,$query) or die("Query could not be executed");
}
答案 2 :(得分:1)
pg_query
返回结果资源。您可以使用pg_fetch_row
查询此资源以获取数据。
pg_query
仅返回FALSE。但是,您的声明永远不会失败(只要您可以正确访问数据库和表)。它运行并返回一个值(TRUE或FALSE)。
因此if($result)
始终返回true,并且不会向您提供有关查询结果的任何信息。
这应该有效:执行查询,获取第一行,检查它的第一个(也是唯一的)列。
$query = "SELECT EXISTS (SELECT * FROM Food WHERE foodname = '$food_name')";
$result = pg_query($conn,$query) or die("Query could not be executed");
$row = pg_fetch_row($result);
if($row[0])
{
echo 'food already exists: ';
echo $food_name;
printf("\n");
}
else
{
echo 'new food inserted';
printf("\n");
$query = "INSERT INTO food VALUES ('$food_name','$food_price','$food_date')";
$result = pg_query($conn,$query) or die("Query could not be executed");
}