我試圖把我的SQL查詢放在一個單獨的文件中,以便不再重複它們。我試圖爲此創建一個類和函數,但出現了一些問題。我無法弄清楚爲什麼。我甚至懷疑這是否是繼續進行的好方法,因爲我沒有在網上找到類似的例子。查詢 - 把他們放在課堂上?
原代碼,並導致我想獲得那些者:
//this works but must be refactored
$book = $_POST['book'];
$select_titles = mysql_query("
SELECT booktitles.id_title, booktitles.title, booktitles.id_book
FROM booktitles
WHERE booktitles.id_book = $book
") or die(mysql_error());
while($selected_titles = mysql_fetch_assoc($select_titles))
{
$id_title = $selected_titles['id_title'];
$title = $selected_titles['title'];
echo $title."<br/>";
// now the second query, wich needs the $id_title
$select_content = mysql_query("
SELECT content.id_content, content.content, content.id_title
FROM content
WHERE content.id_title = $id_title
") or die(mysql_error());
while($selected_content = mysql_fetch_assoc($select_content))
{
$id_content = $selected_content['id_content'];
$content = $selected_content['content'];
echo $content."<br/>;
}
}
我試圖以這種方式(請注意,就像我在前面的例子中那樣我無法合併這兩個查詢將這一,因爲我必須能夠分別訪問它們):
// file : query.php
class Queries
{
public function selectTitles($id_book)
{
$select_titles = mysql_query("
SELECT booktitles.id_title, booktitles.title, booktitles.id_book
FROM booktitles
WHERE booktitles.id_book = $book
") or die(mysql_error());
while($selected_titles = mysql_fetch_assoc($select_titles))
{
$id_title = $selected_titles['id_title'];
$title = $selected_titles['title'];
echo $title."<br/>";
}
}
public function selectContent($id_title)
{
$select_content = mysql_query("
SELECT content.id_content, content.content, content.id_title
FROM content
WHERE content.id_title = $id_title
") or die(mysql_error());
while($selected_content = mysql_fetch_assoc($select_content))
{
$id_content = $selected_content['id_content'];
$content = $selected_content['content'];
echo $content."<br/>;
}
}
}
// file : books.php
require_once('query.php');
$book = $_POST['book'];
$display_titles = new Queries;
$display_titles->selectTitles($book);
while($id_title)
{
$display_content = new Queries;
$display_content->selectContent($id_title);
// this does not work. Furthermore, I must be able to add something here (like a form which uses the values) --> I seem not allowed to do that
}
這是行不通的。任何想法如何處理這將非常感謝!
(注:這裏是一個回答類似的問題:modify php oop mysql query)
在此行上添加雙引號:'echo $ content。「
'此外,您還沒有從函數返回任何內容:'selectTitles'。books.php中的$ id_title的值是什麼? – 2011-04-18 14:36:10
hi觀察者, id_title應該由第一個查詢返回...謝謝! – Raphael 2011-04-18 14:48:11
我的觀點是它沒有被返回,你所做的只是迴應。一旦這個函數完成,$ id_title不再被設置。 – 2011-04-18 14:56:04