0

这是我的代码:

<?php
include("inc/incfiles/header.inc.php");
session_start();
$user_id = $_SESSION["id"];
if (!isset($_SESSION["id"])) {
    header("location: index.php");
}
else {
    echo "Welcome, user number " . $user_id . ". This is you're newsfeed!";
    echo "<br><a href=\"logout.php\">Log Off?</a>";
}

echo "<br><br>";

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

echo "First Name: " . $userFname . "<br>";
echo "Last Name: " . $userLname . "<br>"; ?>

header.inc.php 文件仅用于 sql 连接和 html 标头。

我现在的问题是,当我调用名字和姓氏时,它只会给出输出“资源 ID #6”和“资源 ID #7”。我不明白为什么它不显示实际的名字和姓氏?

4

4 回答 4

0

PHP 的mysql_query()函数不会返回SELECT子句中的“东西”。相反,它返回一个资源,您可以使用它来获取该“东西”。

尝试这个:

// Obtain the resource:
$resource = mysql_query("SELECT first_name FROM users WHERE id=$user_id");

// From that resource, get a row of data as an associative array
// The keys in that array will match the names in your SELECT clause
$row = mysql_fetch_assoc($resource);

echo "First Name: " . $row['first_name'] . "<br/>";
于 2013-06-29T22:54:45.890 回答
0

函数mysql_query返回一个您仍需要解析的结果集。添加这一步:

$result = mysql_query("SELECT first_name FROM users WHERE id=$user_id");
$userFname = mysql_fetch_object($result);
echo $userFname->first_name; //will print the user's first name

mysql_fetch_object将使用表的列作为属性初始化对象。

鉴于您的情况,我可能只会获取一个用户记录并使用同一对象中的两个名称属性:

$result = mysql_query("SELECT * FROM users WHERE id=$user_id");
$user = mysql_fetch_object($result);
echo $user->first_name;
echo $user->last_name;
于 2013-06-29T22:55:13.280 回答
0

函数“mysql_query”实际上并没有返回结果值,你接下来需要调用这样的东西:

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

$result = mysql_query("SELECT last_name FROM users WHERE id=$user_id");
$row = mysql_fetch_assoc($result);
$userLname = $row["last_name"];

甚至更好:

$result = mysql_query("SELECT first_name, last_name FROM users WHERE id=$user_id");
$row = mysql_fetch_assoc($result);
if($result) {
    $userFname = $row["first_name"];
    $userLname = $row["last_name"];
}
于 2013-06-29T22:55:30.620 回答
0

mysql_query() 返回一个result资源,而不是实际数据。

您需要使用其中一种fetch功能提取数据。您的代码应如下所示:

$result = mysql_query("SELECT first_name, last_name FROM users WHERE id=$user_id");
if ($result === false) {
     echo mysql_error;

} else {
 list ($userFname, $userLname) = mysql_fetch_array($result);
}
于 2013-06-29T22:56:09.470 回答