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.
Related
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.
i am confused about how to extract values from a query, and place them into specific variable, when i don't know before hand what the name of the value will be.
it might be easier to show you what i mean.
the images below are the returned values, grouped by heading i.e Total_responded, Percent_responded etc.
so the first row will have under the column Responce the value Poached with a Percent_responded of 16.66667.
however the next row will have under column Responce $scrambled with a Percent_responded of 83.333333
i now want to place each of these values into individual variables like:
$poached , $poachedPercentage, $scrambled, $scrambledPercentage etc
i attempted to do it below, but produced the wrong figures. this is also not a cost effective way to do it. so, i would really appricaite some advice on how to extract the values
$getPollResult = results();
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce = safe_output(round($row['RESPONCE']));
$percentage = safe_output(round($row['Percent_responded']));
if($responce = 'Poached')
{
$percentageOne = $percentage;
$poached = $responce;
}
if ($responce = 'Scrambled')
{
$percentageTwo = $percentage;
$scrambled = $responce;
}
// echo " $percentagePoached $percentageScrambled ";die();
}
Use
$responce = trim($row['RESPONCE']);
Instead Of
$responce = safe_output(round($row['RESPONCE']));
Also, Change in if condition = to ==.
you can use "variable variables" (PHP Docs) to achieve that:
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce_name = trim($row['RESPONCE']);
$percentage_name = $responce_name . "Percentage";
$percentage = safe_output(round($row['Percent_responded'])); //don't know what safe_output() does
$$percentage_name = $percentage; //notice the double "$" here
}
your PHP variables will then look like this:
$PoachedPercentage = 17;
$ScrambledPercentage = 83;
// and so on....
I'm trying to pass a value for a query that takes in a variable from an earlier Sql query and then compares the result against a field from another table. But I can't seem to figure out my syntax.
$topName = $row_rsAdminDetails['fullName'] ;
$TESTqueryTwo =
"SELECT * FROM participants, admin WHERE admin.over_id = participants.fk_over_id AND participants.dr_over_names LIKE '%$topName%'";
$TESTresult2 = mysql_query($TESTqueryTwo) or die(mysql_error());
the php output I'm looking to do:
<?php
// Print out the contents of each row
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
echo $row_TESTresultTwo['userName']. " - ". $row_TESTresultTwo['Participant_Name'];
echo "<br />";
}
?>
Problem could be on this line:
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
should be
while($row_TESTresultTwo = mysql_fetch_array($TESTresult2)){
// as you have no $TESTresultTwo variable...
}
And also try with the query ... with LIKE '%".$topName."%'"
I previously designed the website I'm working on so that I'd just query the database for the information I needed per-page, but after implementing a feature that required every cell from every table on every page (oh boy), I realized for optimization purposes I should combine it into a single large database query and throw each table into an array, thus cutting down on SQL calls.
The problem comes in where I want this array to include skipped IDs (primary key) in the database. I'll try and avoid having missing rows/IDs of course, but I won't be managing this data and I want the system to be smart enough to account for any problems like this.
My method starts off simple enough:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Two notes:
Yes, I should probably move that $localityMax check to a PHP loop.
I'm intentionally skipping the first array key.
The problem here is that any missed key in the database isn't accounted for, so it ends up outputting like this (sample table):
1 - Tok
2 - Juneau
3 - Anchorage
4 - Nashville
7 - Chattanooga
8 - Memphis
-
-
I want to write "Error" or NULL or something when the row isn't found, then continue on without interrupting things. I've found I can check if $i is less than $row[$i] to see if the row was skipped, but I'm not sure how to correct it at that point.
I can provide more information or a sample database dump if needed. I've just been stuck on this problem for hours and hours, nothing I've tried is working. I would really appreciate your assistance, and general feedback if I'm making any terrible mistakes. Thank you!
Edit: I've solved it! First, iterate through the array to set a NULL value or "Error" message. Then, in the assignations, set $i to $row["id"] right after the mysql_fetch_assoc() call. The full code looks like this:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Reset
for ($i=1;$i<$localityMax+1;$i++)
{
$localityData["id"][$i] = NULL;
$localityData["name"][$i] = "Error";
}
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$i = $row["id"];
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Thanks for the help all!
Primary keys must be unique in MySQL, so you would get a maximum of one possible blank ID since MySQL would not allow duplicate data to be inserted.
If you were working with a column that is not a primary or unique key, your query would need to be the only thing that would change:
SELECT id, name FROM localities WHERE id != "";
or
SELECT id, name FROM localities WHERE NOT ISNULL(id);
EDIT: Created a new answer based on clarification from OP.
If you have a numeric sequence that you want to keep unbroken, and there may be missing rows from the database table, you can use the following (simple) code to give you what you need. Using the same method, your $i = ... could actually be set to the first ID in the sequence from the DB if you don't want to start at ID: 1.
$result = mysql_query('SELECT id, name FROM localities ORDER BY id');
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[(int) $row['id']] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
// This saves a query to the database and a second for loop.
end($data); // move the internal pointer to the end of the array
$max = key($data); // fetch the key of the item the internal pointer is set to
for ($i = 1; $i < $max + 1; $i++) {
if (!isset($data[$i])) {
$data[$i] = array(
'id' => NULL,
'name' => 'Erorr: Missing',
);
}
echo "$i. {$data[$id]['id']} - {$data[$id]['name']}<br />\n";
}
After you've gotten your $localityResult, you could put all of the id's in an array, then before you echo $localityDataStuff, check to see
if(in_array($i, $your_locality_id_array)) {
// do your echoing
} else {
// echo your not found message
}
To make $your_locality_id_array:
$locality_id_array = array();
foreach($localityResult as $locality) {
$locality_id_array[] = $locality['id'];
}
Morning all!
My MySQL query returns a PHP variable name which I'd like to "double" evaluate when I output it. It may be best for me to do this by example.
On the static resources page I have:
$page1 = "test1.php";
$page2 = "test2.php";
And my MySQL table called tbl_pages contains 2 entries under fld_pagename: $page1 and $page2. That way, I figure that I only define $page1 and $page2 once.
Now, on the page I'm working on, I have a query which returns the name of the page:
$query = mysql_query("SELECT fld_pagename FROM tbl_pages WHERE fld_show = 1 ORDER BY fld_ref");
while($row = mysql_fetch_array($query)){
$nameofpage = $row['fld_pagename'];
echo "$nameofpage",'<br />';
}
However, the double quotes around the variable only evaluate the variable to one level. Its output is:
$page1<br />$page2<br />
But I want these variables to be evaluated before output:
test1.php<br />test2.php<br />
Any thoughts much appreciated!
If I get you correctly, you can use this PHP feature (example):
$test1=1234;
$test2='test1';
echo $$test2; // echoes 1234
Or, to make it compatible with your system...
$nameofpage=substr($nameofpage,1); // remove dollar
echo $$nameofpage.'<br/>';
If you're after evaluating the pages you've referenced, then this would work:
$query = mysql_query("SELECT fld_pagename FROM tbl_pages WHERE fld_show = 1 ORDER BY fld_ref");
while($row = mysql_fetch_array($query)){
$nameofpage = $row['fld_pagename'];
include($nameofpage);
echo '<br />';
}
If you only store variable name without $ you can use variable of variable feature of PHP
echo $$nameofpage,'<br />';
can remove $ from input stored
$nameofpage=substr( $nameofpage, 1 );
echo $$nameofpage,'<br />';
it seems your database design is wrong.
There is not a single reason to store PHP variable names in the database.
Store pagenames itself and you'll be okay