在PHP数组中存储和显示MySQL结果

在PHP数组中存储和显示MySQL结果

问题描述:

Suppose I have the following MySQL table result:

ID    price    
-------------
 1     10      
 2     20      
 3     30      


Basically what I want to accomplish is to store these values to a PHP array, and have these values displayed/echoed as a HTML table on a per row basis.

I could do something like:

if($result) {

    $i = 0;

    while ($row = mysql_fetch_array($result)) {
        $id[$i] = $row['id'];
        $price[$i] = $row['price'];      
    }
}

And just have those elements echo together with the HTML table.

However, I also need to have a function that allows the user to delete a row. With that mind I believe I need to have some sort of a 'key' for every row as the identifier for deletion -- a feature which multidimensional array supports.

假设我有以下MySQL表结果: strong> p>

  ID price 
 ------------- 
 1 10 
 2 20 
 3 30 
  code>  pre> 
 
 
基本上我想要完成的是将这些值存储到PHP数组中,并将这些值显示/回显为每行的HTML表。 p>

我可以这样做: p>

  if($ result){
 
 $ i = 0; 
 
 while($ row = mysql_fetch_array($ result))  {
 $ id [$ i] = $ row ['id']; 
 $ price [$ i] = $ row ['price'];  
} 
} 
  code>  pre> 
 
 

让这些元素与HTML表格一起回显。 p>

但是 strong>,我还需要一个允许用户删除行的函数。 有了这个想法,我相信我需要为每一行提供某种“键”作为删除标识符 - 多维数组支持的功能。 p> div>

There's nothing preventing you from using a multi dimensional array and using one of the unique values as an index:

// Store result
$data = array();
if($result) {
    while ($row = mysql_fetch_array($result)) {
        $data[$row['raiser_id']] = $row;
    }
}


// Building table
echo "<table>";
foreach ($data as $row)
{
    echo "<tr>";
    echo "<td>" . $row['raiser_id'] . "</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['fcr'] . "</td>";
    echo "<td>" . $row['date_of_application'] . "</td>";
    echo "<td>" . $row['no_of_heads'] . "</td>";
    echo "<td>" . $row['place_of_farm'] . "</td>";
    echo "</tr>";
}
echo "</table>";


// Removing an entry by raiser_id
$raiser_id = 10;
if (!empty($data[$raiser_id]))
{
    unset($data[$raiser_id]);
    echo "Removed entry";
}
else
{
    echo "No entry to remove";
}

To delete a row from the database, you have to have another PHP script and have to call it using POST method and run an SQL query in it.

If you are talking of just displaying this table, PHP has nothing to do here then - go for JavaScript.

By the time a user sees his table, there is no mysql result, no PHP array and no whole PHP running either. It's all dead long time ago. Keep that in mind.