2013-02-07 59 views
0

大家好我對這個一對多的說法有點問題。我在mysql數據庫和文件夾中添加圖像,這部分是完美的。但是當我想要展示他們時,這是我的棘手部分。我不知道我創建數據庫的方式或代碼中的問題在哪裏。因此,這裏有兩個:1 to many mysql statment plus showing images and text

我的兩個表是文本和imagess 在文本表: text_id - 初級 text_field - 獨特

在imagess表: ID - 初級 名 標題 路徑

我的代碼是這樣的:

 <?php 

    $result = mysql_query("SELECT * FROM text text_id, imagess id WHERE (text_id=id AND text_field=title) "); 

    while($row = mysql_fetch_assoc($result)){ 
    echo '<br>№'.$row['text_id'].'<br>'; 

    echo''.$row['title'].'<br>' 
    .$row['text_field']; 

    echo'<br><img src="'.$row['path'].'?url='.$row['path'].'/>'; 
    } 

    ?> 

我的目標是學習如何用2-3張圖片顯示1個標題+文字。我希望有人能向我解釋我的錯誤在哪裏,因爲從我閱讀的書中看不出這樣的事情。

預先感謝您。

+0

SQL查詢顯然是不正確的,但沒有看到你試着用 – Bgi

+0

您可以粘貼該查詢的樣本輸出表的完整結構,我不能糾正它嗎? – Techmonk

+0

@Bgi我的桌子是這樣的: imagess id INT 11 NOT NULL AUTO_INCREMENT primary; name varchar(50)NOT NULL; title varchar(80)NOT NULL; path varchar(100)NOT NULL; 對於文本表格: text_id - 主要的詮釋11非空自動增量; text_field - unique varchar 80 not null; – user2015448

回答

1

在一對多關係中,所有您必須忽略「1」的倍數出現次數。 你還必須加入你的imagess表的外鍵。 查詢中有錯誤,「FROM text text_id」表示您在名爲text_id的文本上創建別名。

<?php 
$currentTextId = -1; 
$result = mysql_query("SELECT * FROM text, imagess WHERE (text.text_id=imagess.text_id) ORDER BY text.text_id"); 

while($row = mysql_fetch_assoc($result)){ 
    if($row['text_id']!=$currentTextId){ 
     $currentTextId=$row['text_id'] 
     echo '<br>№'.$row['text_id'].'<br>'; 
    } 

    echo''.$row['title'].'<br>'.$row['text_field']; 
    echo'<br><img src="'.$row['path'].'?url='.$row['path'].'/>'; 
} 

?>