连接数据库中的准备语句

时间:2017-06-18 12:51:33

标签: php sql statements

我正在尝试使我的网站免受sql注入。所以我决定更改我的代码并用准备好的语句替换它。我想我在下面的代码中做了一个小错误。

<?php
session_start();


$host= 'localhost';
$user='root';
$pass='';
$db='gameforum';


$conn= mysqli_connect($host, $user, $pass, $db);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
}

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

    if ($password!==$rpassword) {
$_SESSION['err']="Passwords did not match, please try again!";
header("Location: index.php");
    $conn->close();
}
else {
    $stmt = $conn->prepare("INSERT INTO users (username, password, rpassword, email) VALUES (?, ?, ?, ?)");
    if(!$stmt){
            echo "false";
    }else {
    $stmt->bind_param("ssss", $username, $password, $rpassword, $email);
      if ($stmt->execute === TRUE) {
       $redirectUrl = 'index.php';

   $_SESSION['registrationsuccessful']="Your account was successfully created! You may now log in to your account.";
   header("Location: index.php");
}else{
    $_SESSION['alreadyexists']="Username or email already exists!";
header("Location: index.php");
    $stmt->close();
    $conn->close();
  }
$stmt->close();
$conn->close();
}
    }

我现在面临的问题是我收到了消息&#34;用户已经存在&#34;当我尝试创建一个实际上不存在的帐户时。谢谢!

3 个答案:

答案 0 :(得分:0)

您已经执行了execute语句。删除其中一个。或者,只检查一个执行语句

是否成功

答案 1 :(得分:0)

我认为问题的原因是$stmt->execute()的第二次使用 - 但可以对代码进行一些其他修改。

如果初始逻辑if ( $password!==$rpassword )测试成功,则创建数据库连接〜否则看起来毫无意义。我会使用一个会话变量而不是3 - 它可以更容易在其他页面上检查值。

将第一个$stmt->execute()的结果分配给变量,并在需要时在进一步的逻辑测试中使用该变量。

对于错误消息 - 显示用于开发的详细错误消息但从未在生产中显示(确实更可取) - 因此删除了$conn->connect_error

另一件事,混合使用proceduralobject orientated代码可能不是一种好的做法 - 更好地坚持一个或另一个(我认为OO更容易)

<?php
    session_start();

    $username = $_POST['username'];
    $password = $_POST['password'];
    $rpassword = $_POST['rpassword'];
    $email = $_POST['email'];
    $_SESSION['registration_status']="";

    if ( $password!==$rpassword ) {
        $_SESSION['registration_status']="Passwords did not match, please try again!";
        exit( header( "Location: index.php" ) );

    } else {

        $host= 'localhost';
        $user='root';
        $pass='';
        $db='gameforum';


        $conn= mysqli_connect($host, $user, $pass, $db);
        if( $conn->connect_error ) die( "Connection failed" );


        $stmt = $conn->prepare("INSERT INTO users (`username`, `password`, `rpassword`, `email`) VALUES (?, ?, ?, ?)");
        if( $stmt ){

            $stmt->bind_param("ssss", $username, $password, $rpassword, $email);
            $result = $stmt->execute();

            /* use the return value from stmt->execute() */
            $_SESSION['registration_status'] = $result ? "Your account was successfully created! You may now log in to your account." : "Username or email already exists!";

            $stmt->close();
        }

        $conn->close();

        exit( header( "Location: index.php" ) );
      }
    }
?>

答案 2 :(得分:0)

你可以试试这个,

<?php
// if session not start, start now
!session_id() ? session_start() : null;
$mysql_server = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_db = "gameforum";
// connect db connection
$conn = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
// chck if connection has error
if ($conn->connect_errno) {
    printf("Connection failed: %s \n", $conn->connect_error);
    exit();
}
// db encoding
$conn->set_charset("utf8");
// when POST happen
if (isset($_POST) && !empty($_POST)) {
    // convert POST array key as PHP variable
    extract($_POST);
    // if password matched with confirm password
    if ($password === $rpassword) {
        // create insert query with prepare
        $stmt = $conn->prepare("INSERT INTO users (username, password, rpassword, email) VALUES (?, ?, ?, ?)");
        // if prepare fine, there is no query or mysql error
        if ($stmt) {
            // bind real values
            $stmt->bind_param("ssss", $username, $password, $rpassword, $email);
            // if query executed
            if ($stmt->execute()) {
                // success message & redirect
                $_SESSION['registrationsuccessful'] = "Your account was successfully created! You may now log in to your account.";
                header("Location: index.php");
                exit();
            } else {
                // query error & redirect
                $_SESSION['alreadyexists'] = "There was an error or Username/Email already exists!";
                header("Location: index.php");
                exit();
            }
        }
    } else {
        // password matched failed
        $_SESSION['err'] = "Passwords did not match, please try again!";
        header("Location: index.php");
        exit();
    }
}

我没有关闭连接,因为PHP将关闭脚本末尾的所有打开的文件和连接。