prepared statement using bindValue not working

2019-08-14 04:01发布

I'm new to PHP and I'm trying to get a prepared statement to work. Its for my final year project at university and I remember reading that prepared statements are good practice and also good for SQL injections. However the following code gives me a Server 500 error.

<?php
    $email = "blah@blah.co.uk";
    $hash = "somerandomhashedpassword";
    $db = new mysqli("localhost", "root", "1234", "UEAnetwork");    
    $sql = "INSERT INTO Students (Email, Password) VALUES (?,?)";
    $stmt = $db->prepare($sql);
    $stmt->bindValue(1, $email);
    $stmt->bindValue(2, $hash);           
    if ($stmt->execute()) {
        echo "You have registered!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
    }
?>

If I run the following then a row is inserted, so I'm pretty sure I'm connecting to the database properly.

<?php
    $db = new mysqli("localhost", "root", "1234", "UEAnetwork");    
    $sql = "INSERT INTO Students (Email, Password) VALUES ('blah@blah.co.uk','somerandomhashedpassword')";
    $stmt = $db->prepare($sql);         
    if ($stmt->execute()) {
        echo "You have registered!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
    }
?>

Am I using bindValue incorrectly? I've seen it used this way in many tutorials online but I must be doing something wrong.

1条回答
一夜七次
2楼-- · 2019-08-14 04:47

mysqli has a very different API than PDO. There is no mysql_stmt::bindValue. You want to use mysql_stmt::bind_param, but the syntax is quite different:

$stmt->bind_param('ss', $email, $hash);
查看更多
登录 后发表回答