简体   繁体   中英

Trying to loop through an array in PHP. Is there a better way to do this?

So I have three tables I am trying to fetch data from.

A Customers table An Orders table and a Parts table

I am trying to basically produce a report that displays what the user bought and how much it cost. This involves getting their accountID from Customers, joining that with the accountID attached to the OrderID in Orders then taking the PartID within orders, attached to orderID, and returning the partName.

What I was thinking was looping through a php array and using sql to populate it with customerNames then use sql for the other queries to sort everything by name. Not sure if that is the best way to do that though since INNER JOIN wasn't working for me when trying to query 3 tables. Here is my code for the array:

$sql = "SELECT firstName FROM Customers INNER JOIN Orders ON 
    Customers.accountID=Orders.accountID";
$statement = $conn->query($sql);

$i = 0;
$NameArray = array();

while ($Names = $statement->fetch()) {
    echo "<br>";
    echo $Names[0];
    $NameArray[$i];
    echo "<br>";
    $i++;
}

this give the error undefined index. Not really sure why

$sql = "SELECT firstName FROM Customers INNER JOIN Orders ON 
Customers.accountID=Orders.accountID";
$statement = $conn->query($sql);

$i = 0;
$NameArray = array(); ***CREATES an empty array

while ($Names = $statement->fetch()) {
    echo "<br>";
    echo $Names[0];
    $NameArray[$i];  ***Should start with 'echo'.
                        Also, there's nothing assigned to $NameArray[$i]
    echo "<br>";
    $i++;
}

In the above code, I found 2 issues and noted them, but neither will solve your index error. You still have to assign a value to $NameArray[$i] before you can echo it without the index error.

Regarding your loop to lookup the info, you might be able to just add the [Cost] field to your SQL like this:

SELECT Customers.firstName, Orders.Cost, Orders.PartID FROM Customers INNER JOIN Orders ON 
Customers.accountID=Orders.accountID

You can subsequently add the Parts table to the query with the following join:

Orders.PartID = Parts.PartID

And then simply add Parts.partName to the SELECT fields.

I guess you are running mysqli

you will need to list all the table column for both customer and order table.

Now for testing, am adding a column name for customer and quantity for order tables.

lets assume that we want to select Customers.name and Orders.quantity from database

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = 'SELECT Customers.accountID, Customers.name, Orders.quantity, Orders.accountID FROM Customers
LEFT JOIN Orders ON Customers.accountID=Orders.accountID
ORDER BY Customers.accountID';

    $result = mysqli_query($con,$query);
    while($row = mysqli_fetch_assoc($result)){ 
  $order_quantity = $row['quantity'];
  $customer_name = $row['name'];

//you can now echo

echo $customer_name.' '.$order_quantity.'<br/>';
}
?>

Now since you wants to generate an arrays, your code will look like below

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

 $res_arr = array();

$query = 'SELECT Customers.accountID, Customers.name, Orders.quantity, Orders.accountID FROM Customers
LEFT JOIN Orders ON Customers.accountID=Orders.accountID
ORDER BY Customers.accountID';

    $result = mysqli_query($con,$query);
    while($row = mysqli_fetch_assoc($result)){ 
  $order_quantity = $row['quantity'];
  $customer_name = $row['name'];

$res_arr[] = array("customer name" =>$customer_name, "order quqntity" =>$order_quantity);
}
 echo json_encode($res_arr);
    exit
?>

or you can just do as per below if you do not want the resultant array response to be parameter initialized..

$result = mysqli_query($con,$query);
    while($row = mysqli_fetch_array($result)){    

        $res_arr[] = $row;
}
    echo json_encode($res_arr);
    exit;

Actually $NameArray is an empty array.

Probable you want something like: $NameArray[$i] = $Names[0]; and at the end of the loop you will have all the firstName(s) in $NameArray

Sorting by name can make mysql better

$sql = "select firstName
from Customers AS Customers
inner join Orders AS Orders on Customers.accountID = Orders.accountID
GROUP BY Customer.accountID
ORDER BY Customer.firstName";

...

$i=0;
while($Names=$statement->fetch()){
    echo $Names[$i];
   $i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM