How to query MySQL from PHP correctly
<?php
/*
1. Connect to the database
2. Prepare statement
3. Process results
4. Close statement
5. Close connection
*/
//Create database connection
$mysqli = new mysqli("localhost", "myuser", "mypass", "mydb");
//Check for connection errors
if (mysqli_connect_errno()) {
//It's not always a good idea to show error text to the user
printf("MySQLi connection error: %s\n", mysqli_connect_error());
exit();
}
//Create prepared statement
if ($stmt = $mysqli->prepare('SELECT `uName` FROM `myusers` WHERE `uId` = ?') {
//Statement is prepared, bind a variable to the query
$stmt->bind_param("d", $varUserId);
if ($stmt->execute()){
//Query executed successfully so bind results to variables
$stmt->bind_result($uName);
while ($stmt->fetch()) {
//Fetch results
echo $uName.'<br />';
}
} else {
//Execute statement issued an error - for example server closed the
//connection unexpectedly
//Again, it's not always a good idea to show error text to the user
printf("MySQLi error: %s\n", $mysqli->error);
}
//Remember to always close the statements or you can have problems later
//This method can also fail (but it would be too formal to treat this kind of errors)
$stmt->close();
} else {
//Prepared statement issued an error - usually query parse errors
//Again, it's not always a good idea to show error text to the user
printf("MySQLi error: %s\n", $mysqli->error);
}
//Close connection - it's not a must but it's a good habit
$mysqli->close();
?>