Home  >  Article  >  Backend Development  >  PHP connects to the database to implement simple queries

PHP connects to the database to implement simple queries

WBOY
WBOYOriginal
2016-08-08 09:26:132431browse

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

PHP connects to the database to implement simple queries

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:
PHP connects to the database to implement simple queries
When you search by id, enter 1 and it displays:
PHP connects to the database to implement simple queries
Complete code:





	
按id号查找:
"; echo "idnumnamesexbithday"; if(isset($_POST['select_all'])){ $arr=mysql_query("select * from test",$conn); while($row = mysql_fetch_array($arr)){ echo "{$row['id'] }{$row['num']} {$row['name']} {$row['sex']} {$row['birthday']}"; // echo $row['id'] . " " . $row['num']; // echo "
"; } }else if (isset($_POST['select_sure'])) { $id=$_POST['select_index']; $arr=mysql_query("select * from test where id=$id",$conn); if($row=mysql_fetch_assoc($arr)){ //如果查询的到 echo "{$id}{$row['num']} {$row['name']} {$row['sex']} {$row['birthday']}"; } } echo ""; mysql_close($conn); ?>

  • PHP connects to the database to implement simple queries
  • Size: 3.3 KB
  • PHP connects to the database to implement simple queries
  • Size: 8.5 KB
  • PHP connects to the database to implement simple queries
  • Size: 7.2 KB
  • Attachments

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn