Home > Article > Backend Development > Detailed introduction to the steps to connect php to the database
This article briefly describes the steps to connect PHP to the database for reference only.
1: Link database
①Host address
②mysql username
③mysql password
④Select Connected database
⑤Port number
mysqli_connect($localhost, $user, $password, $port);
Return: If the connection is successful, the symbol of the resource type is returned; if the connection fails, false is returned.
If we establish more than one connection with mysql, then various functions that operate the database in the future must pass in the returned connection symbol;
If we establish only one connection with mysql, then There is no need to pass in this identifier for various functions that operate the database in the future. Suggestions are passed in.
2: Check whether the database connection is successful?
mysqli_connect_errno()
and mysqli_connect_error()
##mysqli_connect_errno(); Returns the last database connection error The error number, the connection is successful and returns 0
mysqli_connect_error(); Returns the error message of the last database connection
3: Select the database
mysqli_select_db($conn, $dbname);①Identifier ②Connection database nameIf the connection is successful, return true; if the connection fails, return false
4: Set character set encoding Format
mysqli_select_charset($conn, $charset);
5. Write sql statement
$sql = "select * from table_name";
6. Execute sql statement
mysqli_query($conn, $sql);If it is adding, deleting or modifying, a Boolean value will be returned. The number of rows affected by the last operation, if Yes query will be put back into the resource result set. The above content is for reference only. For more related questions, please visit the PHP Chinese website:
The above is the detailed content of Detailed introduction to the steps to connect php to the database. For more information, please follow other related articles on the PHP Chinese website!