Multiple PHP dynamic variables displaying other dynamic variable values - php

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?

Related

Storing database results to a variable in 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]

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 query get result from select

hi I need help with 2 mysql queries I am working on. I need to get data from first query and use it in second query.
First query (get different extension for domains)
$resultExt = mysql_query("SELECT * FROM extension”) or die(mysql_error());
while($rowExt = mysql_fetch_array( $resultExt )) {
$extDom = $rowExt[‘ext’];
$postDom = 'Domain_’ . $extDom ;
$dom_to_show .= '$rowCart[$postDom];';
}
and I get my list of domain extensions
$Domain_com = $rowCart[‘Domain_com’]; $Domain_net = $rowCart[‘Domain_net’];
and so on
Second Query (get data from cart)
then I need to get data from cart table
$showCart = mysql_query("SELECT * FROM cartlist where Session = '".$session."' ORDER BY ID DESC") or die(mysql_error());
while($rowCart = mysql_fetch_array( $showCart )) {
//here i need to get variable like $Domain_com = $rowCart['Domain_com’];
//if I use echo $dom_to_show; or $dom_to_show; I get no result
}
what do I need to put inside the second while to get results from query?
thanks
The echo should echo out a result, i have added an array that will get all the data in the row and output it after it has ran. This will help you see if there is any data returned from the query.
$showCart = mysql_query("SELECT * FROM cartlist where Session = '".$session."' ORDER BY ID DESC") or die(mysql_error());
while($rowCart = mysql_fetch_array( $showCart )) {
//here i need to get variable like $Domain_com = $rowCart['Domain_com’];
//if I use echo $dom_to_show; or $dom_to_show; I get no result
echo $rowCart['Domain_com'];
//or
$array[] = $rowCart;
}
echo "<pre>";
print_r($array);
also
$rowCart['Domain_com'];
was set to
$rowCart['Domain_com’];
which is wrong.

Extract a specific value from this data type

I'm using this script to get data from a database
$sql = "SELECT * FROM items WHERE catid = 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row['extra_fields'];
}
The output is:
[{"id":"1","value":"johndoe"},{"id":"2","value":"marydoe"}]
I want to extract/print only the value corresponding to "id":"1" (that in this case is 'johndoe'). I'm not able to extract it from the above data type.
To read JSON in PHP use
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields'];
// Do something with $array['id']
}
Did you realise you can directly go for that data in MySQL?
SELECT value FROM items WHERE id = 2;
edit:
Basically your query is
SELECT comma-separated column names or star for all, use only what you really need to save bandwidth, e.g. SELECT id, value
FROM table-name, e.g. FROM mytable
WHERE columnname = desired value, e.g. WHERE id = 2
You want to query only the required columns in the required rows. Imagine one day you would have to parse 1 million users every time you want to get an id... :)
The output is JSON. Use PHP's json_decode function.
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
foreach($array AS $item) {
echo $item['id'];
}
}
Currently this is the code that fits my needs:
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
$value = $array[0]->value;
}
You should do it in the mysql query part. For example, set the ID = 1 in the query.

Accessing array data from mysql database and php

I have two mysql tables with information:
One table stores page information like its name and location as well as an array column to store what widgets to show per page stored in array format: 1,2,3,4
The other table is the actual widget table with the widget info and the id as its identifier ex: 1,2,3,4
I need to:
Get array data from the page table
Loop through that array and display content from the widget table.
Ive been working with foreach statements:
The url for each page follows this format index.php?page=thispage&route=thisroute thus the $_GET['page']
$page = $_GET['page'];
$order = "SELECT * FROM pages where name='$page'";
$result = mysql_query($order);
while($row = mysql_fetch_array($result)){
$widget = array();
$widget .= $row[3];
}
print_r($widget);
foreach($widget as $w) {
$order = "SELECT * FROM menu where id='$w'";
$result = mysql_query($order);
while($row = mysql_fetch_array($result)){
print $row[1];
}
}
UPDATE: Figured out a solution that works for me.
The reason behind keeping the comma separated values is because i could have one widget per page or 15 widgets per page and each widget can be added on the fly. And from the administration side i want to be able to select which widgets each page can have.
When keeping the data in comma separated values where all the data is in ONE column "1,2,3,4".
Ill just stick to exploding the data into an array and looping through each value of the array:
$page = $_GET['page'];
$order = "SELECT * FROM pages where name='$page'"; //select widgets to show on page
$result = mysql_query($order);
while($row = mysql_fetch_array($result)){
$widget = $row[3];
$string = preg_replace('/\,$/', '', $widget); //remove trailing comma
$array = explode(', ', $string);
foreach($array as $value) //loop over values
{
$order = "SELECT * FROM widget where id='$value'";
$result = mysql_query($order);
while($row = mysql_fetch_array($result)){
print $row[1]; //print data: this will be formated to the specific divs set up.
}
}
}
Get array data from the page table:
SELECT array_column_name FROM table_store_page WHERE id=your_id (use this sql to fetch the array in)
Execute the SQL statement in php maybe using mysql_query
Anyway, STORING array/comma-separated values in Database is NEVER RECOMMENDED. You can try normalizing your Database.

Categories