PHP pass variable to foreach loop from a mySQL result - php

I need to pass a variable to a foreach loop from a mySQL result.
So I have this code:
$GetClaim = "SELECT * FROM cR_Claimants WHERE memberID = '".$memberID."' AND ParentSubmission ='".$refNumb."'";
$resultGetClaim=mysql_query($GetClaim) or die("Error select claimants: ".mysql_error());
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
$name = $rowGetClaim['Name'];
$city = $rowGetClaim['city'];
$region = $rowGetClaim['region'];
}
Now I need to pass the variable to the foreach
foreach($name as $k=>$v) {
echo $city;
echo $region;
etc..
}
The above code does not work. I think I cannot pass a variable from a mySQL loop. The problem is also tat every row I get from the database should be related to the specific $name. So obvioiusly one $name will have its own $city etc..
How do I achieve this?
Please help

You are not retrieving an array with all returned records, you are retrieving an array which contains a single record.
To get the next name (the next record), you must make another call to mysql_fetch_array.
The code you present does that implicitly by assigning $rowGetClaim within a while conditional. A failed mysql_fetch_array call would return false, which would exit the while loop.
There is absolutely no need to use the for each as you presented. Just place the echo right after the assignment (e.g.
$region = $rowGetClaim['region'];
echo $region

Either out put directly fromt eh loop or build an array and then loop through it.
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
echo $rowGetClaim['Name'];
echo $rowGetClaim['city'];
echo $rowGetClaim['region'];
}
OR
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
foreach($rowGetClaim as $k => $v{
echo $v;
}
}
OR
$names = array();
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
$names[] = $rowGetClaim;
}
foreach($names as $data){
foreach($data as $k => $v) {
echo $v;
}
}

Related

how to loop through array with dynamic keys in PHP

I have an array data where I am storing the result of an SQL query as below :
$stmt = sqlsrv_query($db,$sql);
$data = [];
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
if(!empty($row)) { $data[] = $row; } }
then I want to create a group key which is the concatenation of specific keys of my array data as below :
foreach ($data as $d) {
$group_key = $d['id'].'_'.$d['Country'].'_'.$d['Order Numer'];
//rest of my code
}
it works fine but I want to choose the keys dynamically instead of setting up manually id, Country and Order Number...
let's say I have an array $PostKeys = ["id","Country","Order Number"]; this array will vary depending on the values selected by user...
What I did is :
$PostKeys = ["id","Country","Order Number"];
foreach ($data as $d) {
foreach($PostKeys as $value)
{ $array_group_key[] = $d[$value] ; }
$group_key = implode("_",$array_group_key);
// rest of my code
}
I am supposed to get the same result but there is always mismatch. I didn't figure out where is the issue exactly. Any suggestions please ? Thank you very much.
You need to empty $array_group_key each time through the loop. Otherwise, you're appending to the results from all the previous rows.
foreach ($data as $d) {
$array_group_key = [];
foreach($PostKeys as $value)
{
$array_group_key[] = $d[$value] ;
}
}

moved working routine to function, now results are not present

As I try to consolidate my code and make it more available to other projects, I've run into a problem:
variables that were generated and available are not anymore when that routine is moved to a function:
This is the query:
$count = "SELECT eid, Count, Name, name2, Email, pay FROM h2018";
THIS WORKS FINE:
$result = $mysqli->query($count);
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
echo($a." and ".$value."<BR>");
}
NOT WORKING FINE:
function avar($result) {
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
}
}
$result = $mysqli->query($count);
avar($result);
echo($a." and ".$value."<BR>");
I thought the variable variables would be available from outside of the function. I tried doing a return, but that didn't help. I also tried to global $$key, but that didn't work either.
What am I doing wrong?
There is multiple mistakes or missing steps like return or array
function avar($result) {
$data=array();
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$data[$key] = $value;//if there is multiple records then used array otherwise you should used variable
}
return $data;
}
$result = $mysqli->query($count);
$data=avar($result);//get return value
print_r($data);
Please, read the PHP documentation about the Variable Scope for more information. The variables inside your function are local so you cannot access them outside of your function. You would have to return something.
For example, this could work:
function avar($result) {
$resultArray = false;
$row = $result->fetch_assoc();
foreach ($row as $key => $value) {
$resultArray = [
'key' => $key,
'value' => $value
];
}
return $resultArray;
}
$result = $mysqli->query($count);
$queryResult = avar($result);
if ($queryResult) {
echo 'Key: ' . $queryResult['key'] . ' | Value: ' . $queryResult['value'];
}
Please do note that fetch_assoc will return an array with multiple items if there is more than one result. In my example only one (and the last) result will be returned.
Edit: As #Nigel Ren said in his comment. In this case you're basically rebuilding an array which is going to look (nearly) the same as the array which is being returned by fetch_assoc, which is pointless. My function can be used if you want to add conditions in the future, or manipulate some data. Otherwise, don't use a function and just use the results from fetch_assoc.

How to loop through a JSON array and put data in variables

I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:
Notice: Trying to get property of non-object
My JSON data looks like this:
{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?
<?php
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = $data->AttractionInfo[0]->Id;
$attractieType = $data->AttractionInfo[0]->Type;
$attractieStatus = $data->AttractionInfo[0]->State;
$attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
$attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
$attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;
?>
I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.
Update code:
require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);
$sql = "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.
try this...
$content = json_decode(file_get_contents($url));
foreach($content->AttractionInfo as $data ){
$id = $data->Id;
$type = $data->Type;
$map = $data->MapLocation;
$state = $data->State;
$color = $data->StateColor;
if(!empty($data->WaitingTime)) {
$time = $data->WaitingTime;
}
if(!empty($data->StatePercentage)) {
$percent = $data->StatePercentage;
}
//persist your data into DB....
}
I think you need something like this:
$json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
$arr = json_decode($json);
foreach ($arr->AttractionInfo as $key => $attraction) {
foreach($attraction as $key=> $value) {
print_r($key.' - '.$value.'<br>');
$$key = $value;
}
}
echo '<br>';
echo $Id; // it will be last item/attraction id.
We can improve this code. Just say where and how do you want to use it

PHP: show only last data from same data on loop

i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}

How to fetch URL variable array using $_REQUEST['variable name']

I am using a URL to fetch data stored/shown within URL. I get all the value of variable using $_REQUEST['v_name'] but if there is a array in URL how can i retrieve that value.
For Example:
WWW.example.com/rooms?&hid=213421&type=E
I got the value hid and type using
$hid=$_REQUEST['hid'];
but in URL like:
WWW.example.com/rooms?&rooms=2&rooms[0].adults=2&rooms[0].children=0&rooms[1].adults=2&rooms[1].children=0
how can i retrieve value of adults and children in each room.
please help.
Thanks in Advance
You could also try something like this, since most of your original $_REQUEST isn't really an array (because of the .s in between each key/value pair):
<?php
$original_string = rawurldecode($_SERVER["QUERY_STRING"]);
$original_string_split = preg_split('/&/', $original_string);
$rooms = array();
foreach ($original_string_split as $split_one) {
$splits_two[] = preg_split('/\./', $split_one);
}
foreach ($splits_two as $split_two) {
if (isset($split_two[0]) && isset($split_two[1])) {
$split_three = preg_split('/=/', $split_two[1]);
if (isset($split_three[0]) && isset($split_three[1])) {
$rooms[$split_two[0]][$split_three[0]] = $split_three[1];
}
}
}
// Print the output if you want:
print '<pre>' . print_r($rooms, 1) . '</pre>';
$valuse = $_GET;
foreach ($valuse as $key=>$value)
{
echo $key .'='. $value. '<br/>';
}

Categories