内容:
使用MySQLi面向过程的方式,实现三种方式的数据库连接操作。
<?php header("content:text/html;charset=utf-8"); define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PASS','root'); define('DB_NAME','table'); define('DB_CHAR','utf8'); //(1)面向过程连接数据库: $db=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die( '连接失败'); mysqli_set_charset($db,DB_CHAR); $sq1='SELECT `id`,`姓名` FROM `student`'; $res1=mysqli_query($db,$sq1); $res2[]=mysqli_fetch_all($res1,MYSQLI_ASSOC); echo '<pre>'; print_r($res2); mysqli_free_result($res1); mysqli_close($db); //<!-- 面向对象的数据库mysqli连接 --> $mysqli=new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME); if ( $mysqli -> connect_error ) { die( 'Connect Error (' . $mysqli -> connect_errno . ') ' . $mysqli -> connect_error ); } $sql = "select * from student"; $mysqli->set_charset("utf8"); $result = $mysqli->query($sql); $row = $result->fetch_array(); // 从结果集中取得一行作为数组 print_r($row); /* free result set */ $result->free(); /* close connection */ $mysqli->close();
结果:
Array ( [0] => Array ( [0] => Array ( [id] => 1 [姓名] => 小白 ) [1] => Array ( [id] => 2 [姓名] => 小黑 ) ) ) Array ( [0] => 1 [id] => 1 [1] => 小白 [姓名] => 小白 [2] => 40bd001563085fc35165329ea1ff5c5ecbdbbeef [密码] => 40bd001563085fc35165329ea1ff5c5ecbdbbeef )