create PHP Variables from data in a table - php

I have a table called global_settings with 2 columns (field, value)
i need a way to make each row a variable
so for example:
is field = title and value = hello i would need:
$title = 'hello';
I have tried doing this:
$global_sql="SELECT * from global_settings ";
$global_rs=mysql_query($global_sql,$conn) or die(mysql_error());
while($global_result=mysql_fetch_array($global_rs))
{
$global_sql2="SELECT * from global_settings where field = '".$global_result["field"]."' ";
$global_rs2=mysql_query($global_sql2,$conn) or die(mysql_error());
$global_result2=mysql_fetch_array($global_rs2);
$global_result2["field"] = $global_result2["value"];
}
but that didn't work - any ideas?

I strongly suggest you do not auto-create variables from your DB. You'll be littering your script's namespace with potentially useless variables, and probably overwriting other variables you DID want to keep separate. Do it as you are - store the settings in an array.
Plus, unless I'm totally misreading your code, there's absolutely no reason for the sub-query. A simple:
$settings = array();
$sql = "SELECT field, value FROM settings"
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$settings[$row['field']] = $row['value'];
}
is all you need to grab all of the settings.

This line will not create a variable named after the value for field.
$global_result2["field"] = $global_result2["value"];
You can create an array variable, for example:
$array_of_results[ $global_result2["field"] ] = $global_result2["value"];
This way you will have the following array:
[ 'field' => 'value' ]

Related

Variable naming in foreach

I am using a foreach statement to extract data from a SQL table and am using an array to loop through every single piece of data I need. Previously I just set the variables for the extracted data equal to the array IDs. Now I would like to instead concatenate a string to the array ID names but am not sure how to accomplish this.
Basically I would just like to add "_type" to every single variable name such this it is no longer named $Banana but §Banana_type instead.
I have tried changing the $$val to $$val . '_type'. However this didn't work. I am quite sure I just need to concatenate the '_type' somehow and would appreciate if anyone can help me out.
$variablesArray = array(
"Apple",
"Banana",
);
foreach($variablesArray as $val) {
$query = "SELECT * FROM {$tableName} WHERE ID = '{$CI_NOYEARS}'";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
$$val = $data["COINFO"];
}
}
If you really really need to have variable variables you can concatenate the variable name and store it in another variable like this:
$varName = 'foo'.'1';
$$varName = 1; // $foo1 = 1;
or you can concatenate without the variable in between:
$var = 'v';
echo ${$var.'ar'}; // echoes 'v'
But you can see how ridiculously unclear it gets. This is terrible design choice to use variable variables and it will also confuse your IDE intellisense, static analyzers, and so on. Please don't use variable variables. A better choice would be an array:
$myVars = [];
$myVars['foo'] = 'bar';

Adding inside a while loop php

I have a script that pulls values from a MySQL database and puts into into a variable. Each time it iterates, it pulls a new value. I want to add these values together. Here's what I have:
while ($row = mysql_fetch_array( $result )) {
$getvalue = mysql_query("SELECT value FROM pointvalues WHERE code = '$row[code]'")or die(mysql_error());
$rowcode1 = mysql_fetch_array($getvalue);
$finalValue = $rowcode1["value"];
}
I want to keep adding $finalValue to itself.
I recommend saving yourself all that work and simply changing your query to:
SELECT SUM(value) FROM pointvalues WHERE code = x
Reference: SUM

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.

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.

php & mysql - loop through columns of a single row and passing values into array

I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language

Categories