Prepared Statements PHP mysqli Tutorial

Published :
Author :
Adam Khoury
Prepared statements provide a way to template a query if there is a need to repeat the same query many times with different parameters or values. <?php $mysqli = new mysqli("localhost", "db_user", "db_password", "db_name"); if (mysqli_connect_error()) { echo mysqli_connect_error(); exit; } // The (?,?,?) below are parameter markers used for variable binding $sql = "INSERT INTO people (username, gender, country) VALUES (?,?,?)"; $stmt = $mysqli->prepare($sql); $stmt->bind_param("sss", $u, $g, $c); // bind variables $u = 'Anton'; $g = 'm'; $c = 'Sweden'; $stmt->execute(); // execute the prepared statement $u = 'Tanya'; $g = 'f'; $c = 'Serbia'; $stmt->execute(); // execute the prepared statement again $stmt->close(); // close the prepared statement $mysqli->close(); // close the database connection ?>