PHP foreach loop giving only 1 result - php

I have this array:
$cust = xtc_db_query("SELECT customers_id FROM orders");
$customers = xtc_db_fetch_array($cust);
When I try to display every single record I get only the first one:
foreach ($customers as $v) {
echo "ID: $v.\n <br>";
}
I tried setting the array manually and then it works fine:
$customers = array(1, 2, 3, 17);

Your $customers array will only ever contain one value (the last result from the query). You'll need to use a while loop:
$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust))
{
// Use $customers here.
}

$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust)){
echo "ID: $customers[customers_id].\n <br>";
}

xtc_db_fetch_array will return one record in every iteration.
To get all the records, you'll have to put xtc_db_fetch_array($cust) in while loop like below.
$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust)){
print_r($customers);
}

Related

Getting all records json_encode

I'm trying to get all data from table 1 in json format.
$arr = array();
$sql = "SELECT * FROM table1 ORDER BY price DESC";
$statement = $connect->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $val){
$arr['id'] = $val['item'];
$arr['price'] = $val['price'];
}
echo json_encode($arr);
Result:
{"id":"item00125","price":"112.35"}
The problem is that I get only one record. Why isn't the foreach(){ not sending all the records?
Try:
foreach ($result as $val){
$arr[] = array(
"id" => $val['item'],
"price" => val['price']
);
}
That's because your array is being over-written every time.
Try this:
$i = 0;
foreach ($result as $val){
$arr[$i]['id'] = $val['item'];
$arr[$i]['price'] = $val['price'];
$i++;
}
echo json_encode($arr);
You got only one result because you override array key at every itration of loop
Just pass result set into json_encode Without using loop as
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
here your result variable get the all records but the problem is in the for each loop you are put the each value in position of ['id'] and ['price'] so every time for each loop put the value at that same position so means replace the value so you are getting the last value so I thing you have to put the every record in different different position like this:
$i = 0;
foreach ($result as $val)
{
$arr[$i]['id'] = $val['item'];
$arr[$i]['price'] = $val['price'];
$i++;
}
echo json_encode($arr);
I hope it works fine

Array for a SQL database using PHP

Can someone please help? I'm new to PHP and struggling to make this bit of code to work. For example I have a sql database table with the following schema and data:
Type....rent_price
a..........100
b..........200
c..........300
I want to be able to echo say, "a", in one section and "200" in another. The following code will display "a" but then I can't seem to get it to display anything from the rent_price column using a second array.
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['type']);
for ($set1 = array (); $row = $result->fetch_assoc(); $set1[] =$row['rent_price']);
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
You loop through the results twice, without resetting. Try to loop only once:
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
$set = array ();
$set1 = array ();
while ($row = $result->fetch_assoc())
{
$set[] = $row['type'];
$set1[] =$row['rent_price'];
}
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
Depending on what you mean by '"a" in one section and "200" in another', you may be able to forgo creating the intermediate arrays and just print the values from your query as you fetch them. Two cells in a table row, for example:
while ($row = $result->fetch_assoc()) {
echo "<tr><td>$row[type]</td><td>$row[rent_price]</td></tr>";
}
your data is in the first element of array
$set1[0]
but youre probably better off maintaining the naming throughout
$results = array();
while ($row = $result->fetch_assoc()){
$results[] = $row;
}
foreach ($results as $result){
echo $result['type'];
echo $result['rent_price'];
}
OR
$results = array();
while ($row = $result->fetch_assoc()){
$results['types'][] = $row['type'];
$results['rent_prices'][] = $row['rent_price'];
}
foreach ($results['types'] as $type){
echo $type;
}
foreach ($results['rent_prices'] as $rent_price){
echo $rent_price;
}

array_sum returning the sum of values as string

This seems like it should be really straightforward, but I keep getting unexpected output. I'm trying to access specified rows in a SQL database which each contain a numerical value and then calculate the sum of those values. PHP is concatenating the values as if they were strings even after I've set the datatype of the values to float. My code:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I have also tried:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
My output is always something like: 100002000030000
with 10,000 20,000 and 30,000 being the values of each population.
I've successfully calculated sums using foreach with values that weren't retrieved from MySQL.
What is going on here?
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I think what you want is this:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);
First, don't initialize the array with an empty string. Do this instead:
$total = array();
or with the new style:
$total = [ ];
Second, rewrite the floatval thing like this:
array_push($total, floatval($value));
That should fix it...

how to count duplicates values inside while loop using php

$query = "select * from tableitem";
$result = mysql_query($query);
$col = array();
while ($row = mysql_fetch_array($result)){
//they have computation here inside loop.
$amount = $value;
if($row['status']>3){ // base on the status only
if($amount>0){ //base on the computation
$count = $item;
// i need to count here the item before the grouping of duplicate item below.
if (!isset($col[$row['item']])) { // this is working for grouping the duplicate value
echo $row['item'];
echo $count; // count item
$col[$row['item']] = true;
}
}
}}
Sample output should be like this inside while loop if possible.
Item one 2
Item two 3
Item five 4
You can do that with sql not necessary php;
SELECT COUNT(*) as N,item
FROM tableitem
GROUP BY item
it will return duplicate items and you can check with n>1. And you can add more column for group.
$itemArray;
while ($row = mysql_fetch_array($result)){
if($row['n']>1){
itemArray[] = $row['item'];
}
}
print_r($itemArray);
If you increment array values using the keys you are trying to count:
$check = array();
foreach($values as $key => $value) {
if (isset($check[$key])) {
$check[$key]++;
} else {
$check[$key]=1;
}
}
var_dump($check);

How to fetch all the matched rows from a Mysql table in a PHP array

I am trying to get the matched rows from a table and save it in a Global Array so that I can use it in different functions.
But when I do print_r of that array it shows only last row.
Here is my code
function setCampoFeed()
{
echo $sql = "SELECT campofeed.tag,campofeed.registro,campofeed.valor FROM campofeed ".
"INNER JOIN registrofeed ON registrofeed.id = campofeed.registro ".
"WHERE registrofeed.feed='".$this->idFeed."'";
$result= $this->localDb->execute($sql);
$this->campoFeed= mysql_fetch_array($result))
}
So here campoFeed is the array that should have all the rows of the match, but now its just having the last row.
Thanks in advance
Use
$this->campoFeed[] = mysql_fetch_array($result);"
insted of
$this->campoFeed= mysql_fetch_array($result);
You will get all data in array
Try this one if it works for you..
$resultArray = array();
$campoFeed = array();
$resultArray = mysql_fetch_array($result);
foreach($resultArray as $key => $value){
$campoFeed[$key] = $value;
}
print_r($campoFeed);
Use this
$mergedArray=array();
while($data= mysql_fetch_array($result)) {
$final_array = unserialize($data['data']);
$mergedArray=array_merge($mergedArray,$final_array);
}
array_unique($mergedArray, SORT_REGULAR);

Categories