tdrsam
tdrsam

Reputation: 527

php mysql - add user_id to session variable

When I register a user I add them to a database and they get an id which is auto generated by auto_increment. Now I'm trying to add that id to a session variable so I can use it on other pages in the website and manipulate their row in the database. This is what I have so far.

This line adds the form inputs to the db when the user registers:

$insert = mysql_query("INSERT INTO users (`email`, `password`) VALUES ('example','values'))");

Then I'm trying to get the user_id into a variable that I can use on other pages of the website. I'm trying this:

if ($insert) {
  $select_id = mysql_query("SELECT `id` from `users` WHERE `email` = '$form_input'");
  $id_arr = mysql_fetch_array($select_id);
  $id_var = $id_arr['id'];
  session_start();
  $_SESSION["Register"] = $id_var[0];
}

But it doesn't work so I'm trying a var_export to see what's in $id_var and I get a value of '3' which doesn't match the user_id that supposed to be stored in the variable.

Upvotes: 0

Views: 70

Answers (3)

Passionate Coder
Passionate Coder

Reputation: 7294

as Comments by Jens. I strongly recommend to use mysqli or even better PDO. As mysql is depreciated and completely removed in PHP7.

now as per your code try this

 if ($insert) {
      $select_id = mysql_query("SELECT `id` from `users` WHERE `email` = '$form_input'") or die(mysql_error());// to see error
if($select_id != null){
      $id_arr = mysql_fetch_array($select_id);
      $id_var = $id_arr['id'];
      session_start();
      $_SESSION["Register"] =   $id_var;
    }
}

Upvotes: 0

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

You need to iterate over the result set to get the value of id

$id="";
while ($row = mysql_fetch_array($select_id))   
{    
  $id= $row ['id'];
}
if($id!=""){
   session_start();
   $_SESSION["Register"] = $id;
}

Note: mysql_query 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.Alternatives to this function include: mysqli_query() or PDO::query()

Moreover, passing the values directly into the query is not safe. Please, read about SQL injection

Upvotes: 1

Tamil
Tamil

Reputation: 1203

You can use mysql_insert_id()

mysql_query("INSERT INTO mytable (1, 2, 3, 'blah')");
$last_id = mysql_insert_id();

See this : mysql_insert_id()

Note: mysql_query 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.Alternatives to this function include: mysqli_query() or PDO::query()

Upvotes: 0

Related Questions