编程语言PHP与MySQL交互

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 "
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("
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 "
The ID is ".$id." and the text is ".$testField."
";
}
} 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);
}

通过服务器访问,效果如下:

进入命令行查看数据库

  • 大小: 176.6 KB

  • 大小: 20.4 KB

  • 大小: 145.7 KB

  • 查看图片附件

以上就介绍了PHP与MySQL交互,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

文章来源:https://www.php.cn/faq/332515.html

百度网盘搜索
www.ijzcn.cn
阿哇教育
www.awaedu.com
作文哥
www.zuowenge.cn
搜码吧
www.somanba.cn
(0)

相关推荐