Mysql results as PHP named variables - php

I have a table in mysql called site_settings that looks like this
Table in PHPMyAdmin
I am trying to store all of my website settings in mysql and want to pull them into PHP as variables.
I want to pull all values from the variable_name column as the $variable names in PHP and have their values set to whats in the variable_type column.
$site_name = Vexed
$registration_enabled = False
here is my code:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$$row['variable_name'] = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
the last two lines i am using to see if the variable have been created but i cant get it to work. the best result i have got so far is
[Array] => Array
(
[variable_name] => Vexed
)
Can anyone tell me where i am going wrong?
Thanks in advance to anyone who can help.

What you're trying to duplicate is PHP's extract() builtin function.
It's generally considered a bad practice, because it will make your code harder for readers to understand or debug.
What is so wrong with extract()?
How to demonstrate an exploit of extract($_POST)?
https://dzone.com/articles/php-bad-practice-use-extract
https://blog.josephscott.org/2009/02/05/i-dont-like-phps-extract-function/

What I think is happening is that when you call $$arr['variable_name'] it's actually doing $$arr first (which evaluates to $Array after the string conversion), and then trying to assign into assign the ['variable_name'] key into $Array.
I would expect this minor modification to work:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$name = $row['variable_name'];
$$name = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
Edit: I'll also echo, that it's a little bit weird to dynamically create variables in this way and it will make your code hard to follow.

Related

Settings Keys from a Database as Variables in PHP

My apologies as I am sure the answer is obvious. But I am new to PHP... a transplant from ColdFusion. I have a MySQL table called settings the holds key pair values that I want to set as site-wide variables in php. For instance: page_title => 'Untitled Page', site_title => 'Sirius FireWeb'.
Here is my function that grabs the data from the database:
function get_sitesettings(){
global $db;
$sql = "SELECT * FROM settings WHERE autoload = 'yes'";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;}
Here is where I call the function and thought I could loop through the query results and set the variables, but I really have no idea how to do it in PHP.
$get_settings_result = get_sitesettings();
while($settings = mysqli_fetch_assoc($get_settings_result)) {
// SET THE VARIBLES HERE USING THE QUERY OUTPUT?
}
$page_css = array();
$no_main_header = false;
$page_body_prop = array('class' => 'smart-style-1 fixed-header');
$page_html_prop = array();
Can someone please provide guidance on how to set keys as variable names in PHP?
${$settings["key"]} = $settings["value"];
But I don't think it's a good idea.
Can you try the extract() on the results?
http://php.net/manual/en/function.extract.php

How to send an array with pdo to use it in html_options of smarty 3.1.21

I'm updating a section that uses MySQL to PDO to show an {html_options} of Smarty. This code works well actually with MySQL, but I don't know how to get same results using PDO.
This is the code that works well actually:
// Send states
$q="SELECT id, state FROM states";
$data=$db->execute($q);
$idStates=array();
$states =array();
for ($i=0; $i<sizeof($data);$i++) {
array_push($idStates,$data[$i]->id);
array_push($states,$data[$i]->state);
}
$smarty->assign('idStates',$idStates);
$smarty->assign('states',$states);
Then all works well in the .tpl file
<select name="des_idState" class="form-control">
<option>Select state</option>
{html_options output="$states" values="$idStates" selected=$data.idState}
</select>
What I am trying to do with PDO works well using {foreach}, but I need to use the selected, and I think is easiest doing with {html_options} of Smarty, but I don't know how to send the array from PDO.
$sql1="SELECT id, state FROM states";
$stmt = $dba->prepare($sql1);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$idStates = $row['id'];
$states = $row['state'];
$smarty->assign('idStates', $idStates);
$smarty->assign('states',$states);
}
I have been trying with this code that shows me the array using echo $idStates . ' ' . $states . '<br>';, however it doesn't work in the {html_options}, nothing shown, no error, just a blank space.
Could somebody help me?
I know it has been a while since this question was posted, but did you ever find a solution to your problem? I believe you could fix the id and state variables to be arrays with minimal code modifications.
In the example below, I have added id and state array declarations at the beginning to ensure that the arrays are empty (as a precaution for the next step). I then changed $idStates= to $idStates[]= and $states= to $states[]=, which will add the current value to those arrays on each loop. Last, I moved the smarty variable assignments to be after the while loop so that the arrays will be fully populated. Here is the modified code:
$sql1="SELECT id, state FROM states";
$stmt = $dba->prepare($sql1);
$stmt->execute();
$idStates = array();
$states = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$idStates[] = $row['id'];
$states[] = $row['state'];
}
$smarty->assign('idStates', $idStates);
$smarty->assign('states',$states);
I have also included an alternative solution below that should return the same data. In this example, I use $stmt->fetchAll instead of $stmt->fetch to get all rows at once and then store them in an associative array. I then use array_column when declaring the smarty assignments, which separates out the id and state columns from the $rows associative array. This results in a bit less code without sacrificing readability:
$sql1 = "SELECT id, state FROM states";
$stmt = $dba->prepare($sql1);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign('idStates', array_column($rows, 'id'));
$smarty->assign('states', array_column($rows, 'states'));

Put mysql results in one php array, like this?

To get an array like this array("123","456","789"); I use the code:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
$regIDs = implode(',', $result_array);
$registrationIDs = array($regIDs); // array("123","456","789");
but I would expect PHP/mySQL has a simpler/faster solution for this?
I doubt that your code produces the result you want.
// assuming the this query produces 123,456,789
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
// $row contains: array("123")
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
// $result_array now contains: array("\"123\"", "\"456\"", "\"798\"");
$regIDs = implode(',', $result_array);
// $regIDS now contains a single string: "\"123\",\"456\",\"798\"";
$registrationIDs = array($regIDs);
// registrationIDs now is an array containing a single string: array("\"123\",\"456\",\"798\"");
If you really need an array that looks like this: array("123","456","789"); it is much simpler.
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = $row['regid'];
and that's all.
If your mysql result contains the number as an integer instead of an string you can convert it like this:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = strval($row['regid']);
Also, keep in mind that the mysql_* functions are becoming deprecated. Don't start new code with it and make plans to port your existing code to mysqli_* or PDO.
You can use PDO implementation. At first sight, it may be more difficult to understand, but once you get used to it, it reveals to be really powerful and handy (IMHO! One year ago i switched to it and i love it)!
For your example, the PDO implementation would be like this:
/*CONNECT TO DB, FIRST. $dbh contains a handler to the current DB connection*/
$stmt = $dbh->prepare("SELECT regid FROM table WHERE active = '1'");
$stmt->execute();
$Regids = $stmt->fetchAll(PDO::FETCH_COLUMN,0);
There are many formatting options you can specify, like
PDO::FETCH_COLUMN
PDO::FETCH_ASSOC
and more...These options will allow you to get the array formatted as you prefer. As you can see i got the result in just 3 simple rows.
EDIT
Note: you are not escaping PHP variables before inserting them in your Query, and your code may suffer SQL INJECTION. Be careful!! Here is a simple guide to prevent it.
(In my code, just to be clear, i avoided the problem by just putting the table name instead of $table, just to show simply how to get the result you wanted.)
try this .. use Group concat in query ...
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT(regid) as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // 123,456,789
for getting result "123","456","789" try this
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT('\"',CONCAT(regid),'\"') as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // "123","456","789"

convert mysql query in to an array format

can any one know the, convert mysql query in to an php array:
this is mysql query :
SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC
I want to convert this query in to simple php array .
So, you need to get data out of MySQL. The best way, hands down, to fetch data from MySQL using PHP is PDO, a cross-database access interface.
So, first let's connect.
// Let's make sure that any errors cause an Exception.
// <http://www.php.net/manual/en/pdo.error-handling.php>
PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// We need some credentials...
$user = 'username';
$pass = 'password';
$host = 'hostname';
$dbname = 'database';
// PDO wants a "data source name," made up of those credentials.
// <http://www.php.net/manual/en/ref.pdo-mysql.connection.php>
$dsn = "mysql:host={$host};dbname={$dbname}";
$pdo = new PDO($dsn, $user, $pass);
There, we've connected. Let's pretend that $sql has the SQL you provided in your question. Let's run the SQL:
$statement = $pdo->prepare($sql);
$statement->execute();
There, it's been executed. Let's talk about results. You steadfastly refuse to tell us how you want your data structured, so let's go through four ways that you could get your data.
Let's first assume that the query returns a single row. If you want a numerically indexed array, you would do this:
// <http://www.php.net/manual/en/pdostatement.fetch.php>
$array = $statement->fetch(PDO::FETCH_NUM);
unset($statement);
If you want an associative array with the column names as the keys, you would do this:
$array = $statement->fetch(PDO::FETCH_ASSOC);
unset($statement);
Now, what if the query returns more than one record? If we want each row in a numerically indexed array, with each row as an associative array, we would do this:
// <http://www.php.net/manual/en/pdostatement.fetchall.php>
$array = $statement->fetchAll(PDO::FETCH_ASSOC);
unset($statement);
What if we want each row as a numerically indexed array instead? Can you guess?
$array = $statement->fetchAll(PDO::FETCH_NUM);
unset($statement);
Tada. You now know how to query MySQL using the modern PDO interface and get your results as no less than four types of array. There's a tremendous number of other cool things that you can do in PDO with very minimal effort. Just follow the links to the manual pages, which I have quite intentionally not linked for you.
This over-the-top post has been brought to you by the letters T, F and W, and the number PHP_MAX_INT + 1.
i don't get you clearly, but
mysql_fetch_array and mysql_fetch_assoc
both returns only array
please refer:-
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-fetch-assoc.php
If you just need a simple array...
while ($row = mysql_fetch_array($query)) { //you can assume rest of the code, right?
$result[$row['url_id']] = array($row['sumtime']);
}
For a simple array
$sql = mysql_query("SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC");
while($row = mysql_fetch_array($sql)){
$array1 = $row['sumtime'];
$array2 = $row['title'];
$array3 = $row['url'];
}
Hope this is one you wanted
Dude the fastest way is probably the following
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
print_r($data);

PHP DELETE immediately after select

I have a PHP server script that SELECTs some data from a MySQL database.
As soon as I have the result from mysql_query and mysql_fetch_assoc stored in my own local variables, I want to delete the row I just selected.
The problem with this approach is that it seems that PHP has done pass-by-reference to my local variables instead of pass-by-value, and my local variables become undefined after the delete command.
Is there anyway to get around this? Here is my code:
$query="SELECT id, peerID, name FROM names WHERE peer = $userID AND docID = '$docID' AND seqNo = $nid";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:1 getUsersNamesUpdate() query: ".$query."\n");
if (mysql_num_rows($result) == 0)
return array();
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:2 getUsersNamesUpdate() query: ".$query."\n");
return $result;
You are overwriting your $result variable with your second statement:
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query); // result does not contain the array anymore
Change the name to something else. It has nothing to do with call-by-reference or such.
Actually, your first assignment of the values is unnecessary as $row is already an array:
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
You could just do:
$row = mysql_fetch_assoc($result);
// at the end
return $row;
Then you don't even have to change your variable name for the second statement. But consider to use meaningful variable names.
First of all, why not just use only one query to delete the row that interests you ?
Something like this should do the trick, I suppose :
delete
from names
where peer = $userID
AND docID = '$docID'
AND seqNo = $nid
Of course, don't forget to escape/convert the values that should be ;-)
This way, no need for a select query, followed by a delete one.
Second : to make your code more easier to read / understand / maintain, you should probably not re-use the same variable for several different purposes.
Here, your $result variable is used for more than one thing, and it makes things harder to understand :
resource returned by the first mysql_query
then, array containing data from the first row
then, resource returned by the second mysql_query
It's a bit confusing, and will, one day or another, lead to errors...
Actually, it already has ;-) : the third assignment is overriding the data you're getting with the second ones, and boom, you've lost the information that corresponds to the row you've just deleted ;-)

Categories