从我的SQL数据库调用值无法正常工作

时间:2013-06-29 22:47:59

标签: php html sql phpmyadmin

这是我的代码:

<?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 connect和html标题。

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

4 个答案:

答案 0 :(得分:0)

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

试试这个:

// 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/>";

答案 1 :(得分: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;

答案 2 :(得分: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"];
}

答案 3 :(得分: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);
}