2009-11-18 94 views

回答

5

這是一個完整的例子:

http://php.net/manual/en/mysqli-result.fetch-array.php

  1. 連接
  2. 選擇數據庫
  3. 製作查詢
  4. 循環的結果,並獲取數組來獲得該行
+0

有一點需要注意:mysql_query可以返回FALSE,這將導致php.net示例中的while循環失敗。所以,首先要做一個if(如Gabriel Sosa的回答)。除此之外,php.net頁面上的示例代碼很好。 – nash 2009-11-18 15:40:21

+0

正是我在找的,很好的例子! – 2009-11-18 15:42:39

+0

這個例子在php7中不再有效。這裏有一些與mysqli的例子:http://php.net/mysqli-stmt.fetch – youcantexplainthat 2016-07-07 16:13:28

15

第一個e我想到的示例:

<?php 

    $link = mysql_connect(/*arguments here*/); 

    $query = sprintf("select * from table"); 

    $result = mysql_query($query, $link); 

    if ($result) { 
     while($row = mysql_fetch_array($result)) { 
     // do something with the $row 
     } 

    } 
    else { 
     echo mysql_error(); 
    } 
?> 
1

我建議創建一個數據庫函數,充當數據庫提取的包裝。使數據庫函數調用,甚至數據庫本身的類型(例如,mysql-> postgresql或mysql-> couchdb或使用PDO對象或某物)變得更容易。

一些函數,你創建一個查詢並返回一個完全關聯的數組,然後你將數據庫連接代碼粘在那裏。

這也可能是好籤入到使用PDO的道路,因爲它抽象了數據庫中的特定功能對你來說,與MySQL和PostgreSQL等

4

工作。如果你正在使用MySQL版本4.1。 3或更高版本,it is strongly recommended你使用mysqli擴展而不是進一步開發的mysql擴展,不支持MySQL 4.1+的功能,沒有準備和多個語句,沒有面向對象的接口。 ..]

請參閱mysqli-stmt.fetch瞭解循環遍歷mysqli結果集的過程式和麪向對象的方法。

+0

我熟悉mysqli擴展並知道使用它,但不知道爲什麼它的首選,直到你解釋,謝謝! – 2009-11-18 16:19:12

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

$conn = new mysqli($servername, $username, $password, $dbname); 
if ($conn->connect_error) { 
die("Connection failed: " . $conn->connect_error); 
} 

$sql = "SELECT * FROM table"; 
$result = $conn->query($sql); 

if ($result->num_rows > 0) { 
while($row = $result->fetch_assoc()) { 
?> 
//Loop Content... Example:- 

**<li><?php echo $row[name]; ?></li>** 

<?php 
}}; 
?>