-3
$id = mysql_query("SELECT id FROM account WHERE username='".$username."' LIMIT 1") or die(mysql_error);

$_SESSION['id'] = $id ;

echo ("ID: ".$_SESSION["id"]."");

It outputs "ID: 0" while the id of the account in the database should be 1 instead. Please help!

xenazfire
  • 63
  • 1
  • 1
  • 9
  • have a look at what `var_dump($id)` outputs after your myswl_query and that should give you a hint as to where it's going wrong. – Stu Mar 16 '13 at 11:56
  • $id will return a resource value like #7 resource. Its not a good thing to save it in your session! – Oh What A Noob Mar 16 '13 at 11:58

2 Answers2

2

mysql_query returns a resource. The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

$result = mysql_query("SELECT id FROM account WHERE username='".$username."' LIMIT 1") or die(mysql_error); 
while ($row = mysql_fetch_assoc($result)) 
{
    $_SESSION['id'] = $row['id'] ;
}
echo ("ID: ".$_SESSION["id"]."");

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • Thanks! It works! Alright. Gonna read up on preventing mysql injections. – xenazfire Mar 16 '13 at 12:26
  • Hi @JW, all is working well but is it possible to store the same id in the session to the database? I tried to store the same id from the session to the database but it won't be inserted. – xenazfire Mar 16 '13 at 16:44
2

try this

$id = mysql_query("SELECT id FROM account WHERE username='".$username."' LIMIT 1") or die(mysql_error);

while($myid = mysql_fetch_array($id)){

$_SESSION['id'] = $myid ;

}

echo ("ID: ".$_SESSION["id"]."");
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Athar Ahmed
  • 151
  • 10