Connecting to MySQLi
<?php if ($db = @mysqli_connect('localhost', 'user', 'password')) { mysqli_select_db($db, 'hoshmand'); echo 'Connected to the database.'; mysqli_close($db); } else { echo 'Connection failed.'; } ?>
Connecting to MySQL using ext/mysqli
works just like using ext/mysql
, however an i
is appended to the function names.
Keep in mind that the different variable order for mysql(i)_select_db()
is one of the prominent differences between the two extensions. The newer one wants the database handle first. Another difference between these two extensions is that the database handle is a mandatory parameter whenever used. With ext/mysql
, the last handle created by mysql_connect()
is the current default handle for the page. One more difference: mysqli_connect()
accepts the name of the database as an optional fourth parameter, so you can avoid using mysqli_select_db()
.
Alternatively, the mysqli
extension also offers an object-oriented syntax to access a data source. Although this tutorial uses the functional approach to make a transition from ext/mysql
to ext/mysqli
as painless as possible, the following shows what the object-oriented approach looks like:
$db = new mysqli('localhost', 'user', 'password'); $db->select_db('hoshmand'); $db->close();