Selected values as json_encode data - php

I've got two foreach() loops in my php to fetch MySQL data from 2 different dbs.
foreach ($result as $val) {
$country = $val["count"]; //results fetched successfully
$number = $val["tel"];
}
foreach ($rslt as $dta) {
$score = $dta["score"]; //results fetched successfully
$rank = $dta["rnk"];
}
I want to pass the results from both foreach loops as json_encode() data.
My question is, how do I pass $number , $score and $rankas json_encode()?
I tried the below at the bottom of the code, but did not work.
$data = array();
$data[$val] = $val["tel"];
$data[$dta] = $dta["score"];
$data[$dta] = $dta["rnk"];
echo json_encode($data);
Expecting output:
[{"tel":"123456","score":"785","rnk":"135"}]

$dta and $val are only in the loops scope. You assign variables within the loop, so use them.
$data = array();
$data['tel'] = $number;
$data['score'] = $score;
$data['rnk'] = $rank;
echo json_encode($data);
You can also assign $data within your foreach loop.
$data = array();
foreach ($result as $val) {
$data['country'] = $val["count"]; //results fetched successfully
$data['tel'] = $val["tel"];
}
foreach ($rslt as $dta) {
$data['score']= $dta["score"]; //results fetched successfully
$data['rank'] = $dta["rnk"];
}
echo json_encode($data);

try this
$data = array();
foreach ($result as $val) {
$data['tel'][] = $val["tel"];
$country = $val["count"]; //results fetched successfully
$number = $val["tel"];
}
foreach ($rslt as $dta) {
$data['score'][] = $dta["score"];
$data['rnk'][] = $dta["rnk"];
$score = $dta["score"]; //results fetched successfully
$rank = $dta["rnk"];
}
echo json_encode($data);
Added an extra [] if array size of $val["tel"],$dta["score"],$dta["rnk"] is greater than 1 else you can remove [] if array size is 1

Related

Data in nested foreach loops used in update query

This is my code:
session_start();
/* loops through each row in the global $_SESSION variable which
contains the array and uses the $value to GET the data in the text
boxes and output them */
// studevent_result =
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
echo $studResult;
echo "<br>";
}
// result_postion =
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition = $_GET[$value];
echo $studPosition;
echo "<br>";
}
echo "<br>";
// stud_id =
foreach ($_SESSION['arrayId'] as $value) {
echo $value;
echo "<br>";
}
// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
UPDATE result
SET studevent_result = '00:20:33',
result_position = '6'
WHERE result.stud_id = '12'
";
$updateRow = mysqli_query($conn, $updateQuery);
I use $_SESSION variables which all store an array. I extract the results of these arrays using foreach loops.
In $updateQuery, I want to make studevent_result = to the results of my first foreach loop above, result_position = to the results of the second foreach loop above and the result.stud_id = to the results of the third foreach loop above.
After me editing the code my code now looks like this:
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
foreach ($_SESSION['arrayNamePosition'] as $data) {
$studPosition = $_GET[$data];
foreach ($_SESSION['arrayId'] as $idValue) {
echo $idValue;
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult',
result_position = '$studPosition'
WHERE result.stud_id = '$idValue'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
}
}
I nested the foreach loops. But the problem now is that for the last foreach loop in the nested loops, $idValue in the query only uses the last element in the array $_SESSION['arrayId']. How can I fix this to loop throught the whole array, so that the query uses all the values in the array?
Thanks in advance.
If I understood your issue this should help you
session_start();
$i = 0;
$studResult = array();
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult[$i] = $_GET[$value];
$i++;
}
$studPosition= array();
$i=0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
}
$stud_id = array(); $i=0;
foreach ($_SESSION['arrayId'] as $value) {
$stud_id[$i] = $value; $i++;
}
for($j =0; $j<$i; $j++){
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult[$j]',
result_position = '$studPosition[$j]'
WHERE result.stud_id = '$stud_id[$j]'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
Hope it will be helpful. Happy coding :)

getting duplicated results from nested foreach loop

I'm trying to get the following output from mysql for Google Line Chart API:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
I have set up several input checkboxes to send field names (e.g width,diameter) to the database via $_POST["info"] and retrieve the values from those fields. Here's the part that generates the data from mysql:
$result = $users->fetchAll();
$comma = "";
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
My desired output should be like this:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
But that code is generating duplicated results like this
[["product","diameter","width"],["Product 1","24"],["Product 2","24,4,8"]]
I guess I shouldn't be using the nested foreach to loop over $_POST. Can anyone tell me how to fix that?
Full PHP Code:
$info = $_POST["info"]; // It contains an array with values like width,diameter,thickness etc...
$comma = "";
foreach($info as $in)
{
$field .= "".$comma."b.".$in."";
$comma = ",";
}
$sql = "
SELECT {$field},a.user_id,a.name
FROM `product_detail` a INNER JOIN
`attr` b ON a.model = b.model
WHERE a.user_id = ?
GROUP BY a.model
";
$users = $dbh->prepare($sql);
$users->bindValue(1, $_SESSION["user_id"]);
$users->execute();
$result = $users->fetchAll();
$comma = "";
$data="";
$i = 1;
$data[0] = array_merge(array(product),$info);
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p];
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
$_POST["info"] Content:
Array
(
[0] => diameter
[1] => width
)
try it like this:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d[]=$r["name"];
foreach($_POST["info"] as $p)
{
$d[]= $r[$p];
}
$data[$i] = $d;
$d=array(); //set $d to empty not to get duplicate results
$i++;
}
echo json_encode($data);
The end result you are looking for, is valid JSON. You should not try to manually generate that.
Instead you should make an array of arrays in php and use json_encode($array) to get the result you are looking for.
Also note that by injecting your POST variables directly in your query, you are vulnerable to sql injection. When accepting fields, you should check them against a white-list of allowed values.
Try the below solution:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d = array();
foreach($_POST["info"] as $p)
{
$d[] = $r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$data[$i] = array($r["name"]) +$d;
$i++;
}
echo json_encode($data);

how to store associative array php MySQL

I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}

HTML select not inflating correctly from PHP array

I am trying to create a drop down menu of usernames or a <select> as it's known in HTML. However I am only getting the last value back from my array and I can't figure out why.
PHP
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
HTML
<select>
<?php $names = getUserName($db); foreach($names as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value ?></option>
<?php }?>
</select>
I'm fairly sure the HTML section of my code is solid. I think the error lies in how I'm adding values to my $names array but after staring at it for a half an hour I can't see it. Thanks for any help/fresh eyes.
You need to declare your array outside the loop
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
this is emptying your array every time : $names = array();
use this :
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
You are creating a new $names array every row then returning the last one. You need to declare the array outside the while loop. The following should work:
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
The problem is you're re-initializing the array on every loop:
See:
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
Should be:
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;

How to get last value of for loop?

I'm trying to get the value of $row->price for the last iteration in my for loop as below
foreach ($getprices->result() as $row)
{
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
I did try the following, however it didn't appear to work
$numItems = count($getprices->result());
$i = 0;
foreach($getprices->result() as $row) {
if(++$i === $numItems) {
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
}
}
Any suggestions?
Use $row->price just after the loop has ended:
foreach ($getprices->result() as $row)
{
// ...
}
$lastprice = $row->price;
This is really just a trick, but it will work. If you are iterating over an array you can also do it like this:
$array = $getprices->result();
foreach ($array as $row)
{
// ...
}
$lastprice = end($array)->price; // this will work independently of any loop
Add a line $lastitem=$row right after the for statement ; it will contain the last value after the loop is finished
You can use php end to get the last value of an array.
eg;
$arr = $getprices->result();
$last = end($arr);

Categories