How to create dynamic variables from SQL results - php

This one should be easy and it's killing me I can't find the solution!
I have a SQL query return records from a database. The two fields I am using are $row["staff_id"] and $row["name"].
From that I want to build a dynamic variable which is something like:
$staffid_1 = "Mark Smith";
$staffid_2 = "Sally Baker";
$staffid_3 = "Peter Pan";
The varibale name is created dynamically be combining "staffid_" and $row["staff_id"] for the first part then $row["name"] for the name.
I've tried:
${$staff_id . $row["staff_id"]} = $row["name"];
echo ${$staff_id . $row["staff_id"]} . "<br>";
But no luck! Any assistance would be appreciated :)

I would think you might be best to change your query to return the first part of it, then whatever you're calling it from to concatenate it together, eg
Query:
SELECT '$staffid_' + ltrim(rtrim(cast(staff_id as varchar))) + ' = "' + name + '"'
FROM [table list]
ORDER BY ...
Then concatenate the individual rows of result set as required, with in-between as you seem to require.

Okay so in PHP you have an awesome option to use a double leveled variable which basically means this :
$$varname = $value;
This results in the fact that if you have a string variable ,
(for example $staffid = "staffid_1") that you can do the following:
$staffid = "Jasonbourne";
$$staffid = "Matt Damon";
// Will result in
$JasonBourne = "Matt Damon";
So for your example:
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
Will result in the variable : $staff_id_1 = "Mark Smith";
To read more about double - leveled variables :
http://php.net/manual/en/language.variables.variable.php
EDIT: If you wanna loop through the rows :
foreach ($sql_result as $row) {
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
}

Related

How to export array from php file to another php file

In one file i have something like this:
$result = mysqli_query($con, "SELECT * FROM users WHERE id_province = '".$province_id."' AND id_city = '".$city_id."' AND age >= '".$age1."' AND
age <= '".$age2."' AND id_rank = '".$rank_id."' AND id_position = '".$position_id."';");
while ($row = mysql_fetch_array($result)) {
$array[] = $row;
}
And I want to use $array in another php file. How can I do it?
You can use SESSIONS
session_start();
$result = mysqli_query($con, "SELECT * FROM users WHERE id_province = '" . $province_id . "' AND id_city = '" . $city_id . "' AND age >= '" . $age1 . "' AND
age <= '" . $age2 . "' AND id_rank = '" . $rank_id . "' AND id_position = '" . $position_id . "';");
while ($row = mysql_fetch_array($result)) {
$array[] = $row;
}
$_SESSION['array'] = $array;
and in second file you can use code below
#session_start();
$array = $_SESSION['array'];
When trying to pass between multiple files, you could use classes instead of scripts. This helps maintain the code better.
Let's say the second file was SecondFile.class. I could instantiate it and then pass the array as a parameter.
$secondFile = new SecondFile;
$secondFile->someClassMethod($array);
Or, if you don't need to use the second file for anything else, use a shorter syntax:
(new SecondFile)->someClassMethod($array);
So... "export" is the wrong term for this, what you are looking at is variable scope
In the simplest terms - something declared outside a function is "global" and something declared within a function is private to that
You want to pass an array from one file to another? If you have 3 files (main, include_num1 and include_num2), this is simple;
Main;
<?php
require_once 'include_num1.php';
require_once 'include_num2.php';
?>
include_num1;
<?php
$myarray = array("a", "b", "c")
?>
include_num2;
<?php
var_dump($myarray);
?>
This will produce something like;
myarray = (array)
string 0 : a(1)
string 1 : b(1)
string 2 : c(1)
This is because in this example, the array is declared in the global scope, if you did the require's the other way around - this would error as at time of the var dump, $myarray does not exist
You can skip out the "main" by just including the include_num2 from the include_num1
If you want to use a global variable inside a function, declare the function as normal, and use the global available;
<?php
$myvar = "A variable";
function myFunction()
{
if (isset($myvar)) print $myvar; // Will do nothing
global $myvar;
if (isset($myvar)) print $myvar; // Will Print "A variable"
}
?>
You can save your array in the database, file, cookie, session....
It depends of what you want to do versus the necessary security level.
The simplest way would be:
//At the top of your page
#session_start();
//This line goes after you get all data you want inside your array
$_SESSION['mySession'] = $array;
And in the other page:
//At the top of your page
#session_start();
//To recover you array:
$array = $_SESSION['mySession'];
Not the best option, but it works.

How to insert two variable value into single field in php?

code:
<?php
if(isset($_POST['add_new']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$field = $_POST['field'];
$message = $_POST['message'];
$comment1 =array($_POST['comment1'],$s_date);
$comment2 = $_POST['comment2'];
$status = $_POST['status'];
$s_date = date('Y-m-d');
$interested_in = $_POST['interested_in'];
$academic_details = $_POST['academic_details'];
$city = $_POST['city'];
$sql = "insert into enquires2(name,email,phone,field,message,comment1,comment2,status,s_date,interested_in,academic_details,city,admin_idd)values('$name','$email','$phone','$field','$message','$comment1','$comment2','$status','$s_date','$interested_in','$academic_details','$city','$admin_id')";
$result = mysqli_query($link,$sql);
if($result == true)
{
$msg .= "<p style='color:green;'>You are successfully add new enquiry</p>";
}
else
{
$msg .= "<p style='color:red;'>Error!</p>";
}
}
?>
In this code I want to pass two value in single variable i.e.
$comment1 = array($_POST['comment1'],$s_date);
which show (array) when I print query ($sql). How can I pass two value into single variable ? please help me.
Another option if you don't want to concatenate , use serialize function make an associative array and serialize it and store to db
for example :
$comment1 =serialize(array("comment"=>$_POST['comment1'],"date"=>$s_date));
and when you get form db ,just use
$data = unserialize($yourDataFromDb);
and you get your values like
$data["comment"] // Your comment
$data["date"] // your date
Simply use concatenation
$comment1 = $_POST['comment1'] . $s_date;
But if you want to parse later and keep sepration between comment and date you can use any format like
$comment1 = $_POST['comment1'] . "--date--" . $s_date;
Later you can simply use print_r (explode("--date--",$str));
Something like multivalue field.
You already record the value of $s_date in a separate "date" field, so there's no need to record it again within the comment field.
If you want to combine them for display or reporting purposes later on, then you can easily do that in the object or UI layer using simple string concatenation. I would advise you not to do this when storing the data as you're attempting - otherwise you're just duplicating the same value twice in the row for no obvious reason, as well as making it more difficult to separate what the user actually wrote from the date you inserted into it.

Appending loop number to SQL row variable

"Undefined variable: payout_item_1" so it's getting the variable name correctly but I must have the format wrong.
for ($x = 1; $x <= 5; $x++) {
echo "<input name = 'payout_item_" . $x . "' type = 'text' value = '" . $row[${"payout_item_" . $x}] . "' style = 'width : 150px;' ";
}
I'm making a couple assumptions
You have a table with columns "payout_item_1" through "payout_item_5"
You do not have variables called $payout_item_1 through $payout_item_5 in which the actual column names are stored.
Currently your code is building variable variables:
This statement builds a variable name with payout_item_1 (in the first iteration). Effectively $payout_item_1.
${"payout_item_" . $x}
The code is then looking for a value in that variable to use as the column header name. Effectively, it's expecting somewhere further up for there to be something akin to
$payout_item_1 = "column1";
Which, as the error suggests, it cannot find. If my assumption in 1. was correct, all you need to do is reformat to
$row["payout_item_" . $x]
and you will be referencing the column payout_item_1 (through 5) from your $row object. Written literally:
$row["payout_item_1"]

HTML id's to one single php variable?

Please help...
I would like to know how you display multiple html id's (e.g. firstname & surname) in one .php variable (e.g $firstname )...
Here's my code:
$customerFirstname = $_POST['firstname'];
$customerSurname = $_POST['surname'];
$customerFullname = ''; // first & surname id's of customer retrieved from enquiryForm
Thanks in advance...
Thanks All for your comment... really appreciated
Try with concatination of two strings like
$customerFirstname = $_POST['firstname'];
$customerSurname = $_POST['surname'];
$customerFullname = $customerFirstname .' '. $customerSurname;
Not sure whether you mean an array or a string, so I'll provide an example of both.
Array:
$customerFullName = array($customerFirstName, $customerLastName);
Concatenation:
$customerFullName = $customerFirstName . ' ' . $customerLastName;
Just concatenate the variables in other. Like it:
$customerFirstname = $_POST['firstname'];
$customerSurname = $_POST['surname'];
$customerFullname = $customerFirstname.' '.$customerSurname;
The quick and easy solution , Use an array . A better approach , use an object . In the second case you can group all user related functions , properties together , so my vote goes for objects .

session variable inside another variable - how?

I have a script that displays countries in different languages. For example "United Kingdom" in Spanish would be "Reino Unido", etc. Every language is stored in a different table, like "name_es" for Spanish or "name_en" for English. The correct table is then selected through a session value stored for each user. What I have is this:
if ($countries_id)
{
$sql_select_countries = $this->query_silent("SELECT name_".$_SESSION['language']." as name FROM " . DB_PREFIX . "countries WHERE
id IN (" . $countries_id . ")");
if ($sql_select_countries)
{
while ($country_details = $this->fetch_array($sql_select_countries))
{
$countries_array[] = $country_details['name'];
}
}
}
Note that the problem line is this:
$countries_array[] = $country_details['name'];
I need it to be something like
$countries_array[] = $country_details['name_$_SESSION['language']'];
But I can't figure out the correct syntax :(
So you want to concatenate the string 'name_' with the vale stored in session?
$countries_array[] = $country_details['name_'.$_SESSION['language']];
I think if you add some speech marks and curly brackets you can do this:
$countries_array[] = $country_details["name_{$_SESSION['language']}"];
$countries_array[] = $country_details[$_SESSION["language"]];

Categories