I got a numerical ID of 20 characters witch looks like 10527391670258314752, given this ID, how can I get the username associated with it?
The table looks like this:
id | name | password | balance
10527391670258314752 | Jhon | 12345 | 12.51
The username retrieved from the database should then be stored into $_SESSION['name']
.
I've tried this:
$connection = mysqli_connect('localhost', 'root', '', 'user_data');
$id = '10527391670258314752';
$query = "SELECT username FROM user_data WHERE id = '$id'";
$result = mysqli_query($connection, $query);
$record = mysqli_fetch_array($id);
$_SESSION['id'] = $record;
echo $_SESSION['id'];
The output is Array()
instead of the name.
That's actually a very good question that has almost no good answers on Stack Overflow.
Basically you need the following steps to perform a SELECT query using mysqli:
The detailed explanation can be found in my article, How to run a SELECT query using Mysqli, as well a helper function to simplify the routine.
Following this plan here is your code
$sql = "SELECT * FROM users WHERE id=?"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $id);
$Stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch the data
now you can store the username in the session variable:
$_SESSION['name'] = $user['name'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With