鏈接mysql數據庫,輸出數據

<?PHP

//  舊版的

    header("Content-type: text/html; charset=utf-8");
    $con = mysql_connect('localhost', 'root', '');
    mysql_select_db('music');
    mysql_query('set names utf8');
    $sql = 'select name, musicName from music_list';
    $query = mysql_query($sql);
    if( $query && mysql_num_rows($query) ){
        while($row = mysql_fetch_assoc($query)){
            $data[] = $row;
        }
        echo json_encode($data);
    }


    //下面是5.3以上的版本的
    //定義頭文件utf-8編碼
    header("Content-type: text/html; charset=utf-8");
    //鏈接數據庫
    $link = new mysqli('localhost', 'root', '', 'music');
    //如果數據庫鏈接失敗
    if(mysqli_connect_errno()){
        die('Unable to connect!');
    }
    //對數據庫定於utf8的編碼
    mysqli_set_charset($link, 'utf8');
    //表查詢語句
    $sql = 'select name, musicName from music_list';
    //執行查詢代碼
    $result = $link->query($sql);
    //聲明data數組變量
    $data = array();
    //循環查詢語句  放到data數組裏面
    while( $row = $result->fetch_object() ){
        $data[] = $row;
    }
    //輸出數組
    echo json_encode($data);
?>
發佈了23 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章