2014-04-27 86 views
0

首先,我有index.php文件中的代碼包含如下無法建立與PHP數據庫連接

<form action="connection.php" method="post"> 
<table> 
    <thead><tr><td>Enter Item Details</td></tr></thead> 
    <tr> 
     <td>Item name :- </td> 
     <td><input type="text" maxlength="30" name="item_name"></td> 
    </tr> 
    <tr> 
    <td>Item Desc :- </td> 
    <td><input type="text" maxlength="150" name="item_desc"></td> 
    </tr> 
    <tr> 
    <td colspan="2"><input type="submit" value="Add Item"> 
    </td></tr> 
</table> 

</form> 

和我connection.php由代碼如下

$host="localhost"; 
$username="root"; 
$password=""; 
$db_name="eatery"; 
$tbl_name="test_item"; 
mysql_connect("$host", "$username", "$password") or die("Not able to connect to MySql"); 

echo "connected"; 
mysql_select_db("$db_name") or die ("Not able to connect to eatery database"); 

我已經安裝WAMP包運行Apache服務器和我的PHP代碼。現在點擊index.php的提交按鈕,而不是數據庫連接成功/失敗消息,它顯示了connection.php的內部代碼。所以我在這裏錯過了什麼?

+0

它顯示了connection.php的確切內容? – lagbox

+0

確保你不會忘記在** connection.php **腳本和'?>'末尾寫入'<?php'。否則,服務器將其視爲常規文本/ html。 – Wh1T3h4Ck5

+0

我認爲標題需要調整。這不是數據庫問題。 – lagbox

回答

1

裹在PHP標籤connection.php文件:

<?php 

// your php code 

?> 

UPDATE:

如果仍然心不是」工作。也許你應該確保Apache使用PHP。你通過apache提供你的文件,而不是直接從文件系統中提取文件。

+0

我已經添加它們 –

1

您必須將變量作爲變量傳遞,而不是字符串。

改變這種

mysql_connect("$host", "$username", "$password")or die .... 
    mysql_select_db("$db_name")or die... 

<?php 
..... 
..... 
..... 
mysql_connect($host, $username, $password) or die .... 
mysql_select_db($db_name)or die ... 
...... 
?> 

和調試錯誤,看到確切的錯誤使用,而不是你的錯誤消息。

or die(mysql_error()); 
+1

應該沒關係 – lagbox

+0

我改變了變量但仍然是相同的錯誤。它顯示頁面本身的內容。也試過mysqli_connect –

+0

它顯示頁面本身的內容。 ???那麼你忘記了PHP標籤:)。在開始使用'<?php'並在文件末尾使用'?>'查看編輯答案 –

0

在你 connection.php嘗試用這個代替:

$con = mysqli_connect("localhost","root","","eatery"); 

,或者你也可以只使用:

mysqli_connect("localhost","root","","eatery"); 

它應該工作!乾杯! :)