以一个简单的实例进行展示,代码逻辑为:进行连接、创建一个表、插入数据、获取数据并显示结果。
?
(1):命令行建立test数据库
?
(2):以下是php脚本(进行连接、创建一个表、插入数据、获取数据并显示结果)
class="php" name="code"><?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); }
?
通过服务器访问,效果如下:
进入命令行查看数据库
?
?
?
?