【问题标题】:If statement throwing error before else is readIf 语句在读取 else 之前抛出错误
【发布时间】:2022-11-30 03:24:19
【问题描述】:

试图创建一个基本的 SQL 注册 php 脚本。我被允许注册并将我重定向到登录页面,但重复的电子邮件在 if 语句中给出错误并忽略其他。

我得到的错误:

致命错误:未捕获 mysqli_sql_exception:C:\xampp\htdocs\websiteproject\html\php\signup.php:20 中键“email”的重复条目“test@example.com” 堆栈跟踪:#0 C:\xampp\htdocs \websiteproject\html\php\signup.php(20): mysqli_stmt->execute() #1 {main} throw in C:\xampp\htdocs\websiteproject\html\php\signup.php on line 20

我的代码:

<?php
$password_hash = password_hash($_POST["password"], PASSWORD_DEFAULT);
$mysqli = require __DIR__ . "/database.php";
$sql = "INSERT INTO siteusers (username, email, pass_hash)
        VALUES (?,?,?)";
        
$stmt = $mysqli -> stmt_init();

if (!$stmt->prepare($sql)) {
    die("SQL error: " . $mysqli->error);
}

$stmt->bind_param("sss",
        $_POST["name"],
        $_POST["email"],
        $password_hash);
        
if ($stmt->execute()){
    header("Location: ../loginRegister.php");
} else{
    die($mysqli->error . "" . $mysqli->$errno);
}

任何线索为什么它在 if 语句而不是 else 中出错?谢谢。

【问题讨论】:

    标签: php


    【解决方案1】:

    try/catch 在这里更合适。 MySql 抛出的错误会在它出现的地方破坏脚本,而不是像您预期的那样返回一个虚假值。

    try {
      $stmt->execute();
      header("Location: ../loginRegister.php");
    } catch (Exception $e) {
      die($mysqli->error . "" . $mysqli->$errno);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2017-08-14
      • 2017-10-28
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多