2014-09-06 47 views
2

這是我第一次在SO發帖,如果我打開一個存在的問題,我很抱歉。因爲我無法在Google中找到結果。對不起,但我仍然在PHP PDO和學習階段新鮮。PHP PDO,雖然沒有達到我的願望最終結果

回到我的問題,目前我正在建立一個來自我妻子的客戶訪問日誌,但我堅持的結果。我有兩個表,其中一個存儲客戶信息,另一個表存儲訪問詳細信息。我上傳在這裏的測試表:SQL Fiddle

及以下是我目前的編碼和我使用PHP PDO

<?php 

require_once 'dbconnect.php'; 

$p_id = $_GET['name']; 

try { 
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); 

$sql = "SELECT customer.fname, customer.lname, customer.gender, services.treatment, services.date 
      FROM customer LEFT JOIN services 
      ON customer.id = services.customer_id 
      WHERE customer.slug LIKE :id"; 

$q = $conn->prepare($sql); 
$q->execute(array('id' => $p_id)); 
$q->setFetchMode(PDO::FETCH_ASSOC); 

} catch (PDOException $pe) { 
die("Could not connect to the database $dbname :" . $pe->getMessage()); 
} 

?> 
<!DOCTYPE html> 
<html> 
<head> 
<title>Test</title> 
</head> 
<body> 
<div id="container"> 
<h1>Customer Record</h1> 
Name: <br /> 
Gender: <br />  
<table class="table table-bordered table-condensed"> 
    <thead> 
     <tr> 
      <th>Customer Name</th> 
      <th>Customer Gender</th> 
      <th>Treatment</th> 
      <th>Date</th> 
     </tr> 
    </thead> 
    <tbody> 
     <?php while ($r = $q->fetch()): ?> 
     <tr> 
      <td><?php echo htmlspecialchars($r['fname']), ' ', htmlspecialchars($r['lname'])?></td> 
      <td><?php echo htmlspecialchars($r['gender']); ?></td> 
      <td><?php echo htmlspecialchars($r['treatment']); ?></td> 
      <td><?php echo htmlspecialchars($r['date']); ?></td> 
     </tr> 
     <?php endwhile; ?> 
    </tbody> 
</table> 
    <a href="search.html">Seach Again</a> 
</body> 
</div> 
</html> 

我作爲實現哪些SQL小提琴的結果,但我想要的是,名稱和性別不會重複。

Screenshot

我想是因爲每截圖圖像,名稱:李四和性別:男性,應該是在上面,而不是保持

我有截圖連接在一起重複,而下面的表格顯示所有的訪問細節。我試圖修改代碼,但它似乎並沒有真正解決。

請告訴我,我真的不知道如何實現我想要的。

非常感謝。

回答

1

既然你在你的SQL查詢做了LEFT JOIN,你提前知道所有通過$q->fetch()返回fnamelnamegender值將是爲相同customer.slug,正確的時間?所以你可以指望這一點。

我的建議是改爲使用fetchAll()函數來獲取customer.slug的所有記錄的數組,然後在您的視圖中進行渲染。例如(沒有測試),你可以$q->setFetchMode(PDO::FETCH_ASSOC);後添加以下...

$cs = $q->fetchAll(); // customer services join 

然後,在你<html>視圖,你可以這樣做以下:

<h1>Customer Record</h1> 
Name: <?php echo htmlspecialchars($cs[0]['fname'].' '.$cs[0]['lname']); ?> <br /> 
Gender: <?php echo htmlspecialchars($cs[0]['gender']); ?> <br /> 

<table> 
    <thead> 
    <tr> 
     <th>Treatment</th> 
     <th>Date</th> 
    </tr> 
    </thead> 
    <tbody> 
    <?php foreach($cs as $r): ?> 
    <tr> 
     <td><?php echo htmlspecialchars($r['treatment']); ?></td> 
     <td><?php echo htmlspecialchars($r['date']); ?></td> 
    </tr> 
    <?php endforeach; ?> 
</tbody> 

當然,查看任何記錄是否被查詢返回並且如果不是,則顯示「未找到」消息也可能是一個好主意。畢竟,$cs[0]可能是空的,給你一個PHP錯誤。

+0

謝謝@ joseph8th它現在解決了我的問題:) – 2014-09-06 20:04:56

+0

很高興我可以幫助! – Joseph8th 2014-09-06 20:15:30