Home>Article>Backend Development> How to connect to database in php
How to connect to the database in PHP
The first step is to create a connection
$a = mysql_connect("localhost","root","");
The meaning of the parameters in the brackets:
1.localhost - IP address, localhost means the local machine. If you need to connect to another server, you need to enter the IP address of the server you want to connect to.
2.root——Username, the username of the server to be connected to, just write the username saved when creating the server.
3.""——Server password, the password of the server to be connected to. If there is no password, just write nothing within the double quotes, but the double quotes cannot be omitted.
4.$a - If the connection is successful, a MySQL connection ID will be returned or a FALSE will be returned when the connection fails. Since there is a return value, we need to create a variable to receive it.
Related recommendations: "PHP Getting Started Tutorial"
Attachment:
How to quickly change the server password:
1. On the server Select MySQL (MySQL Console) in the menu bar
and click to enter the c# interface:
Here Enter password means please enter the password, please enter the password of the server, if not click the Enter key directly.
##Then enter a sentence after mysql>: mysql>use mysql;——This sentence means which database to choose Press Enter to run Next, you need to write a modification statement:update mysql.user set password = PASSWORD(123) where user = 'root';Modify this mysql.user table, and then set the password to 123, The PASSWORD on the right side of the equal sign here must be in uppercase, otherwise an error will be reported. The password has been changed.
The second step is to select the database to be operated
mysql_select_db("mydb",$a); mydb——the name of the database $a——What to use to connect to the databaseThe third step is to write the SQL statement
$q = "select * from Nation";—— Query all data in the Nation tableThe fourth step is to execute the SQL statement
$w=mysql_query($q);——Call the mysql_query() method to Execute this SQL statement. When it is executed, a result set will be returned. We need to create another variable to receive it. $q——The variable representing the SQL statement $w——The variable that accepts the result setThe fifth step is to read data from the result set
The returned result set can be read using the mysql_fetch_xxx method.while($e = mysql_fetch_row($w)) { var_dump($e); }Example: mysql_fetch_row——Read data one by one from the result set
The above is the detailed content of How to connect to database in php. For more information, please follow other related articles on the PHP Chinese website!