1

我的 MySQL 数据库设置为名称为“chatterr”,表名称为“maillist”。我目前正在使用下面的php:

<?php
mysql_connect("localhost","root","");

//query databae
$query = "SELECT * FROM maillist ORDER BY id DESC LIMIT 4";
$result=mysql_query($query) or die('Error, insert query failed');
$row=0;
$numrows=mysql_num_rows($result);

while($row<$numrows) {
    $id=mysql_result($result,$row,"id");
    $first_name=mysql_result($result, $row, "first_name");
    $last_name=mysql_result($result, $row, "last_name");
?>

<?php echo $id; ?>

<?php
$row++;
}
?>

它适用于本地主机,但不适用于 PHP。代码有什么问题?

4

2 回答 2

3

mysql_select_db在查询之前选择一个数据库

mysql_connect("localhost","root","");
mysql_select_db("chatterr");

或在查询中指定数据库名称

$query = "SELECT * FROM chatterr.students ORDER BY id DESC LIMIT 4";

更新:除此之外,您的连接可能失败。改变

mysql_connect("localhost","root","");

$db = mysql_connect("localhost","root","");
if (!$db) {
    die('Could not connect: ' . mysql_error());
}

看看是不是这样。

UPDATE3:把它们放在一起。尽管该代码有很大的改进空间,但它在我的机器上运行良好。

<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("chatterr", $db);
if (!$db_selected) {
    die ('Could not select db: ' . mysql_error());
}

//query databae
$query = "SELECT * FROM test.students ORDER BY id DESC LIMIT 4";
$result=mysql_query($query) or die('Error, insert query failed');
$row=0;
$numrows=mysql_num_rows($result);

while($row<$numrows)
{
$id=mysql_result($result,$row,"id");
$first_name=mysql_result($result,$row,"first_name");
$last_name=mysql_result($result,$row,"last_name"); ?>

<?php echo $id; ?>

<?php

$row++;
}
?>

请不要将 mysql_* 函数用于新代码。它们已被 弃用。对PDOMySQLi使用 准备好的语句

于 2013-03-10T06:09:02.313 回答
0

这样做:

<?php
$con = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("chatterr",$con) or die(mysql_error());

//query database
$query = "SELECT * FROM maillist ORDER BY id DESC LIMIT 4";
$result=mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result))
{
    $id = $row["id"];
    $first_name = $row["first_name"];
    $last_name = $row["last_name"];
}
?>
于 2013-03-10T06:07:01.057 回答