Dino
Dino

Reputation: 1457

PHP mysqli help with binding var in code block?

I am pretty new to prepared statements, I am currently working through all my code to update it.

I need a bit of help rewriting the following code:

        if($stmt = $db->query("select * from product where active=1 and id=?")){
            echo "Returned Result";
        }else{
            echo "Invalid SQL";
        }

Using this code I need to bind the variable $_POST['id']:

            $stmt->bind_param("s", $_POST['id']);

where would I place the bind to get the whole code block to work?

thanks in advance

Upvotes: 1

Views: 78

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270617

Instead of query() you need to call prepare():

// Prepare the statement first and bind params
$stmt = $db->prepare("select * from product where active=1 and id=?")){
$stmt->bind_param("s", $_POST['id']);

// Then execute it
if ($stmt->execute()) {
    echo "Returned Result";
    // Then fetch your results
} else {
    echo "Query failed";
}

Upvotes: 1

Related Questions