douci7521 2011-06-13 04:33
浏览 27
已采纳

使用php连接到mysql

Here is my following tutorial code from "Learning PHP MYSQL and Javascript" by OReilly.

<?php 
//require_once = 'login.php';

$db_database = 'publications';
$db_hostname = 'localhost:8888';
$db_username = 'root';
$db_password = 'root';


$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if(!$db_server) die("Unable to connect to MYSQL: ". mysql_error());

mysql_select_db($db_database)
    or die("Unable to connect to database: " . mysql_error());

$query = "SELECT * FROM classics";
$result = $mysql_query($query);

if(!$result) die ("Could not query: " . mysql_error());
$rows = mysql_num_rows($result);

for($j = 0; $j < $rows; ++$j)
{
    echo 'Author: ' . mysql_result($result, $j, 'author') . '</br>';
    echo 'Title: ' . mysql_result($result, $j, 'title'). '</br>';
    echo 'ISBN: '.mysql_result($result, $j, 'isbn').'</br>';
}

?>

However, I'm getting an error when trying to connect. The browser says it's a 500 error (which really isn't that helpful). When I take out the lines $db_username = 'root'; $db_password = 'root'; I get another error saying: "Unable to connect to database: Access denied for user ''@'localhost' to database 'publications'".

Can anyone help diagnose the problem?

Thanks!

  • 写回答

6条回答 默认 最新

  • douiwn6941 2011-06-13 04:38
    关注

    Change this

    $result = $mysql_query($query);
    

    to this

    $result = mysql_query($query);
    

    Function name is mysql_query not $mysql_query, $ is used in variable names.

    Also, instead of trying to "see" your code immediately in a browser window you could use a PHP command line instead. If your file is called foo.php you coudl do:

    >> php foo.php
    PHP Notice:  Undefined variable: mysql_query in /var/www/foo.php on line 17
    PHP Fatal error:  Function name must be a string in /var/www/foo.php on line 17
    

    As you see, the error message is pretty clear. Because of using $mysql_query it thinks that mysql_query is a variable, but such a variable is not defined somewhere.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类