首先创建connect.php脚本,以后数据库连接就require该脚本
<?php header('content-type:text/html;charset=utf-8'); $host='localhost'; $user='root'; $psd='root'; $db='demo1'; //创建mysqli对象连接数据库 $mysqli = new mysqli($host,$user,$psd,$db); //另外一种写法 //$mysqli = new mysqli(); //$mysqli->connect($host,$user,$psd); //$mysqli->select_db($db); if ($mysqli->connect_errno) { //如果连接失败输出错误结果 die('connect failed:'.$mysqli->connect_error); }else { echo 'connect success'; } //设置默认客户端字符集 $mysqli->set_charset('utf8');
方法:connect()
属性:connect_errno 以及 connect_error
2.insert语句
query()方法执行sql语句
affected_rows属性受影响的记录数
insert_id 插入的主键id
error和errno 错误信息
<?php //引入连接数据库脚本 require 'connect.php'; //1.创建sql语句 $sql = "INSERT INTO `student` (`name`,`course`,`grade`) VALUES ('赵无双', 'php', 77)"; if ($mysqli->query($sql)) { echo '成功添加了 '.$mysqli->affected_rows.'条记录,id为'.$mysqli->insert_id; }else { echo 'insert failed'.$mysqli->connect_errno.':'.$mysqli->connect_error; } //关闭 $mysqli->close();
这个脚本存在重复插入数据的漏洞,可以结合查询操作来解决该漏洞
3.select语句(结合插入语句)
<?php require 'connect.php'; $sql = "SELECT `name` FROM `student` WHERE `name`='赵无双'"; $res = $mysqli->query($sql); if ($res->num_rows>0) { echo '已存在该用户名,请重新输入用户名'; }else { $sql1="INSERT INTO `student` (`name`,`course`,`grade`) VALUES ('赵无双','php', 77)"; if ($mysqli->query($sql1)) { echo '<p>'; echo '成功插入了'.$mysqli->affected_rows.'条记录,ID:'.$mysqli->insert_id; echo '</p>'; }else { echo '插入失败'.$mysqli->connect_errno.':'.$mysqli->connect_error; } } //关闭 $mysqli->close();
4. 删除操作
<?php require 'connect.php'; $sql="DELETE FROM `student` WHERE `name`='黄蓉'"; $res=$mysqli->query($sql); if ($res) { echo '<p>'; echo '成功删除了'.$mysqli->affected_rows.'条记录'; echo '</p>'; }else { echo '删除失败'.$mysqli->connect_errno.':'.$mysqli->connect_error; } //关闭 $mysqli->close();
5.更新操作
<?php require 'connect.php'; $sql = "UPDATE `student` SET `grade`=99 WHERE `id`=4"; $res = $mysqli->query($sql); if ($res) { echo '<p>'; echo '成功更新了'.$mysqli->affected_rows.'条记录'; echo '</p>'; }else { echo '更新失败'.$mysqli->connect_errno.':'.$mysqli->connect_error; } $mysqli->close();
6.结果集操作
<?php require 'connect.php'; $sql="SELECT * FROM `student` WHERE `id`>1"; $res=$mysqli->query($sql); if ($res) { if ($res->num_rows>0) { //利用while语句往$rows[]插入数据 while($row=$res->fetch_array(MYSQLI_ASSOC)) { echo '<pre>'; // print_r($row); $rows[]=$row; } // }else { //这个代表我虽然查询了,但按照查询的条件没有返回任何有效效果 echo '没有查到数据'; } }else { //这个错误信息是$res不为真的情况下的反馈 echo '查询出错'; } //创建表格来输出 ?> <table border="1px solid black" cellspacing="0" align="center" > <tr> <td>ID</td><td>Name</td><td>Course</td><td>Grade</td> </tr> <!-- 采用foreach语法遍历出相应的字段值--> <?php foreach($rows as $row): ?> <tr> <td><?php echo $row['id'] ?></td> <td><?php echo $row['name'] ?></td> <td><?php echo $row['course'] ?></td> <td><?php echo $row['grade'] ?></td> </tr> <?php endforeach; ?> </table>