php - MySQL 查询和显示不工作?

标签 php html mysql

我的 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。代码有什么问题?

最佳答案

选择带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++;
}
?>

And please, don't use mysql_* functions for new code. They are deprecated. Use prepared statements with either PDO or MySQLi.

关于php - MySQL 查询和显示不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15319438/

相关文章:

php - 如何在 php 中完成验证?

html - Font Awesome 堆叠图标大小

mysql - 升级 MySQL ZIP,从 5.6 到 8 - 不工作

php - 需要 ext-fileinfo。如何将其添加到我的 composer.json 文件中?

php - 使用 PHP 的 preg_replace() 只返回 <h1>?

php - 在 HTML 中重复表格标题

html - 如何让我的表格在移动 View 中按行折叠

javascript - 链接 jquery 文件未按预期工作

php - 多个连接与缓存的单个查询?

mysql - 如何将日期、年份和月份更新到mysql中的现有表