php - 简单的 MYSQL 查询后无法访问用户的名字

标签 php html mysql sql

我想要“欢迎,[用户名]!”出现在我网站的页面上。

我执行这个查询:

我尝试过的选项 1:

$first_name = mysql_query("SELECT first_name FROM users WHERE id = $user_id");

echo "Welcome, " . $first_name . "!";

我尝试过的选项 2:

$users = mysql_query("SELECT * FROM users WHERE id = $user_id");

    if (count($user) == 1)
    {
        // first (and only) row -- meaning only one user in this array
        $user = $users[0];

        echo "first_name: " . $user['first_name'] . "!";
    }

我的用户表中的一行如下所示: 编号 |名字 |姓氏 |电邮 |密码

我已经测试并成功获得了用户的 ID。我的 SQL 查询也经过测试并且有效。

这是插入到 HTML 代码中的 php 代码。

我在访问用户的 first_name 时遇到了困难 - 非常感谢您的帮助!

最佳答案

您忘记获取结果

$users = mysql_query("SELECT first_name  FROM users WHERE id = $user_id");
$row = mysql_fetch_assoc($users);
echo $row['first_name'];

仅供引用,you shouldn't use mysql_* functions in new code .它们不再维护 and are officially deprecated .查看red box ?了解 prepared statements相反,并使用 PDOMySQLi - this article将帮助您决定选择哪个。如果选择 PDO,here is a good tutorial .

关于php - 简单的 MYSQL 查询后无法访问用户的名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24538485/

相关文章:

php - 在网页上显示 PHP/SQL 查询以进行调试

html - Facebook Linter 显示 og :type as webpage when it is defined as company

mysql无法使用mysql if condition in order by

html - 如何让我的 anchor 标签移动到导航栏的右侧?

html - ul li列表的CSS问题

php - jquery 自动完成功能不适用于 php mysql

mysql 在哪里匹配

php - MySQL:使用 CASE/ELSE 值作为连接参数

php - 在 MySQL 中选择格式错误的 URL

php - MySQL查询返回非对象?