How to include a PHP variable inside a MySQL statement?

Spread the love

Sometimes, we want to include a PHP variable inside a MySQL statement

In this article, we’ll look at how to include a PHP variable inside a MySQL statement

How to include a PHP variable inside a MySQL statement?

To include a PHP variable inside a MySQL statement, we can create prepared statements.

For instance, we write

$first_name = "jane";
$last_name = 'smith'
$query = "INSERT INTO contents (first_name, last_name, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $first_name, $last_name);
$stmt->execute();

to call $mysqli->prepare with $query to create a prepared statement from the string.

The ? symbol is the placeholder for the the values

Conclusion

To iterate over an array in JavaScript, we can use the for-of loop or the JavaScript array forEach method.

We call bind_param with the values we want to replace the ? with in the $query string.

"ss" means both placeholders are strings.

Escaping is done automatically to prevent SQL injection.

Finally, we call execute to run the query.

Conclusion

To include a PHP variable inside a MySQL statement, we can create prepared statements.

Leave a Reply

Your email address will not be published. Required fields are marked *