doushi9856 2014-03-11 02:12
浏览 41

使用Mamp和MySQL(PHP)“无法连接”

I am trying to access my MySQL database with PHP, but my page keeps returning the error "unable to connect". Here is my code:

echo '<ul>';

$db_host = "localhost";
$db_user = "user";

$db_link = mysqli_connect($db_host, $db_user, $db_password, $db_name)
or die ("Unable to connect");

$sqlQuery = "SELECT u.user_name, m.message_text, m.time_stamp FROM users AS u INNER JOIN messages m ON u.user_id = m.user_id";

$result = mysqli_query($db_link, $sqlQuery);


if($result)
{
 while ($row=mysqli_fetch_assoc($result)) 
  {
    echo "<li>" . $row['message_text'] . "<br>" . $row['user_name'] . "<br>" . $row['time_stamp'] . "</li>
\t\t<hr>";
}
}
else
{
echo '<p>error displaying resultset</p>';
}

mysqli_close($db_link);
echo '</ul>';
  • 写回答

2条回答 默认 最新

  • doucha5080 2014-03-11 02:43
    关注

    It looks like you haven't set $db_password or $db_name, with the latter definitely necessary to connect to the database. The former should also be set assuming you have a password set for the database (you do have a password set, right?) Verify that you have properly set those variables, and then do a var_dump() on the $db_link like this:

    echo "<pre>";     //For formatting. 
    var_dump($db_link);
    echo "</pre>"
    

    This will give you an idea of whether or not you have properly setup the connection object for the database.

    UPDATE

    SELECT
        u.user_name,
        m.message_text,
        m.time_stamp
    FROM
        users AS u
    INNER JOIN messages m ON u.user_id = m.user_id
    

    Here's your query, but with the proper formatting. Notice the last line, you have:

    INNER JOIN messages m
    

    That stray 'm' isn't necessary, and for the sake of debugging I'd recommend formatting the query like this:

    $sqlQuery = "SELECT `user`.user_name, `message`.`message_text`, `message`.time_stamp FROM users INNER JOIN messages ON `users`.user_id = `message`.user_id";
    

    Edit: As an aside, you mentioned that the query gave you a bool(false) when you used var_dump. This tells you that the query is failing and lets you know to start debugging it. (PHP.net)

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料