我已經在一段時間裏對PHP進行了一些清理,自從我上次用PHP編碼以來已經有3年了。歡迎任何見解!我會給你儘可能多的信息,我可以解決這個錯誤,所以在這裏!PHP數據庫選擇問題
文件
- 的config.php
- database.php中
- news.php
- BLnews.php
- 的index.php
包括
- 的config.php - > news.php
- database.php中 - > news.php
- news.php - > BLnews.php
- BLnews.php - >的index.php
現在我的當前代碼的問題是數據庫連接正在進行,但我的數據庫拒絕被選中。我的查詢應該可以工作,但是由於我的數據庫沒有被選中,所以讓數據交換變得非常煩人!
的config.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";
?>
database.php中
<?php
class Database {
//-------------------------------------------
// Connects to the database
//-------------------------------------------
function connect() {
if (isset($dbhost) && isset($dbuser) && isset($dbpass) && isset($dbname)) {
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect: " . mysql_error());
$selected_db = mysql_select_db($dbname, $con) or die("Could not select test DB");
}
}// end function connect
} // end class Database
?>
News.php
<?php
// include the config file and database class
include 'config.php';
include 'database.php';
...
?>
BLnews.php
<?php
// include the news class
include 'news.php';
// create an instance of the Database class and call it $db
$db = new Database;
$db -> connect();
class BLnews {
function getNews() {
$sql = "SELECT * FROM news";
if (isset($sql)) {
$result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error());
}
return $result;
}
?>
的index.php
<?php
...
include 'includes/BLnews.php';
$blNews = new BLnews();
$news = $blNews->getNews();
?>
...
<?php
while($row = mysql_fetch_array($news))
{
echo '<div class="post">';
echo '<h2><a href="#"> ' . $row["title"] .'</a></h2>';
echo '<p class="post-info">Posted by <a href="#"> </a> | <span class="date"> Posted on <a href="#">' . $row["date"] . '</a></span></p>';
echo $row["content"];
echo '</div>';
}
?>
嗯,這是一個應該得到的信息卻會由於mysql_error在$result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error());
幾乎所有我能看到的錯誤,並說:
無法執行查詢。原因是:沒有數據庫選擇
我真的不知道爲什麼它不會工作,我已經擺弄了很長一段時間了。幫助是最受歡迎的,我提前感謝你!
電賀
檸檬
既然你已經離開了PHP一段時間,你應該谷歌PDO。 – alex
對不起,但在您的數據庫類中,我沒有看到您將vars定義爲$ dbhost或$ dbuser的位置。在你沒有的情況下,if將永遠是假的,所以你既不會得到連接也不會死()。 –
@AurelioDeRosa:他說正在建立連接,如果你看他的代碼,只有在這些變量都設置好的情況下才能建立連接。 – Cyclone