php 如何检查值是否已存在于 MySQL 数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8015098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:46:32  来源:igfitidea点击:

How to check if value already exists in MySQL database

phpmysqldatabase

提问by Dustin

Possible Duplicate:
How do I update if exists, insert if not (aka upsert or merge) in MySQL?

可能的重复:
如何在 MySQL 中更新(如果存在),如果不存在则插入(又名 upsert 或 merge)?

I know this is pretty basic.. but for some reason this is not working for me. I have a form that stores a Facebook user's ID to check if they already submitted the form. I have the form that submits the User ID into the database working perfectly. Its just this part of checking if the User ID value exists in the database that is tripping me up.

我知道这是非常基本的......但由于某种原因这对我不起作用。我有一个存储 Facebook 用户 ID 的表单,以检查他们是否已经提交了表单。我有将用户 ID 提交到数据库中的表单工作正常。它只是检查用户 ID 值是否存在于数据库中的这一部分让我感到困惑。

Here's my code....

这是我的代码......

$user_id = 1234567890;

$checkUserID = mysql_query("SELECT fbUserID from submissions WHERE fbUserID = '$user_id'");

if ($checkUserID) {
echo "GTFO BRO";
} 

Whenever I do an "echo" on the $checkUserID variable I get this returned.. "Resource id #9"

每当我在 $checkUserID 变量上执行“echo”时,我都会返回这个值。“Resource id #9”

回答by drew010

mysql_query returns a resource containing the result of the query, you need to use something like this:

mysql_query 返回一个包含查询结果的资源,你需要使用这样的东西:

$user_id = 1234567890;

$checkUserID = mysql_query("SELECT fbUserID from submissions WHERE fbUserID = '$user_id'");

if (!$checkUserID) {
    die('Query failed to execute for some reason');
}

if (mysql_num_rows($checkUserId) > 0) {
    echo "User id exists already.";
    $user = mysql_fetch_array($checkUserId);
    print_r($user); // the data returned from the query
}

回答by dispake

I think you query string is wrong. If you're using double quotes, you'd have to change it to

我认为您的查询字符串是错误的。如果您使用双引号,则必须将其更改为

.... WHERE fbUserId = '{$user_id}'"

or you have to concatenate it

或者你必须连接它

..... WHERE fbUserId = '" . $user_id . "'"

回答by AliMohsin

try the following piece of code:

试试下面的一段代码:

$checkUserID = mysql_query("SELECT fbUserID from submissions WHERE fbUserID = '$user_id'");

while($test = mysql_fetch_array($checkUserID))

if ($test ) {
echo "GTFO BRO";
}

i hope this will work properly for you..

我希望这对你有用..