How to export array from php file to another php file - php

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.

Related

Arrays that are in variables and displaying them By class/for loop

This is my code: Right now as you can see you are only looking the last index. the show_results for example. First of all, the $titleNamesArr it's a simple variable that contains scraped information. Also the $imageArr , $pathAarr etc.. all the way to the $details. These variables contains each one of them exactly 20 scraped data information... so what i need is someone to guide me how can i display all the variables correctly.
<?php
session_start();
require_once 'Main.php';
require_once 'crawling.php';
$titleNamesArr = $_SESSION['titleNames'];
$imageArr = $_SESSION['imageArr'];
$pathArr = $_SESSION['pathArr'];
$subtitle = $_SESSION['subtitle'];
$description = $_SESSION['descriptionCat'];
$details = $_SESSION['details'];
Ofcourse i can do it like that: But i am reapeating myself a lot, Imagine having 100 data.
$card0 =new Main($titleNamesArr[0],$imageArr[0],$pathArr[0],$subtitle[0],$description[0],$details[0]);
echo $card0->showingCards()."<br>"."<br>";
$card1 = new Main($titleNamesArr[1],$imageArr[1],$pathArr[1],$subtitle[1],$description[1],$details[1]);
echo $card1->showingCards()."<br>"."<br>";
$card2 = new Main($titleNamesArr[2],$imageArr[2],$pathArr[2],$subtitle[2],$description[2],$details[2]);
echo $card2->showingCards()."<br>"."<br>";
This is what i have tried so far. It is returning me 11 from the 20 results, of course somewhere i am wrong.
///// Showing the cards
for($i=0; $i<=count($titleNamesArr); $i++) {
$card = new Main($titleNamesArr[$i], $imageArr[$i], $pathArr[$i], $subtitle[$i], $description[$i], $details[$i]);
echo $card->showingCards() . "<br>" . "<br>";
$i++;
}
Anyone's advise ?
If you remove the unnecessary $i++; the loop will work correctly. The loop counter is already in the for statement.
You could also fix the unnecessary literal concatenation and make "<br>" . "<br>"; into "<br><br>";
Like so:
for($i=0; $i<=count($titleNamesArr); $i++) {
$card = new Main($titleNamesArr[$i], $imageArr[$i], $pathArr[$i], $subtitle[$i], $description[$i], $details[$i]);
echo $card->showingCards() . "<br><br>";
//$i++;
}

How to create array data from database?

How to create an array data from database?
I want to show random data by using array_rand.
If we create by manual is like this.
$a = ['http://php.net/', 'http://google.com/', 'http://bbc.co.uk/'];
Then call it:
echo $a[array_rand($a)];
I try to creat same like that, but fail. Here's what I try:
Data from database:
$query2 = $db->prepare ("SELECT idc FROM content ORDER BY RAND() LIMIT 5");
$query2->execute();
while ($value2 = $query2->fetch()) {
$data_idc[] = $value2['idc'];
}
Then I try to create a same code like code above:
$bank_idc_1 = [ $string_result = "'". implode("', '", $data_idc) . "'" ];
Then I call it:
echo $bank_idc_1[array_rand($bank_idc_1)];
But I get error.
There is no need of this line
$bank_idc_1 = [ $string_result = "'". implode("', '", $data_idc) . "'" ];
Directly go for:-
echo $data_idc[array_rand($data_idc)];
Description:- Through while() loop you are already getting an array so you need to apply array_rand() directly on it.

How to create dynamic variables from SQL results

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"];
}

Php variable increment

So i have the following code that works and outputs the information let's say 2 11. I would like to have $keyidcall increment in variable name so $keyidcall2, $keyidcall3....... with the additional variables I would like the variable to hold the correct value so I can call it later. so expected output would be $Apiammount ="2";
echo $keyidcall; would echo 2
echo $keyidcall: would echo 11
while($Apiammount > 1){
$Keyidquery = mysqli_query($connection, "SELECT ID FROM `Characterapi` WHERE UserId = '$Idcall'");
while($keyid = mysqli_fetch_assoc($Keyidquery)){
$keyidcall = $keyid['ID'];
echo $keyidcall;
}
$Apiammount--;
}
The better way to do this would be to store the values in an array.
$keyidcall[] = $keyid['ID'];
Then you can refer to them later as
echo $keyidcall[0];
echo $keyidcall[1];
in the order that they were entered in.
Or if you wanted something more specific to refer to it by, you could use
$keyidcall[$Apiammount] = $keyid['ID'];
then you would refer to them as:
echo $keyidcall[<apiamount>];
Assuming you know what that would be.
You can do:
$i = 0;
while($foo){
$name = 'keyidcall';
$i++;
$newvar = $name . $i;
echo $$newvar;
}
And $$newvar will echo the value of "keyidcallX" where X is an incrementing value. Not sure if that's what you meant.

How to identify list of variables_x from url in PHP, using one parameter?

I have a members site where users are given up to 7 web page templates to display their products on. Each template has the same field names, differentiated by _1, _2... _7 at the end of each.
For example:
// Template 1 would have the following list of variables
product_name_1
product_descript_1
product_color_1
product_price_1
// Template 2 would have the following list of variables
product_name_2
product_descript_2
product_color_2
product_price_2
// through Template 7
I am able to display any variables for a specific user within a web page, by use of a query string identifying their user_id in the url, ie
http://domain.com/folder/page.php?id=78
I then $_Get any variable by simply identifying it in the PHP file, ie
$product_name_1
$product_descript_1
$product_color_1
$product_price_1
My problem is that the url must identify WHICH template, since each template identifies a specific product, ie _1, _2, ..._7. How do I use a parameter in the url, such as
http://domain.com/folder/page.php?id=78&parameter=_7
...to identify all variables ending with _7, which would appear in the web page? The parameter used in the url would identify the variables to be used in the web page, whether _1, _2, etc.
UPDATE
I have tried the various answers with only partial success, ie "Array_x" is displayed when using any particular variable along with the suggested code. There may be a conflict with the rest of the code I'm using in page.php, as follows:
$db_connection = new mysqli("", "", "");
if ($db_connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
$prop_address=array(
"_1"=>"prop_address_1",
"_2"=>"prop_address_2",
"_3"=>"prop_address_3"
//Through to Temp 7
);
$prop_address{$_GET['parameter']}=$row->prop_address;
echo " $prop_address{$_GET['parameter']} ";
"Array_x" displays (where x=1, 2, 3, etc is used as the parameter in url, ie http://domain.com/page.php?id=72&parameter=1), instead of the actual value held in the database table for $product_name{$_GET['parameter']}. For some reason, the code is not picking up the value of the variable from the database table.
Would it be possible to use arrays so...
$product_name=array(
"1"=>"Product name for template 1",
"2"=>"Product name for template 2"
//Through to Temp 7
);
echo $product_name[$_GET["parameter"]];
You could then do the same for the other variables.
You could fill each array by doing something like:
$row = mysql_fetch_object($query);
$product_name[$_GET['parameter']]=$row->product_name;
echo $product_name[$_GET['parameter']];
I may be missing something...
$_GET['parameter'] = '_2';
$product_name{$_GET['parameter']} = 'string';
echo $product_name_2; // string
or
$_GET['parameter'] = '_2';
$var = 'product_name'.$_GET['parameter'];
$$var = 'string';
echo $product_name_2; // string
Personally, I would use array's for this type of behavior.
Update:
Although the above works and tested ok, it is a lot more work than anyone would probably desired.
In lieu of simplicity, I would suggest the approach via array's.
$templates = array(2 => array(
'product_name' => "value",
'product_descript' => "value",
'product_color' => "value",
'product_price' => "value",
);
foreach($templates[substr($_GET['parameter'],1)] as $var => $val){
$variable = $var.$_GET['parameter'];
$$variable = $val;
}
The above is backwards compatible, it uses substr to remove the leading _ from your parameter.
I couldn't get any of the answers given to work. I found an example given by a user for php variable variables in the PHP manual here and found it to work. I incorporated it into my code as follows:
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
for( $i = 1; $i < 8; $i++ )
{
$product_name[$_GET['parameter']] = "product_name_" . $i;
$product_descript[$_GET['parameter']] = "product_descript_" . $i;
$product_color[$_GET['parameter']] = "product_color_" . $i;
$product_price[$_GET['parameter']] = "product_price_" . $i;
}
${$product_name[1]} = "$row->product_name_1";
${$product_name[2]} = "$row->product_name_2";
${$product_name[3]} = "$row->product_name_3";
${$product_name[4]} = "$row->product_name_4";
${$product_name[5]} = "$row->product_name_5";
${$product_name[6]} = "$row->product_name_6";
${$product_name[7]} = "$row->product_name_7";
// List 7 variables and values for each field name
echo "${$prop_name[$_GET['par']]}";
The only problem is that mysql injection is possible with this code. If anyone could suggest a solution, I would greatly appreciate it.

Categories