Reputation: 99
I have the following PHP code on my site:
$query="SELECT lastname FROM user";
$result=mysql_query($query);
The name of the field I want to show on my webpage is lastname
, while user
is the name of the table itself.
The HTML body of my website is:
Welcome <?php echo $_SESSION['$result']; ?>.
This is not working, can someone please assist me.
Upvotes: 1
Views: 14107
Reputation: 11
$result is a "resource", containing the results of the query. However, what you probably want is to loop through all the results (since that query will return the lastname of every row in 'user')
$query="SELECT lastname FROM user";
$result=mysql_query($query);
while (($row = mysql_fetch_array($result)) !== FALSE) {
echo "The lastname for this row is " . $row['lastname'] . "<br />";
}
You should also look into mysql_fetch_assoc
Upvotes: 1
Reputation: 1128
mysql_query will return a resource so displaying it straight is not the right thing to do. You can better use:
while($row=mysql_fetch_array($result))
{
//echo the relevant fields.
echo(row[0]);
}
You can also use print_r method to dump the whole of the resource. Use echo(mysql_error()) if there is some other fault in the code. You should also read the mysql_query documentation on the php site as it is used a lot.
Upvotes: 0
Reputation: 2094
You would do:
<?php
$query = "SELECT lastname FROM user";
$result = mysql_query($query);
$row = mysql_fetch_assoc($query);
?>
Welcome <?php echo $row['lastname']; ?>.
The array $row
will contain all the values from the selected row.
Upvotes: 0
Reputation: 11697
There are a few things missing here:
The query selects all lastname
's from the table, not just one. You probably need a query like this (assuming $_SESSION['username'] is where you store their username):
$query="SELECT lastname FROM user WHERE username = " . $_SESSION['username'] . ";";
The code does not actually fetch the result set. It just runs the query. You need to run mysql_fetch_assoc() to get the first row of the result set:
$row = mysql_fetch_assoc($result);
You're never setting $_SESSION['$result']
. You should set a variable like so:
$_SESSION['lastname'] = $row['lastname'];
And echo it like so:
Welcome <?php echo $_SESSION['lastname']; ?>.
Putting it all together:
<?php
$query="SELECT lastname FROM user WHERE username = " . $_SESSION['username'] . ";";
$result=mysql_query($query);
$row = mysql_fetch_assoc($result);
$_SESSION['lastname'] = $row['lastname'];
?>
<html>
<head>
<title>My page</title>
</head>
<body>
Welcome <?php echo $_SESSION['lastname']; ?>.
</body>
</html>
Upvotes: 1
Reputation: 48887
$result
will contain just a resource handler. You use that to fetch rows:
<?php
$query = "SELECT lastname FROM user";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
?>
Welcome <?php echo $row['lastname'] ?>
Upvotes: 2