Home > Article > Backend Development > PHP5 operating MySQL database_PHP tutorial
1. Establish database connection
$mysqli = new mysqli("localhost","root","","mydb");
?>
Four parameters are required to establish a database connection. They are database address, database access user name, database access password, and database name. In addition to using the above constructor method of the mysqli object to establish a database connection, you can also call its connect method to establish a database connection.
$mysqli = new mysqli();
$mysqli->connect("localhost","root","","mydb");
?>
You can also establish a data connection through the construction method of the mysqli object, and specify the database to be accessed through the select_db method.
$mysqli = new mysqli("localhost","root","");
$mysqli->select_db("mydb");
?>
Get the error number of the current connection through the errno attribute of the mysqli object. If there are no errors in the current connection, the error number is returned to 0.
$mysqli = new mysqli("localhost","root","");
$mysqli->select_db("mydb");
if($mysqli ->errno == 0) //Determine whether the current connection is successful
{
}
else
{
echo "The Connection is Error!";
exit();
}
?>
Of course, you can pass the mysqli object The error attribute obtains the error information of the current connection. If there is no error, returns "".
$mysqli = new mysqli("localhost","rootsss","");
$mysqli->select_db("mydb");
if($mysqli ->errno == 0) //Determine whether the current connection is successful
{
}
else
{
echo $mysqli->error; //Output the current error message
exit();
}
?>