Settings Keys from a Database as Variables in PHP - 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

Related

Mysql results as PHP named variables

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.

$result only one row then convert into session

i am trying to query one single row from a table 'account'. I kind mess up with the MYSQLI so i need some advice. How can i do that?
$link = mysqli_connect("localhost","root","","database") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM account WHERE username='".$user."' AND password='".$passcode."' LIMIT 1";
$result = $link->query($query) or die("Error " . mysqli_error($link));
$numrow = $result->num_rows;
$res = $result->fetch_assoc();
After the query i want to copy the data to a session, i am doing like that:
session_start();
$tableau = array($res['cod_acc'],$res['username'],$res['password']);
$_SESSION['tableau'] = $tableau;
And after these, how can i print the data?
$tableau = $_SESSION['tableau'];
echo "$tableau['username']";
From your question:
how can i print the data?
First of all you need to add error_reporting() on in your code:
error_reporting(E_ALL);
You are saving values in an array for $_SESSION:
$tableau = array($res['cod_acc'],$res['username'],$res['password']);
$_SESSION['tableau'] = $tableau;
If you look your session array it's not an associative array.
So you can not get the result like:
$tableau = $_SESSION['tableau'];
echo $tableau['username'];
Solution:
You can get username from session array as:
echo $tableau[1]; // username on second index.
Solution 2:
If you want associative index than you need to use associative array as:
$tableau = array(
"cod_acc"=>$res['cod_acc'],
"username"=>$res['username']);
$_SESSION['tableau'] = $tableau;
Now you can use as you need. Note that I am removing password field from session I think its not need.
Side note:
I don't know why are mixing Procedural and Objected Oriented style together.
The problem was in some other line code, sorry for the post. But thanks guys.

PHP/mysql fetch multiple variables in array

I am new to PHP. I wanted to create a new record in another table but just one new variable gets returned. I've tried following:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_name = mysql_query("SELECT user_name FROM accept WHERE user_id=".$user_id." ");
$row1 = mysql_fetch_array($user_name);
$server = mysql_query("SELECT server FROM accept WHERE user_id=".$user_id." ");
$row2 = mysql_fetch_array($server);
$url = mysql_query("SELECT link FROM accept WHERE user_id=".$user_id."");
$row3 = mysql_fetch_array($url);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
And my result is this.
First of all, combine your queries into one:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_info = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row = mysql_fetch_array($user_info);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
In order to create a new record, you will need INSERT INTO, to change existing records use UPDATE.
When you're fetching info from the database, it will be an array so you will need to use it accordingly. So essentially, to use the variables it will be like this:
$row['user_name'] or $row['server'] etc..
Also, look into using mysqli instead. You will need to change your connection script and some other syntax but it needs to be done. mysql is deprecated, insecure, and future support is not there so you will need to change it later anyway.
You should use pdo or mysqli and here is your code;
$user_id = &$_POST["user_id"];
if($user_id){
$result = mysql_query("select user_name,server,link,lpoints from accept where user_id='".mysql_real_escape_string($user_id)."'");
/*You should use single quotes for escaping sql injection*/
if($result){
$vars = mysql_fetch_array($result);
if($vars){
list($username,$server,$link,$lpoints) = $vars;
}
else{
//do something with errors
}
mysql_free_result($result);
}
else{
//do something with errors
}
}
else{
//do something with errors
}
Try This-
$user_id = mysql_real_escape_string($_POST['user_id']);
$result = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row=mysql_fetch_array($result)
$row1=$row['user_name'];
$row2=$row['server'];
$row3=$row['link'];
$lpoints = mysql_real_escape_string($_POST['lpoints']);
Now you got what you wanted based on your requirement use the data to insert or update.

create session with recordset stored in array

How can I take a recordset, store it in an array and then make that array the value of a session? Here is the code I came up with (with answers below integrated):
$colname_getAC = "-1";
if (isset($_GET['tech_id'])) {
$colname_getAC = $_GET['tech_id'];
}
mysql_select_db($database_localhost, $localhost);
$query_getAC = sprintf("SELECT area_code, tech_id FROM zip_zip WHERE tech_id = %s", GetSQLValueString($colname_getAC, "int"));
$getAC = mysql_query($query_getAC, $localhost) or die(mysql_error());
$row_getAC = mysql_fetch_assoc($getAC);
$totalRows_getAC = mysql_num_rows($getAC);
session_start();
// store session data
$_SESSION['area_code']= array();
while ($row_getAC = mysql_fetch_assoc($getAC)) {
$_SESSION['area_code'][] = $row_getAC['area_code'];
}
This just returns "array" though and not the area codes when I call the session.
On the session, I tried this also:
$_SESSION['area_code']= $results[];
But that just made the page stop dead in its tracks with a blank screen.
The reason for this is that I want to insert the values in this session on a different page.
You have it stored as an array, you can see it here:
var_dump($_SESSION['area_code']);
I really dont understand, what exactly you want.
Also this is wrong $_SESSION['area_code']= $results[];
EDITED:
Change your code to:
$colname_getAC = "-1";
if (isset($_GET['tech_id'])) {
$colname_getAC = $_GET['tech_id'];
}
mysql_select_db($database_localhost, $localhost);
$query_getAC = sprintf("SELECT area_code, tech_id FROM zip_zip WHERE tech_id = %s", GetSQLValueString($colname_getAC, "int"));
$getAC = mysql_query($query_getAC, $localhost) or die(mysql_error());
$totalRows_getAC = mysql_num_rows($getAC);
session_start();
// store session data
$_SESSION['area_code']= array();
while ($row_getAC = mysql_fetch_assoc($getAC)) {
$_SESSION['area_code'][] = $row_getAC['area_code'];
}
First - you must change your logic:
From this:
$results = array();
do {
$results[] = $row_getAC['area_code'];
} while ($row_getAC = mysql_fetch_assoc($getAC));
$_SESSION['area_code']= $results;
to this:
$results = array();
while ($row_getAC = mysql_fetch_assoc($getAC))
{
$results[] = $row_getAC['area_code'];
}
$_SESSION['area_code']= $results;
I've just tested - PHP has no trouble storing arrays as session variables and they are available on other pages.
BTW - you used session_start() right?
Update:
do{...}while always executes at least once as checks condition at the end
while{...} exactly the opposite (checks condition before executing code inside code block
You must use the latter here since (for example) your SQL query may return empty result (no records) so you should not execute code within while block since there is no data to get.

Formatting array output using foreach function

I have a script that follows that is supposed to collect data from a field"UserID" in my sql table, submit all data into an array, and then compare a variable to whats in the array. If the value of the variable is already in the array, tell the user that that value is invalid.
$sql = "SELECT *" //User info
. " FROM Users" ;
$result = mysql_query($sql);
//insert where line for assessorid
$users = array();
while(($user = mysql_fetch_assoc($result))) {
$users[] = $user;
}
foreach($users as $user){
$user['UserID'];
}
I need the output of $users to be equivalent to array('user1','user2','user3');
Whats happening is data comes in from a form as $user_name. I want to use this in a statement like follows:
if(in_array($user_name,$users)){
echo "username available"
}
else{
echo "not available"}
I tried using the extract function, but that just created a big mess.
Im not sure what is incorrect about what I'm doing, unless the format of $users as an array cannot be parsed in the in_array() function as it is formatted currently. Any advice is much appreciated. Thanks!
$sql = "SELECT USERID FROM Users" ;
$result = mysql_query($sql);
$users = array();
while(($user = mysql_fetch_assoc($result))) {
$users[] = $user['USERID'];
}
When you are saying
$users[] = $user;
You are not specifying which column in the result set to be appended to the array.
Maybe I am missing something... Why not do it like this:
SELECT UserID FROM Users WHERE Username = 'username'
Then just use mysql_num_rows() to check if the username already exists or not. This should be both faster and more efficient (memory-wise).
In that case, you collect all data from the database and need to do some inefficient processing in PHP as well. It is better to query for that value to see if it is in the database, so:
$username = mysql_real_escape_string($username);
$query = "
select
count('x') as usercount
from
users u
where
u.username = '$username'";
The, if the 'usercount' is 0, the username does not exist. If > 0, the username does exist. This way, you let the database do the work it is designed to do, and the only value that is actually retreived is that single number.
Have you tried modifying your query? Currently you are getting all of the values for every user, but you just seen to need UserID. You could do this:
$sql = "SELECT UserID FROM Users";
$result = mysql_query($sql);
$users = array();
while(($user = mysql_fetch_assoc($result)))
{
$users[] = $user['UserID'];
}
// ...
if (in_array($user_name, $users))
{
echo 'Username not available';
}
else
{
echo 'Username available';
}
Or you could just look up in the database for the given username:
$sql = 'SELECT count(*) FROM Users WHERE UserID = '.mysql_escape_string($user_name);
$result = mysql_query($sql);
// and then just check if the resulting row is equal to 0
Are you attempting to write a script that will check if a username is taken?
If so, it may be easier (and more efficient) to structure the actual query towards this end rather than relying on the programmatic approach.
$sql = "SELECT COUNT(*) FROM Users WHERE Username = '$username'";
Then you could apply this result to a count and allow the user to register or not based on whether a value greater than zero (a user has already taken that name) or not (its free) is returned.
As has been mentioned, that is a rather inefficient way to check for an existing username. The suggestions for modifying your query are good advice.
However, to address the problem with the code you provided:
in_array() will not detect the presence of a value in a multi-dimensional array. Your $users array probably looks something like this:
$users = array(
array('userID', 'foo', 'bar'),
array('userID', 'foo', 'bar'),
array('userID', 'foo', 'bar')
)
and in_array will not search below the first set of indexes. If this is really what you want to do, see this question: in_array() and multidimensional array

Categories