Storing database results to a variable in PHP - php

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]

Related

PHP Creating variables list from Mysql database

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];
}
}

PHP automatically create variables based on what is in mysql database

I dont know if this is possible, but am trying to create a php variable using an entry from a mysql database.
For example, lets say I want to create the following variables, but i want to replace google with whatever the company name is in the database.
$google = $row['companyname'];
$google_ticker = $row['ticker'];
$google_holding = $row['holding'];
So if I had a row in my database with the company name as Yahoo, the following would appear instead:
$yahoo = $row['companyname'];
$yahoo_ticker = $row['ticker'];
$yahoo_holding = $row['holding'];
I have tried different variations of the following however I cant get it to work (I know the code below wont work, its just an example of the sort of thing I have tried):
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$$row['companyname'] = $row['companyname'];
$$row['companyname']_ticker = $row['ticker'];
$$row['companyname']_holding = $row['holding'];
}
I can get it to work using something similar to the following, however doing it this way means I have to create each variable manually (as far as i know). I am trying to get it to create my variables automatically depending on what company names I have in my database.
$values = [];
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$values[$row['companyname']] = $row;
}
$google = $values['google']['companyname'];
$google_ticker = $values['google']['ticker'];
$google_holding = $values['google']['holding'];
Any ideas on how I can achieve this?
Many Thanks
Use a (multidimensional-)Array with KEYS that function as variable names:
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$data[$row['companyname']]['name'] = $row['companyname'];
$data[$row['companyname']]['ticker'] = $row['ticker'];
$data[$row['companyname']]['holding'] = $row['holding'];
}
Now you can access the holding variable like this:
echo $data['google']['holding'];
That should get you started...
Succes!
You can use like this:
${$row['companyname']} = $row['companyname'];
doc

Something is wrong with my custom php function

Okay so I am trying to create a custom function that will echo a site url inside an iframe for the end user.
The script has to check whether or not the user has already seen the site and if they have seen it don't display it any more, but take another site url from the database etc.
Here's what I have come up with so far:
function get_urls() {
require 'config.php';
global $con;
global $currentUsername;
$con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
$query = "SELECT site_url FROM sites WHERE site_url IS NOT NULL";
$result = mysqli_query($con, $query);
// Get all the site urls into one array
$siteUrls = array();
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row;
$index++;
}
$query2 = "SELECT site_url FROM views WHERE user = '$currentUsername' AND site_url IS NOT NULL";
$result2 = mysqli_query($con, $query2);
// Get urls the user has already seen into another array
$seenUrls = array();
$index = 0;
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2;
$index++;
}
// Compare the two arrays and create yet another array of urls to actually show
$urlsToShow = array_diff($siteUrls, $seenUrls);
if (!empty($urlsToShow)) {
// Echo the url to show for the iframe within browse.php and add an entry to the database that the user has seen this site
foreach ($urlsToShow as $urlToShow) {
echo $urlToShow;
$query = "INSERT INTO views VALUES ('', '$currentUsername', '$urlToShow')";
mysqli_query($con, $query);
break;
}
}
// Show the allSeen file when all the ads are seen
else {echo 'includes/allSeen.php';}
mysqli_free_result($result);
mysqli_close($con);
}
I have currently found two errors with this. First the $siteUrls and $seenUrls are all okay, but when I compare the two using array_diff then it returns an empty array.
Secondly the script doesn't write the site url into the database because the $urlToShow is an array not a single url?
I think the problem is in your code is at the place where you are creating your $siteUrls, $seenUrls arrays. mysqli_fetch_assoc() function will give you a result row as an associative array. So if you want to change some of your code in the while loops.
Please chnage this
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row;
$index++;
}
To
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row['site_url'];
$index++;
}
And in the second while loop also. Change this
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2;
$index++;
}
To
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2['site_url'];
$index++;
}
and try
i would not run two queries and try to merge the result array. you can use mysql itself to just return the sites that have not been seen yet:
SELECT sites.site_url FROM sites
LEFT JOIN views ON views.site_url=sites.site_url AND views.user='$currentUsername'
WHERE sites.site_url IS NOT NULL AND views.site_url IS NULL
This will return only site_urls from sites, that have no entry in the views table. The LEFT JOIN will join the two tables and for every non-matching row there will be NULL values in the views.site_url, so that is why i am checking for IS NULL.
Your saving of $urlToShow should work, if you set to $row field content and not $row itself as suggested, but if you want to check what is in the variable, don't use echo use this:
print_r($urlToShow);
If the variable is an array, you will see it's content then.
#Azeez Kallayi - you don't need to index array manually.
$seenUrls[] = $row2['site_url'];
In addition, you can fetch all result
$rows = mysqli_fetch_all($result2,MYSQLI_ASSOC);
foreach($rows as $row){
echo $row['site_url'];
}

Multiple PHP dynamic variables displaying other dynamic variable values

I am generating dynamic variables like so:
$testPMA = '';
$result = mysql_query("SELECT * FROM site_pma") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
${$testPMA.$row['id']} = $row['value'];
}
$testLocation = '';
$result = mysql_query("SELECT * FROM site_location") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
${$testLocation.$row['id']} = $row['value'];
}
then I try displaying them like so:
if(isset(${$testPMA.$row_bom_lines['pma']})) echo ${$testPMA.$row_bom_lines['pma']};
The first one returns correctly. The next column and any after always take their id number for the dynamic variable, but only generate PMA. They never update to show Location or any other one I have created. I even tried mysql_free_result($result); after each one. How do I get the dynamic variable to display each of their own vs displaying the same table information for each column, just with an updated id number?

Looping through MySQL results and saving values to a $_SESSION

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.

Categories