Home > Article > Backend Development > PHP connects to the database to implement simple queries
Hoho, just learned, record it~
1. First create a new database, create a new data table test in it, and insert two records as shown in the picture
2. Create a new php file.
Code to connect to the database:
$conn=mysql_connect("localhost","root","");//连接数据库服务器 if (!$conn){ die('Could not connect: ' . mysql_error()); } mysql_select_db("mytest",$conn);//选择数据库mytetst mysql_query("set names utf8");//设置编码格式
mysql_connect(servername,username,password);
servername | optional. Specifies the server to connect to. The default is "localhost:3306". |
username | Optional. Specifies the username to log in with. The default value is the name of the user who owns the server process. |
password | Optional. Specifies the password to use for login. The default is "". |
3. Execute database statements, such as query statements
$arr=mysql_query("select * from test",$conn);
Output query results
while($row = mysql_fetch_array($arr)){ echo $row['id'] . " " . $row['num']; echo "<br />"; }
—————————————————————————— ——————————————
Implementation results:
When you click to find all, it displays:
When you search by id, enter 1 and it displays:
Complete code:
The above introduces how to connect PHP to the database to implement simple queries, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.