Angelo Tan
Angelo Tan

Reputation: 321

Store and display MySQL result to/from PHP array

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.

Upvotes: 0

Views: 2208

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157839

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.

Upvotes: 1

xsist10
xsist10

Reputation: 3051

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";
}

Upvotes: 1

Related Questions