PHP與MySQL互動
以一個簡單的實例進行展示,程式碼邏輯為:進行連接、建立一個表格、插入資料、取得資料並顯示結果。
(1):命令列建立test資料庫
(2):以下是php腳本(進行連接、建立一個表格、插入資料、取得資料並顯示結果)
<?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); }
透過伺服器存取,效果如下:
進入命令列查看資料庫