Herlambang Permadi
Herlambang Permadi

Reputation: 95

Get other variable using session

I have table user like:

  user
=======
username
password
var

After login, I want to print variable var using username session like this, but have not had any success yet.

<?php

if(empty($_SESSION)){
    header("Location: logout.php");
}
$username=$_SESSION['username'];

$link = mysql_connect("localhost", "root", "");
mysql_select_db("vhts", $link);

$var = mysql_query("SELECT var FROM user where username='$username'", $link);
echo $var;

?>

How can this be corrected?

Upvotes: 1

Views: 37

Answers (2)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

mysql_query() returns a boolean or a resource. When the return value is a resource, the values can be fetched with a call to a function like mysql_fetch_assoc().

$result = mysql_query("SELECT var FROM user where username='$username'", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$var = $row['var'];   
echo $var;    
?>

Important Note:

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

(Source: http://php.net/mysql_fetch_assoc)


So you should really consider using mysqli_query(), mysqli_fetch_array(), etc.

Upvotes: 2

Shahaf Antwarg
Shahaf Antwarg

Reputation: 497

"SELECT var FROM user where username='$username'"

should work.., and the var would probably be in

$var['var']

and don't forget to add the fetch function

$var = mysql_fetch_assoc($var); // highly recommended to use mysqli / PDO

Upvotes: 0

Related Questions