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); }
Access through the server , the effect is as follows:
Enter the command line to view the database
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.