实例
<?php // 一.连接mysql MySqli方式 // 1.参数 $dbType = 'mysql'; $host = '127.0.0.1'; $dbname = 'MyTest'; $user = 'root'; $pw = '13650158099'; //2.调用连接 $db = mysqli_connect($host,$user,$pw); //3.判断成功与否 if (mysqli_connect_errno($db)){ exit('连接MySQL失败!'.mysqli_connect_error($db)); } //4.选择数据库 mysqli_select_db($db,$dbname); //5.设置字符集 mysqli_set_charset($db,'utf8'); echo '<h3>连接MySQL成功!</h3>'; //二. 预处理 select // 1.sql语句 select $sql = "SELECT keyid,name FROM bs_supplier WHERE keyid LIKE ?"; // 2.创建stmt对象 $stmt = mysqli_stmt_init($db); // 3.检测 sql if (mysqli_stmt_prepare($stmt,$sql)) { //4.绑定参数 mysqli_stmt_bind_param($stmt,'s',$tmp); $tmp = 'G%'; //5.执行查询 mysqli_stmt_execute($stmt); //6.获取结果集 mysqli_stmt_store_result($stmt); //7.绑定结果集中的列与变量 mysqli_stmt_bind_result($stmt,$keyid,$name); //8.判断结果集的记录数 if (mysqli_stmt_num_rows($stmt) > 0) { //9.结果遍历 while (mysqli_stmt_fetch($stmt)) { printf("%s:%s",$keyid,$name); echo '<br>'; } } else { echo '没有符合条件的记录!'; } } else { exit('错误代码'.mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt)); } //更新操作 update // 1.sql语句 update $sql = "UPDATE bs_supplier SET name=CONCAT(name,'_update') WHERE keyid = ?"; // 2.创建stmt对象 $stmt = mysqli_stmt_init($db); // 3.检测 sql if (mysqli_stmt_prepare($stmt,$sql)) { //4.绑定参数 mysqli_stmt_bind_param($stmt,'s',$tmp); $tmp = 'GY02'; //5.执行查询 mysqli_stmt_execute($stmt); //6.判断结果集的记录数 $i = mysqli_stmt_affected_rows($stmt); if ($i > 0) { echo '成功更新了'.$i.'笔记录!'; } else { echo '没有记录被更新!'; } } else { exit('错误代码'.mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt)); } // //7.释放stmt // mysqli_stmt_close($stmt); // //8.关闭db // mysqli_close($db); //删除操作 delete // 1.sql语句 delete $sql = "DELETE FROM bs_supplier WHERE keyid = ?"; // 2.创建stmt对象 $stmt = mysqli_stmt_init($db); // 3.检测 sql if (mysqli_stmt_prepare($stmt,$sql)) { //4.绑定参数 mysqli_stmt_bind_param($stmt,'s',$tmp); $tmp = 'GY02'; //5.执行查询 mysqli_stmt_execute($stmt); //6.判断结果集的记录数 $i = mysqli_stmt_affected_rows($stmt); if ($i > 0) { echo '成功删除了'.$i.'笔记录!'; } else { echo '没有记录被删除!'; } } else { exit('错误代码'.mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt)); } //7.释放stmt mysqli_stmt_close($stmt); //8.关闭db mysqli_close($db); ?>
运行实例 »
点击 "运行实例" 按钮查看在线实例