Question

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.

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top