Foreach Loop Php Mysql检索

i want to retrieve mysql data using foreach loop, as i had 10 employees records with expenses, i want to display each employee name and his expenses with a table in a loop. please suggest me how to call this function using foreach

$data = mysql_query("SELECT * FROM employees where dt >= '$from' AND dt <= '$to' ORDER by empname ASC");
while ($result = mysql_fetch_assoc($data))
{

$ta = $result["ta"];
$da = $result["da"];
$petrol = $result["petrol"];
}

I need report like this.

Empname:

Record1 Record2
-----------------
Empname:

Record1 Record2
---------------

Please help.

There is no more support for mysql_* functions, they are officially deprecated, no longer maintained and will be removed in the future. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future.


Since you're using mysql_*, I hope you're using mysql_real_escape_string on your $to and $from variables if they are coming from user input.

I am still not sure why you want to use a foreach but what you want to do, can be done with while which is also a loop:

$data = mysql_query("SELECT * FROM employees where dt >= '$from' AND dt <= '$to' ORDER by empname ASC");
while($result = mysql_fetch_assoc($data))
{
    $rows[] = $result;
}

print_r($rows);

Here is a working example using MySQLi:

<?php
$from = $_POST['from'];
$to = $_POST['to'];

if (is_null($from) || is_null($to))
    die('You must fill the from and to fields...');

$db = new mysqli('localhost', 'root', '', 'test_database');
if($db->connect_error)
    die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

if (!$stmt = $db->prepare("SELECT empname, ta, da, petrol FROM employees WHERE dt >= ? AND dt <= ?"))
    die('Prepare Error: ' . $db->error);

if (!$stmt->bind_param('ss', $from, $to))
    die('Bind Parameters Error ' . $stmt->error);

if (!$stmt->execute())
    die('Select Query Error ' . $stmt->error);

$stmt->bind_result($empname, $ta, $da, $petrol);
$rows = array();
while($stmt->fetch())
{
    $rows[$empname][] = array('ta' => $ta, 'da' => $da, 'petrol' => $petrol);
}
$stmt->close();
$db->close();

foreach ($rows as $empname=>$data)
{
    echo $empname . ':<br /><br />';
    foreach ($data as $result)
    {
        echo $result['ta'] . ' ' . $result['da'] . '<br />';
        echo '-----------------<br />';
        $petrol = $result['petrol'];
    }
    echo '==========================<br />';
}

Output:

Jorge:<br /><br />
12 3<br />
-----------------
1 4<br />
-----------------
2 6<br />
-----------------
3 1<br />
-----------------
33 11<br />
-----------------
==========================<br />
John:<br /><br />
4 3<br />
-----------------
5 6<br />
-----------------
6 8<br />
-----------------
7 9<br />
-----------------
8 10<br />
-----------------
==========================<br />