gpt4 book ai didi

php - 准备好的语句检查行是否存在

转载 作者:可可西里 更新时间:2023-10-31 22:51:26 24 4
gpt4 key购买 nike

我是 Php 中准备好的语句的新手,并且想知道您最好如何检查一行是否已经存在,因为我在这个阶段似乎感到困惑:

<?php 
include '../config.php';

$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);

if(mysqli_num_rows($stmt) > 0) {
$email = $_POST['email'];
$password = $_POST['password'];
$stmt->execute();
header('Location: ../login.php');
} else {
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>

上面返回了 else 语句,如果我将它们切换过来,它会再次插入使用 else 语句并插入记录但仍然不检查。

**更新**

这是我更新后的代码,供您在下面的帮助后查看。

<?php 
include '../config.php';

ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);

$email = $_POST['email'];
$password = $_POST['password'];

$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =?");
$stmt_check->bind_param("s", $email);
$stmt_check->execute();
if($stmt_check->num_rows > 0) {
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
// header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>

最佳答案

mysqli_num_rows 适用于 SELECT 语句。

$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
if(mysqli_num_rows($stmt_check) > 0)

更新代码

<?php 

include '../config.php';

$email = $_POST['email'];
$password = $_POST['password'];

$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
if($stmt_check->num_rows > 0){
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
header('Location: ../login.php');
}

$stmt->close();
$conn->close();
?>

快速链接

哪个州,

This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

编辑 1

改变

if(mysqli_num_rows($stmt_check) > 0){

if($stmt_check->num_rows > 0){

参见 PHP mysqli_num_rows() FunctionExample2

关于php - 准备好的语句检查行是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41440464/

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