To do it with MySQLi OOP, you create an object, then call it's query()
method.
$mysqli = new mysqli('hostname','user','password','databasename');
if (!$mysqli) {
// connect failure, check connect_error()
echo $mysqli->connect_error();
}
else {
// Call query() to execute your SQL
$result = $mysqli->query("SELECT * FROM some_table");
if ($result) {
// $result is an object of type mysqli_result
// Call fetch_assoc() on $result
while ($row = $result->fetch_assoc())
echo $row['id'];
}
}
If you have input parameters which you'll pass into your query, escape them with real_escape_string()
$somevar = $mysqli->real_escape_string($somevar);
$mysqli->query("SELECT * FROM sometable WHERE somecolumn='$somevar';");
The principle benefits of MySQLi
over the older mysql_*
API are
- The ability to use prepared statements instead of dynamic SQL strings
- Object-oriented behavior which can be
extend
ed with your own classes.