如何从MySQL表中获取值 - PHP

时间:2013-04-29 21:26:11

标签: php mysql variables fetch

我很难从我的sql数据库中获取值。我的代码在下面,我试图显示$ balance,但是当我回应它时,它只显示“数组”。

这是我的数据库表的图像: database table

<?php 
session_start();
echo "<!DOCTYPE html>\n<html><head><script src='OSC.js'></script>";
include 'functions.php';

$userstr = ' (Guest)';

if (isset($_SESSION['user']))
{
    $user     = $_SESSION['user'];
    $loggedin = TRUE;
    $userstr  = " ($user)";
    $balancequery = mysql_query("SELECT balance FROM members WHERE user = '$user'"); 
    $balance = mysql_fetch_assoc($balancequery); 
}
else $loggedin = FALSE;

echo "<title>$appname$userstr</title><link rel='stylesheet' " .
     "href='styles.css' type='text/css' />" .
     "</head><body><div class='appname'>$appname$userstr</div>";

if ($loggedin)
{
    echo "<br ><ul class='menu'>" .
         "<li><a href='members.php?view=$user'>Home</a></li>" .
         "<li><a href='members.php'>Members</a></li>" .
         "<li><a href='stockdata.php'>Stocks</a></li>" .
         "<li><a href='logout.php'>Log out</a></li></ul><br />";
}
else
{
    echo ("<br /><ul class='menu'>" .
         "<li><a href='index.php'>Home</a></li>" .
         "<li><a href='signup.php'>Sign up</a></li>" .
         "<li><a href='login.php'>Log in</a></li></ul><br />" .
         "<span class='info'>&#8658; You must be logged in to " .
         "view this page.</span><br /><br />");
}
?>

2 个答案:

答案 0 :(得分:2)

mysql_fetch_assoc返回该行字段的关联数组。要回显该行中的字段,必须为其指定正确的索引,该索引将是字段的名称:

echo $balance["balance"];

此外,不推荐使用mysql php扩展。请查看MySQLiPDO_MySQL

答案 1 :(得分:1)

这是因为你试图回显一个associatove数组,这不起作用。尝试通过索引数组来打印为值

echo $balance['balance'];  //this is just array_name['column_name']

我想记住,mysql_函数已被弃用,因此我建议您切换到mysqliPDO