Home > Article > Backend Development > How to connect php file to database
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——User name, the user name of the server to be connected to, just write the user name saved when creating the server
3.""——Server password, the server to be connected to Password, if there is no password, 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 returned when the connection fails. A FALSE, since there is a return value, we need to create a variable to receive it.
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 database
The third step, write the SQL statement
$q = "select * from Nation"
Query all the data in the Nation table
The fourth step, 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 a variable to receive it.
$q——The variable representing the SQL statement
$w——The variable that accepts the result set
The fifth step is to read from the result set Fetching data
The result set returned can be read using the mysql_fetch_xxx method.
while($e = mysql_fetch_row($w)) { var_dump($e); }
Note: When creating the database, select utf-8 as the encoding format.
Recommended tutorial: PHP video tutorial
The above is the detailed content of How to connect php file to database. For more information, please follow other related articles on the PHP Chinese website!