Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the user_id from mysql using procedural php?

Tags:

php

mysql

I am an android/java developer and Im struggling with php. I've made it as far as inserting a new user in the DB, now I want to get their ID.

What do I do with the result? I want to assign it to a variable.

$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email . "'";
$result = 

PS: Im using mysql, not mysqli.

EDIT: Here is what I did:

$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email ."';";
$store_info = mysql_fetch_array(mysql_query($query)); 
$user_id = $store_info['user_id'];
$response["message"] = "User created with id: " . $user_id;
echo json_encode($response);

And the error message after inserting (successfully) the user in the db:

null{"success":3,"message":"User created with id: "}
like image 373
Kaloyan Roussev Avatar asked Nov 24 '25 02:11

Kaloyan Roussev


2 Answers

I assume that your are using MySQLi API

$query = "SELECT user_id FROM users WHERE user_email = '$user_email'"; //Your Query

$store_info = mysqli_fetch_array(mysqli_query($connection, $query)); 
//Execute the query, fetch the result, it's just one result so no need for a while loop

echo $store_info['user_id']; //echo id

As per the comments, you requested a mysql_() version so here you go...

$query = "SELECT user_id FROM users WHERE user_email = '$user_email'"; //Your Query

$store_info = mysql_fetch_array(mysql_query($query)); 
//Execute the query, fetch the result, it's just one result so no need for a while loop

echo $store_info['user_id']; //echo id

Still consider using mysqli_() or PDO instead. Why? Because mysql_() is now deprecated, read the red box on the documentation page which says...

enter image description here

Refer this answer for PDO tutorial

like image 57
Mr. Alien Avatar answered Nov 26 '25 18:11

Mr. Alien


Here is the PDO variant:

<?php
//credentials
$host = 'localhost';
$user = "user";
$password = '';
$db_name = 'test';
$port = 3306;

//connection to the database
try
{
    $connection = new PDO("mysql:host=$host;port=$port;dbname=$db_name", $user, $password);
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
    echo 'Connection failed: ' . $e->getMessage();
}

//prepare and execute SELECT statement
$sth = $connection->prepare("SELECT user_id FROM users WHERE user_email = :email");
$sth->execute(array(':email' => $user_email));

$record = $sth->fetch(PDO::FETCH_ASSOC);
print $record["user_id"];
like image 39
user4035 Avatar answered Nov 26 '25 17:11

user4035