Correction status:Uncorrected
Teacher's comments:
mysql增删改查,php mysqli使用
mysqli_config.php
<?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASSWORD', 'root'); define('DB_NAME','user' ); define('DB_CHAR', 'utf8');
点击 "运行实例" 按钮查看在线实例
mysqli_connect.php
<?php /* *创建连接,返回连接资源 *判断连接成功 *选择数据表 *设置字符集 */ require 'mysqli_config.php'; // 抑制错误信息 $db=@mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("连接数据库失败"); mysqli_set_charset($db,DB_CHAR);
点击 "运行实例" 按钮查看在线实例
mysqli_query.php
<?php require 'mysqli_connect.php'; $sql="SELECT name,age FROM staf;"; if ($res=mysqli_query($db,$sql)) { if (mysqli_num_rows($res)>0) { while ($row=mysqli_fetch_assoc($res)) { var_export(print_r($row),true); echo "<hr>"; } } } else { exit(mysqli_errno($db).':'.mysqli_error($db)); } // 释放结果集,只对select mysqli_free_result($res); mysqli_close($db);
点击 "运行实例" 按钮查看在线实例
mysqli_delete.php
<?php require 'mysqli_connect.php'; $sql="DELETE FROM staf WHERE name='jess';"; if (mysqli_query($db,$sql)) { if (mysqli_affected_rows($db)>0) { echo '成功删除了'.mysqli_affected_rows($db).'条记录'; } else { echo '没有记录被删除'; } } else { exit(mysqli_errno($db).':'.mysqli_error($db)); } mysqli_close($db);
点击 "运行实例" 按钮查看在线实例
mysqli_insert.php
<?php require 'mysqli_connect.php'; $sql="INSERT INTO staf (name,sex,age,salary) VALUES ('jess',0,30,6000);"; if (mysqli_query($db,$sql)) { if (mysqli_affected_rows($db)>0) { echo "新增了".mysqli_affected_rows($db)."条记录,<br>新纪录主键id:" .mysqli_insert_id($db); } else { echo "没有记录被新增"; } } else { exit(mysqli_errno($db).':'.mysqli_error($db)); } mysqli_close($db);
点击 "运行实例" 按钮查看在线实例
mysqli_update.php
<?php require 'mysqli_connect.php'; $sql="UPDATE staf SET salary=7000 WHERE name='jess';"; if (mysqli_query($db,$sql)){ if(mysqli_affected_rows($db)>0) { echo '成功更新了'.mysqli_affected_rows($db).'条记录'; } else { echo '没有更新'; } } else { exit(mysqli_errno($db).':'.mysqli_error($db)); } mysqli_close($db);
点击 "运行实例" 按钮查看在线实例
mysqli_multiquery.php
<?php require 'mysqli_connect.php'; $sql="SELECT sex,ROUND(AVG(salary),2) FROM staf GROUP BY sex;"; $sql.="SELECT name,age FROM staf WHERE age>50;"; $sql.="SELECT name,salary FROM staf WHERE salary>5000;"; $num=1; if (mysqli_multi_query($db,$sql)) { echo $num.'结果子集<br>'; // 获取当前子结果集 while ($res=mysqli_store_result($db)) { if (mysqli_affected_rows($db)>0) { while ($row=mysqli_fetch_array($res,MYSQLI_ASSOC)) { print_r($row); echo "<br>"; } mysqli_free_result($res); } else { echo '没有满足结果的数据'; } if (mysqli_more_results($db)) { $num++; echo '<hr>第'.$num.'个结果子集的数据<br>'; mysqli_next_result($db); } } } else { exit(mysqli_errno($db).':'.mysqli_error($db)); } mysqli_close($db);
点击 "运行实例" 按钮查看在线实例