Correction status:Uncorrected
Teacher's comments:
PHP实现数据库连接
define('DB_HOST', '127.0.0.1'); define('DB_USER', 'root'); define('DB_PASS', 'root'); define('DB_NAME', 'php'); define('DB_CHAR', 'utf8'); $db = mysqli_connect(DB_HOST, DB_USER, DB_PASS,DB_NAME) or die('failed' . mysqli_connect_error($db)); //if (mysqli_connect_errno($db)) { // exit('failed' . mysqli_connect_error($db)); //} echo '链接成功'; //mysqli_select_db($db,DB_NAME); //mysqli_set_charset($db,DB_CHAR);
php数据库的增删改查
<?php require 'mysqli-connect.php'; // 新增操作 /** * $sql = "INSERT IGNORE staff SET name='zhangwuji' ;"; if (mysqli_query($db,$sql)){ if (mysqli_affected_rows($db)>0){ echo '受影响的记录数' .mysqli_affected_rows($db).'条记录,新增主键id'. mysqli_insert_id($db); }else{ echo '没有新增'; } }else{ exit(mysqli_errno($db) . mysqli_error($db)); } mysqli_close($db); */ //更新操作 /* $sql = "UPDATE staff SET sex='1' WHERE staff_id=15;"; 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)); } */ //删除操作 $sql = "DELETE FROM staff WHERE staff_id=17;"; if (mysqli_query($db,$sql)){ if (mysqli_affected_rows($db)){ echo '受影响的记录数' . mysqli_affected_rows($db); }else{ echo '没有操作记录'; } }else{ exit(mysqli_errno($db) . mysqli_error($db)); } mysqli_close($db); //查询操作 /** $sql = "SELECT name,salary FROM staff ;"; $res = mysqli_query($db, $sql); if ($res){ if (mysqli_num_rows($res)>0){ while ($row=mysqli_fetch_array($res,MYSQLI_NUM)){ var_export($row); } } } else{ exit(mysqli_errno($db) . mysqli_error($db)); } mysqli_free_result($res); mysqli_close($db); */
总结
数据库的连接使用mysqli_connect()函数
使用define()定义数据库连接常量
数据库的增删改查,
步骤1,连接数据库2,准备sql语句3,执行数据库语句,4,关闭数据库。5,如果有结果集要释放结果集