2014-02-22 65 views
0

下面的代碼打印每一行的單詞,然後打破,這是我編碼做的。php - 試圖回顯一個返回的加入My_SQL查詢與foreach循環

不過,我希望它是更聰明,並嘗試在同一行打印*$single*三次,所以它會說的第一個用戶名,姓,和它們的順序描述所有的同一行

我該如何去做這件事?

<?php 
//turn off error reporting for security 
//connecting to database as mysqli class 
$db = new mysqli("localhost", "root", "banana2", "cool"); 
if($db->connect_errno){ 
    echo $db->connect_errno; 
} 
$query1 = $db->query("SELECT first_name, last_name, orders.order_description FROM 
users JOIN orders on users.id=orders.employee_id"); 
$sharp = $query1->fetch_all(MYSQLI_ASSOC); 

function doAgain($sharp){ 
foreach($sharp as $single){ 
    if(is_array($single)){ 
     doAgain($single); 
    } 
    else{ 
     echo $single."<br>"; 
    } 
}  
} 

doAgain($sharp); 
?> 

回答

0

只需使用一個單一的foreach循環,打印在同一行的每一行:

foreach ($sharp as $row) { 
    echo "$row[first_name] $row[last_name] $row[order_description]<br>"; 
} 
0

你需要的功能doAgain?

$rows = $query1->fetch_all(MYSQLI_ASSOC); 

foreach ($rows as $row) { 
    foreach ($row as $fieldname => $value) { 
     echo $value . ' '; 
    } 
    echo '<br/>'; 
} 
+0

我喜歡你的邏輯了很多,但不知道如何$字段名=>值進場時,它有與fetch_all功能呢? – user3340015

+0

哦,你可以使用($行作爲$值) - 值將是每列的值,所以你不必命名它們 –

0

mySQL列是數組的索引。例如,你可以呼應

echo $single['first_name'].$single['last_name'];