-2

我得到了这段代码,用我数据库中的数据创建了一个 JSON 文件:

<?php

$connect = mysql_connect("localhost", "root", "123", "boxr") or die("Error connecting with the host.");

$sql = mysql_query("SELECT * FROM users") or die(mysql_error());

$response = array();
$users = array();
$result = mysql_query ($sql);

while ($row = mysql_fetch_array($result)) {
    $gamertag = $row['gamertag'];
    $banned = $row['banned'];

    $users[] = array('gamertag' => $gamertag, 'banned' => $banned);

}

$response['users'] = $users;

$fp = fopen('users.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);

?>

问题是当我运行脚本时,它显示以下内容:

No database selected

我检查了我的代码两次,但我不知道为什么它告诉我。

4

3 回答 3

2

您必须选择数据库名称:

mysql_select_db ('your_db_name');

那么你可以这样做:

$connect = mysql_connect("localhost", "root", "123") or die("Error connecting with the host.");
mysql_select_db("boxr", $connect);

后来,纠正它:

$sql = mysql_query("SELECT * FROM users") or die(mysql_error());

while ($row = mysql_fetch_array($result))...

经过:

$sql = mysql_query("SELECT * FROM users") or die(mysql_error());    

while ($row = mysql_fetch_array($sql))...

如果您使用名称 $sql 调用函数,则以后不能输入 $result 的名称。

于 2013-07-04T17:02:45.810 回答
2

mysql_* 函数已弃用,但您可以更改查询

$sql = mysql_query("SELECT * FROM dbname.users") or die(mysql_error());
于 2013-07-04T17:03:23.907 回答
0

采用 :

$db_selected = mysql_select_db('db_name', $connect);
if (!$db_selected) {
    die ('Can\'t use db_name : ' . mysql_error());
}
于 2013-07-04T17:07:10.547 回答