无法与PHP建立数据库连接

时间:2014-04-27 14:59:52

标签: php mysql

首先我有index.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的代码内。我在这里失踪了什么?

3 个答案:

答案 0 :(得分:1)

在php标签中包装connection.php文件:

<?php

// your php code

?>

<强>更新

如果仍然没有&#39;工作。也许你应该确保apache正在使用php。并且您通过apache而不是直接从文件系统提供文件。

答案 1 :(得分: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());

答案 2 :(得分:0)

connection.php 中尝试使用此代码:

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

或者你可以使用:

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

它应该工作!干杯! :)