Tutorial by Examples

Object oriented style Connect to Server $conn = new mysqli("localhost","my_user","my_password"); Set the default database: $conn->select_db("my_db"); Connect to Database $conn = new mysqli("localhost","my_user","my_password&q...
The query function takes a valid SQL string and executes it directly against the database connection $conn Object oriented style $result = $conn->query("SELECT * FROM `people`"); Procedural style $result = mysqli_query($conn, "SELECT * FROM `people`"); CAUTION A ...
PHP makes it easy to get data from your results and loop over it using a while statement. When it fails to get the next row, it returns false, and your loop ends. These examples work with mysqli_fetch_assoc - Associative array with column names as keys mysqli_fetch_object - stdClass object with ...
When we are finished querying the database, it is recommended to close the connection to free up resources. Object oriented style $conn->close(); Procedural style mysqli_close($conn); Note: The connection to the server will be closed as soon as the execution of the script ends, unless it...
Please read Preventing SQL injection with Parametrized Queries for a complete discussion of why prepared statements help you secure your SQL statements from SQL Injection attacks The $conn variable here is a MySQLi object. See MySQLi connect example for more details. For both examples, we assume t...
Escaping strings is an older (and less secure) method of securing data for insertion into a query. It works by using MySQL's function mysql_real_escape_string() to process and sanitize the data (in other words, PHP is not doing the escaping). The MySQLi API provides direct access to this function $...
Retrieve the last ID generated by an INSERT query on a table with an AUTO_INCREMENT column. Object-oriented Style $id = $conn->insert_id; Procedural Style $id = mysqli_insert_id($conn); Returns zero if there was no previous query on the connection or if the query did not update an AUTO...
So your query has failed (see MySQLi connect for how we made $conn) $result = $conn->query('SELECT * FROM non_existent_table'); // This query will fail How do we find out what happened? $result is false so that's no help. Thankfully the connect $conn can tell us what MySQL told us about the f...
Prepared statements See Prepared statements in MySQLi for how to prepare and execute a query. Binding of results Object-oriented style $stmt->bind_result($forename); Procedural style mysqli_stmt_bind_result($stmt, $forename); The problem with using bind_result is that it requires the s...

Page 1 of 1