I am trying to store each column name in my database into its own $_SESSION. For example, say my column names are column_one, column_two, column_three, column_four, and column_five. I want these to be stored in a $_SESSION like $_SESSION['column_one'], $_SESSION['column_two'], etc. I am trying to do this in a loop but I have not been successful. How would I setup the loop to achieve this?
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);
if ($num == 1) {
//User was found
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$_SESSION['user_id'] = $row['user_id'];
}
}
Could you try this:
$id = mysqli_real_escape_string($dbc,$id);
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num= mysqli_num_rows(result);
if ($num == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['UserData'] = $row;
}else{
//handle error or user not found
}
echo '<pre>';
print_r($_SESSION['UserData']);
echo '</pre>';
You don't have necessity of use while or another loop, so is just one row
Something like this should work:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach($row as $column => $value) {
$_SESSION[$column] = $value;
}
}
Extra advice for safeguarding against SQL injection, the following two lines:
$id = mysqli_real_escape_string($dbc, $id);
$query = "SELECT * FROM table WHERE user_id = '$id'";
Update:
Thanks to EmilioGort who pointed out the missing connection parameter in mysqli_real_escape_string. See mysqli_real_escape_string docs.
While the other answers proposed a way to do, I'd strongly propose to not do this at all. Why?
First of all $row contains all details of the user in a well defined array form. It is generally good to keep this structure well prepared.
More important: Flattening $row might force name clashes like so:
Suppose $row has a property userName and somewhere else in your application you eventually set
$_SESSION[ 'userName' ] = $newUserName;
The new assignment to $_SESSION[ 'userName' ] might unintentionally change the property saved during the login process.
You might argue "Right now, my code doesn't use userName in $_SESSION'. Right! Unfortunately, you might use just this name for something else many month later on...
A better solution
I'd save the user detail like this:
$_SESSION[ 'sys$userDetails' ] = $row;
Imagine the prefix sys$ as being an indicator for framework generated properties of your session.
Thus, business logic related session data shouldn't have the sys$ prefix.
Related
I am trying to store the result from a MySQL statement for later use in PHP. I have this code which gets me the result:
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
}
}
So I know i will have the results in $row["id"] and $row["name"] and I want to save all of the rows so whenever i need them i can loop through them and for example echo them. I have searched for structures and arrays for keeping them in PHP but I cannot seem to find any information about that or maybe I am not searching in the right direction. Can anyone point me where i should read about this to find out how to do this efficiently and if possible post a small example?
Use sessions:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
$_SESSION['category_' . $row['id']] = $row['name'];
}
}
Then access it later from a different page
$_SESSION['session_variable_name']
You can also create an array of the information and store the entire array in a single session variable.
Just make sure you add the session_start function at the beginning of each page. The if statement prevents you from trying to start it multiple times.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
while ($row = $result->fetch_assoc())
{
$categories[$row['id']]=$row['name'];
}
}
And If you want the name anywhere use below :
$categories[$id]
I've a database that using for 3 languages this way:
id name de_de al_sq
1 title titel titulli
2 points punkte pike
Now when in php $lang is set to 'al_sq':
$lang = 'al_sq';
I'm trying to generate variables using names of that language, in this case:
$langtitle = 'titulli';
$langpoints = 'pike';
Trying something like:
$sql = "SELECT * FROM `langs`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$lang{$row["lang"]} = $row[$lang];
}
}
but something is not good, how to generate these variables?
You have a minor syntax error in your code, which causes an error. What you need to do here is to:
Fetch the name and al_sq columns from the database table. This is done by selecting the value of $lang (based on your code). For security reasons, the value of $lang is protected against SQL injection, as you did not specify where the value was coming from.
Then you must check if there was any results, and in the case there wasn't any, it will simply terminate the script with an error.
Then lastly you must iterate over each row of the returned results, and do a variable variable assignment. This will make $langpoints etc. work (and any other you may add in the future).
Code:
$sql = 'SELECT `name`, `' . $conn->real_escape_string($lang) . '` FROM `langs`';
$result = $conn->query($sql);
if (!$result || !$result->num_rows) {
echo 'Invalid language selected';
exit;
}
while ($phrase = $result->fetch_assoc()) {
${'lang' . $phrase['name']} = $phrase[$lang];
}
// $langtitle
// $langpoints
It seems you are using the database as a key-value store with multiple value fields depending on the language, you could use PDO::FETCH_KEY_PAIR so it returns an array with the name as the key. This way you also avoid loading the data for other languages that you might not need at all:
$query = "SELECT `name`, :column as value FROM `langs`";
$statement = $pdo->prepare($query);
$statement->execute(["column" => $lang]);
$data = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
// $data becomes an array with the name as the key:
$langtitle = $data['title'];
$langpoints = $data['points'];
Make sure, if the user provides the value for $lang, to check that it is a valid column value.
This should be close to what you are wanting based on how your database is presented. Scaling up would be clunky though if there is more the title and points stored.
$lang = 'al_sq';
$sql = "SELECT $lang FROM 'langs'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$langtitle = $row[1];
$langpoints = $row[2];
}
}
I've seen there there are numerous ways to put the results of a SQL query into usable format (that is, variables).
If I have a targeted SQL query that I know will be returning a set of expected values, lets say querying a customer number to pull data, city, state, first and last name, etc..
Code example follows:
$example = '50';
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
if ($col == 'firstname') {
$customerfirstname = $val;
}
}
}
or another way:
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
$myResultArray = array();
while ($row = mysql_fetch_assoc($result))
$myResultArray = $row;
foreach ($myResultArray as $val) {
$customerfirstname = $val['firstname'];
}
That's just two that I could think of.
Is one of the above methods preferable over the other? If so, why?
Is there an alternate method that is even more efficient than either of these?
Neither are preferred.
The foreach's are superfluous.
Since you know the fieldnames you need, you can just do:
while ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
If you do need to apply a conditional for some reason, you can test for the field's existence in the array:
while ($row = mysql_fetch_assoc($result)) {
if (isset($row['firstname'])) {
$customerfirstname = $row['firstname'];
}
}
Finally, since you appear to be selecting by primary key, the while loop is also unnecessary:
if ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
I have used the first example that you posed in every website I have done that requires a database and it hasn't failed me yet. As far as if one is better than the other I'd say no. It's just a matter of taste.
There are many ways. Here's a quick one, but I would prefer to set it up using a DTO and accessing it that way... this will work though for your question.
$query = "SELECT first_name, last_name, city FROM customers WHERE customer_id = '$example'";
$result = mysql_query($query);
// If you are expecting only one row of data, then use this:
list($first_name, $last_name, $city) = mysql_fetch_row($result);
//several rows:
while(list($first_name, $last_name, $city) = mysql_fetch_row($result)){
echo $first_name;
}
I seem to be missing something...
Why not this?
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
while ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
In the first example?
I have a basic PHP function that I am working with. Sometimes, it is passed an array of variables, and other times it is just passed one variable. So, currently, I have something like this:
<?
function do_this($user_id_array) {
$user_ids = array();
foreach ($user_id_array as $single_user_id) {
$sql = 'SELECT username FROM users
WHERE id = $single_unit';
while($row = mysql_fetch_assoc($result)) {
array_push($user_ids, $row['id'];
}
}
return $user_ids;
}
?>
My issue is this: If I call the function and send it only one variable (and not an array), it (obviously) gives me the following error: Invalid argument supplied for foreach()
My question is: How can I change this function in the most efficient way with the least amount of code? Do I have to use an if is_array() statement and just create 2 SELECT statements, one for each case (array and non-array)?
Many thanks!
I see several options:
Pass an array even if it's one element long
Test for is_array() and act accordingly
Add another argument which states whether to check for an int or an array.
I'd go with options 1 or 2, as option 3 is error prone.
Also, there might be a better solution to your problem, you shouldn't have a single query for every user, you should instead use the IN keyword in MySQL, something like this:
$users = (is_array($user_id_array)) ? implode(',',$user_id_array) : $user_id_array;
$query = "SELECT `username` FROM `users` WHERE `id` IN({$users})";
wow. that's a lot of queries. What about to delete foreach and do something like
if (is_array($user_id_array)){
$sql = 'SELECT username,id FROM users
WHERE id IN ('.implode(",", $user_id_array).')';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$users[$row['id']] = $row;
}
}
You can write:
$user_id_array = (array)$user_id_array;
if (!is_array($user_id_array))
$user_id_array = array($user_id_array);
function do_this($user_id_array) {
$ids = array_map('intval', (array)$user_id_array);
$sql = 'SELECT username FROM users
WHERE id IN(' . implode(',', $ids) . ')';
$result = mysql_query($sql);
$usernames = array();
while ($row = mysql_fetch_assoc($result)) {
$usernames[] = row['id'];
}
return $usernames;
}
First line makes sure that you have an array ((array)$user_id_array) and that all values are valid integers. Then a single SQL query is executed for all user ids.
I just submitted my work and my course leader has asked me to use PHP functions to query my database. How can I do this? Is it possible to add just "function getRooms" before my queries, and return the desired result. I need thorough briefing on functions with MySQL.
For example:
How will I add a function to this code:
<?php
// By Kelvin
include ("player.php");
$result = mysql_query("SELECT * FROM phplogin WHERE username = '$username'");
$row = mysql_fetch_assoc($result);
$medipack = $row['medipack'];
if ($_POST['object'] == "Use Medipack") {
if ($medipack != 0) {
mysql_query("UPDATE phplogin SET score = score + 50, health = health + 50, medipack = medipack - 1
WHERE username = '$username'");
echo ("<P>Medipack Used!</P>");
$RoomNumber =5;
}
else {
echo ("<P>You're all out of medipacks!</P>");
}
}
?>
If he's looking for a level of abstraction between the rest of your code and the code accessing the database, wrapping the database logic in functions should be on the right path:
function getRooms($link){
$sql = "SELECT * FROM rooms";
$data = array();
if($set = mysql_query($sql)){
while($row = mysql_fetch_assoc($set)){
$data[] = $row;
}
}
return empty($data)
? null
: $data;
}
$db_connection = mysql_connect('host', 'user', 'pass');
mysql_select_db('name', $db_connection);
$rooms = getRooms($db_connection);
Wrapping these functions into a class, and accessing them by methods is another step, as the instantiated object can manage its own connection, etc., but that may be a step further than necessary. Other functions (based on what I can guess) might be:
function getRoomById($link, $id){ }
function getRoomsByName($link, Array $names){ }
I would imagine your course leader is referring to the PHP's native MySQL functions - http://php.net/manual/en/book.mysql.php
You can wrap your queries inside PHP functions. For example, like this:
function &getRooms(){
$query="SELECT id,name FROM rooms";
$result=mysql_query($query);
$ar_out=array();
while ($row = mysql_fetch_assoc($result)) {
$ar_out[]=$row;
}
return $ar_out;
}
This said, you really should find a tutorial or a book on how to use MySQL and PHP together. There are many things to know about code organization and performance.