PHP interacts with MySQL

WBOY
Release: 2016-08-08 09:29:16
Original
1254 people have browsed it

PHP and MySQL interaction

is demonstrated with a simple example. The code logic is: connect, create a table, insert data, obtain data and display the results.

(1): Create a test database from the command line

(2): The following is a php script (Connect, create a table, insert data, get data and display the results)

<?php
//连接数据库
$mysqli = new mysqli("localhost", "root", "", "test");

if(mysqli_connect_errno()){
	printf("Connect failed:%\n",mysqli_connect_error());
	exit();
} else {
	//建立表testtable
	$sql="create table testtable(id int not null primary 
         key auto_increment,testField varchar(75))";
	$res=mysqli_query($mysqli, $sql);
	if($res=true){
		echo "Table testtable successfully created.";
		//插入一条记录
		$sql_1="insert into testtable(testField) values
				('some value')";
		$res_1=mysqli_query($mysqli, $sql_1);
		if ($res_1=true) {
			echo "<br/>A record has been inserted.";
			//查询记录
			$sql_2="select * from testtable";
			$res_2=mysqli_query($mysqli, $sql_2);
			if ($res_2){
				//显示记录条数
				$number_of_rows = mysqli_num_rows($res_2);
				printf("<br/>Result set has %d rows.\n",$number_of_rows);
				//获取数据并显示结果
				while ($newArray = mysqli_fetch_array($res_2, MYSQLI_ASSOC)){
					$id = $newArray['id'];
					$testField = $newArray['testField'];
					echo "<br/>The ID is ".$id." and the text is ".$testField."<br/>";
				}
			} else {
				printf("Could not retrieve records:%s\n",mysqli_error($mysqli));
			}
		} else {
			printf("Could not insert record:%s\n",mysqli_error($mysqli));
		}
	} else {
		printf("Could not create table:%s\n",mysqli_error($mysqli));
	}
	
	mysqli_close($mysqli);
}
Copy after login

Access through the server , the effect is as follows:

Enter the command line to view the database

  • PHP interacts with MySQL
  • Size: 176.6 KB
  • PHP interacts with MySQL
  • Size: 20.4 KB
  • PHP interacts with MySQL
  • Size: 145.7 KB
  • View image attachment

The above has introduced the interaction between PHP and MySQL, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!