MySQL, PHP

Using MySQL Prepared Statements in PHP

A good reason to use prepared statements is to avoid SQL injection without needing to escape data.

Connect

$conn = mysqli_connect("localhost", "user_name", "xxxxxxxx", "dbname");
if ($conn->connect_errno) {
    echo "Connection failed: " . $conn->connect_errno . " - " . $conn->connect_error;
}

New statement

$stmt = $conn->stmt_init();

Execute Prepared Statement

if($stmt->prepare("INSERT INTO `users` (`Username`, `Password`, `Salt`) VALUES (?, ?, ?)")) {
	$stmt->bind_param('sss', $username, $passwd, $salt); //sss -> string string string
	$username = 'JohnDoe';
	$passwd = '3g435g245g45g54h3455h544h2';
	$salt = 'h45534h634GWgewgESgwEgseagGSAEGg4634h634h';
	$stmt->execute();
	$stmt->close();
}
else{
	echo "Prepare failed: " . $conn->errno . " " . $conn->error;
}

Data types – bind_param

i – integer
d – double
s – string
b – blob – binary

Disconnect

$conn->close();