三、Mysqli查询数据库操作

三、Mysqli查询数据库操作

查询操作

<?php
header("Content-type:text/html;charset=UTF-8");
$mysqli=new mysqli('localhost','root','','shanshi');
if ($mysqli->connect_errno){
    die('Connect Error:'.$mysqli->connect_error);
}
//设置字符集
$mysqli->set_charset('utf8');
$sql="SELECT user_id,username FROM ykb_user";
$mysqli_result=$mysqli->query($sql);
//失败返回false
//print_r($mysqli_result);
if ($mysqli_result && $mysqli_result->num_rows>0){
    //echo $mysqli_result->num_rows;
    //$rows=$mysqli_result->fetch_all();//获取结果集中的所有记录,默认返回的是二维的
    //索引+索引的形式
    //$rows=$mysqli_result->fetch_all(MYSQLI_NUM);
    //索引+关联的形式
    //$rows=$mysqli_result->fetch_all(MYSQLI_ASSOC);
    //索引+二者都有的形式
    //$rows=$mysqli_result->fetch_all(MYSQLI_BOTH);
    //取得结果集中第一条记录作为索引数组返回
    /*$row=$mysqli_result->fetch_row();
    print_r($row);
    echo '<hr/>';
    //取得结果集中的一条记录作为关联数组返回
    $row=$mysqli_result->fetch_assoc();
    print_r($row);
    echo '<hr/>';*/
    /**
     * 二者都有,fetch_arrar参数
     *  MYSQLI_ASSOC 关联
    */
    /*$row=$mysqli_result->fetch_array();
    print_r($row);
    echo '<hr/>';
    //返回对象
    $row=$mysqli_result->fetch_object();
    print_r($row);
    echo '<hr/>';
    //移动结果集内部指针
    $mysqli_result->data_seek(0);
    $row=$mysqli_result->fetch_assoc();
    print_r($row);*/

    while ($row=$mysqli_result->fetch_assoc()){
        //print_r($row);
        //echo '<hr />';
        $rows[]=$row;
    }
    print_r($rows);
    //释放结果集
    $mysqli_result->free();
}else{
    echo '查询错误活着结果集中没有记录';
}
//关闭连接
$mysqli->close();



回复列表


回复操作