php - prepared statement using bindValue not working

799

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 = "[email protected]";
    $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 ('[email protected]','somerandomhashedpassword')";
    $stmt = $db->prepare($sql);         
    if ($stmt->execute()) {
        echo "You have registered!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
    }
?>

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

945

Answer

Solution:

mysqli has a very different API thanPDO. There is nomysql_stmt::bindValue. You want to usemysql_stmt::bind_param, but the syntax is quite different:

$stmt->bind_param('ss', $email, $hash);

People are also looking for solutions to the problem: php - wrong value is being inserted into the database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.