2016-04-29 36 views
1

我想爲我的數據庫選擇最後一行,並將標題爲s1和s2的列回顯到網頁主體,以下是我的代碼。這給出了一個錯誤。無法在php中使用mysqli_result類型的對象作爲數組Mysql

<html> 
<body> 
<?php 

$servername = "localhost"; 
    $username = "root"; 
    $password = ""; 
    $dbname = "mydb2"; 

      $conn = new mysqli($servername, $username, $password, $dbname); 
      if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error); 
      } 
$sql = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1"; 
$row = array(); 
$row = mysqli_query($conn,$sql); 
echo " cup 1". $row["s1"]. "CUP 2". $row["s2"]; 
?> 



</body> 
</html> 
+4

你跳過了'fetch'部分,查詢執行後,獲取結果 – Ghost

回答

1

你必須使用mysqli_fetch_assoc(通過你的結果集是將循環)如下:

if ($result = mysqli_query($conn, $sql)) { 

    while ($row = mysqli_fetch_assoc($result)) { 
     echo " cup 1". $row["s1"]. "CUP 2". $row["s2"]; 
    } 

    /* free result set */ 
    mysqli_free_result($result); 
} 

沒有循環:

if ($result = mysqli_query($conn, $sql)) { 

    $row = mysqli_fetch_assoc($result); 
    if($row) 
    { 
     echo " cup 1". $row["s1"]. "CUP 2". $row["s2"]; 
    } 

    /* free result set */ 
    mysqli_free_result($result); 
} 
+0

爲什麼環路僅有1行? –

0

您的解決方案

<html> 
<body> 
<?php 
$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "mydb2"; 
$conn = new mysqli($servername, $username, $password, $dbname); 
if ($conn->connect_error) { 
    die("MySQL Connection Error"); // Try not to output SQL error messages on the front-end, look into error_reporting() 
} 

$sqlQuery = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1"; 
$results = mysqli_fetch_assoc(mysqli_query($conn, $sqlQuery)); 
echo " cup 1". $results["s1"]. "CUP 2". $results["s2"]; 
?> 
</body> 
</html> 

在除了 我建議不要在程序風格和麪向對象風格上進行SQL操作,因爲這會導致將來出現很多複雜情況。

0

使用mysqli_fetch_assoc的結果取到陣列

$sql = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1"; 
if ($result = mysqli_query($conn, $sql)) { 
    $row = mysqli_fetch_assoc($result); 
    echo " cup 1". $row["s1"]. "CUP 2". $row["s2"]; 
} 
相關問題