Dave
Dave

Reputation: 23

Table generated from database table - how to add in £ sign?

I have the following code,

<?php
// sending query
$result = mysql_query("SELECT * FROM {$table} ORDER BY Price");
if (!$result) {
    die("Query to show fields from table failed");
}

$fields_num = mysql_num_fields($result);


echo "<table width='700px'><tr>";

// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($result);
    echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

    echo "</tr>\n";
}
mysql_free_result($result);


?>

There is a "Price" column where I need the £ sign inserted before each price before it is displayed. I have the HTML code &#163; and &pound; , however I am not sure where one would insert that to add it before to only the records coming from the Price column.

Upvotes: 0

Views: 82

Answers (4)

rzetterberg
rzetterberg

Reputation: 10268

You could get the key of the column by doing this:

foreach($row as $key => $cell){
    if($key == "Price"){
        echo "<td>&pound; $cell</td>"; //From price column
    }else{
        echo "<td>$cell</td>"; //From other columns
    }
}

Edit: if you want to check that it's printing at the right column:

foreach($row as $key => $cell){
    if($key == "Price"){
        echo "<td>$key: &pound; $cell</td>"; //From price column
    }else{
        echo "<td>$key: $cell</td>"; //From other columns
    }
}

Now it will output the name of the column so you will see which column contains the right information. Then when you found the right information just replace "Price" in the if-statement to the right one and then remove $key from the echo.

Upvotes: 0

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

I suggest you retrieve values with mysql_fetch_assoc(). That way you will obtain an associative arrays and you can do this:

foreach($row as $cell_name => $cell_value){
}

Note: this will only work if you don't have duplicate names in the result set.

Upvotes: 1

shadyyx
shadyyx

Reputation: 16055

I'd recommend rewritting to use mysql_fetch_assoc instead of mysql_fetch_row -> therefore You know when price (and other column)s is being processed:

// printing table rows
while($row = mysql_fetch_assoc($result)) {
    echo "<tr>";
    // $row is associative array...
    echo "<td>$result['id']</td>";
    echo "<td>$result['name']</td>";
    ...
    echo "<td>&pound; $result['price']</td>";
    ...
echo "</tr>\n";

}

Upvotes: 1

Svish
Svish

Reputation: 158121

If you use mysql_fetch_assoc instead, you can do in your foreach:

foreach($row as $name => $value)
{
    if($name == 'price')
        echo ...;
    else
        echo ...;

}

Upvotes: 1

Related Questions