The userâs information is stored in a database table, when the user registered. You would query that database table, using a SELECT query, to find and then fetch the row of data that matches the userâs id thatâs stored in the login session variable.
The reason I/we donât write out verbose paragraphs like that in every reply is, no one would continue to post replies if each one has to cover every fundamental building block and knowledge about what you have already done, leading up to the point where you are at. Learning and growing in any task involves building on and using prior knowledge gained.
Have a look at the fetch function. When you call execute, that returns a pointer to a set of results, you then need to use fetch to get the results out of it.
Which protocol should I be using? PDO or MySQLi? I know I can do it both ways, but I donât really understand the difference between the two (except that PDO can work on 12 different database systems and MySQLI only works on MySQL, which means Iâd have to rewrite everything if I change it) and which is the best way to do it?
$sql_query = $pdo->query("SELECT first_name FROM users WHERE id = {$_SESSION['id']}");
$result = $sql_query->execute();
$first_name = implode($sql_query->fetch(PDO::FETCH_ASSOC));
This code runs the defined query in the $sql_query variable. When executed by $result, it is produced as an array rather than a string. To convert it, I used implode on the last line followed by PDO::FETCH_ASSOC to call the array for conversion.
I have a feeling what is happening may not be clearly understood. A way that helps me a lot of times is to add a short data type to variable names. eg.
$sql_query_rs = $pdo_obj->query("SELECT first_name FROM users WHERE id = {$_SESSION['id']}");
$result_rs = $sql_query_rs->execute();
$first_name_str = implode($sql_query_rs->fetch(PDO::FETCH_ASSOC));
It looks like â$resultâ would error to me. Any chance reporting / display are off and it isnât being used anywhere?
Iâm using implode() here so that I can convert the result of the query into a string which can be used to show Welcome, (first name here)! Is there a better way to do it?
$stmt = $pdo->prepare(âSELECT first_name FROM users WHERE id =?â);
$stmt->execute([$_SESSION[âidâ]]);
$name = $stmt->fetchColumn();
echo $name;
I see. Thanks for that! I checked the manual and replaced the code accordingly:
$name_query = $pdo->prepare("SELECT first_name FROM users WHERE id = ?");
$name_query->execute(array($_SESSION['id']));
$username = $name_query->fetchColumn();