gpt4 book ai didi

php - 检查用户名是否存在(PDO)

转载 作者:行者123 更新时间:2023-11-29 17:16:16 24 4
gpt4 key购买 nike

我搜索过与我的问题类似的内容,他们都使用 mysqli当我使用PDO时。 (我不确定它们之间是否有所不同)

if(!empty($_POST['username']) && !empty($_POST['email']) && !empty($_POST['password'])):
if (mysql_num_rows($check_username) != 0):
echo "Username already exists";
else:
$stmt = $conn->prepare($registration_insert);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));

if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
endif;

$check_username其值为

SELECT * FROM users WHERE username='".$username."'"

此代码输出:

Warning: mysql_num_rows() expects parameter 1 to be resource, string given in path:\to\my\wesbite\signup.php on line 15

第 15 行=

if (mysql_num_rows($check_username) > != 0):

最佳答案

mysql_num_rows 用于 mysql_ 驱动程序。 PDO 中的等效函数是 http://php.net/manual/en/pdostatement.rowcount.php但这对于 select 不起作用。

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

执行select count(*)并使用返回值来了解是否有结果。还要参数化该查询。这是基于手册示例 #2 的改编:

$stmt = $conn->prepare('SELECT count(*) FROM users WHERE username= ?');
$stmt->execute(array($username));
if($stmt->fetchColumn() > 0) {
echo 'username already exists';
}

关于php - 检查用户名是否存在(PDO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51581690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com