2017-02-21 77 views
0

我碰到一個問題,即時通訊嘗試的PHP腳本。所以當我啓動它時,腳本完美地連接到MySQL和數據庫,但是當我嘗試從'代碼'數據庫中選擇數據時,它會給我一個這樣的錯誤:「無法獲取數據:」。它應該做的是說「無法獲取數據:(然後是錯誤)」,但它沒有。先謝謝了。 :)PHP select MySQL給出未知錯誤

PHP代碼:

<?php 
$servername = "localhost"; 
$username = "username"; 
$password = "password"; 
$dbname = "database"; 

// Create connection 
$conn = mysqli_connect($servername, $username, $password); 
mysqli_select_db($dbname); 

// Check connection 
if (!$conn) { 
    die("Connection failed: " . mysqli_connect_error()); 
} 
echo "Connected successfully"; 

    $sql = 'SELECT code FROM codes'; 
    $retval = mysql_query($sql, $conn); 

    if(! $retval) { 
     die('Could not get data: ' . mysql_error()); 
    } 

    while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { 
     echo "Code:{$row['code']}"; 
    } 

    echo "Fetched data successfully\n"; 

    mysql_close($conn); 
?> 
+4

要結合'mysql'&'mysqli'。僅在每個操作中使用'mysqi' –

+2

您正在將mysqli與mysql混合 –

+0

您檢查數據庫名稱。 –

回答

2

你混合MySQL和mysqli的在一起,我固定的錯誤:

<?php 
ini_set('display_errors', 1); 
error_reporting(E_ALL); 
$servername = "localhost"; 
$username = "root"; 
$password = "pass"; 
$dbname = "table"; 

// Create connection 
$conn = mysqli_connect($servername, $username, $password); 
     mysqli_select_db($conn, $dbname); 

// Check connection 
if (!$conn) { 
    die("Connection failed: " . mysqli_connect_error()); 
} 
// echo "Connected successfully"; 

    $sql = 'SELECT username FROM users'; 
    $retval = mysqli_query($conn ,$sql); 

    if(! $retval) { 
     die('Could not get data: ' . mysqli_error()); 
    } 

    while($row=mysqli_fetch_array($retval,MYSQLI_ASSOC)) { 
     echo "Code:{$row['username']}"; 
    } 

    echo "Fetched data successfully\n"; 

    mysqli_close($conn); 
?> 
+0

感謝這個工作,你的男人! :d –