I'm trying to do a little text formatting and query the SQL all in one hunk of code. Previously, it was doing the listing just fine without formatting, but I need to replace underscores with spaces and remove the category that precedes each string for the purposes of user readability.

<?php
 //doing the query
    $query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
    $result = mysql_query($query) or die("Unable to query parts table!");
    while($row=mysql_fetch_array($result)) {
 //explode removes the preceding category, str_replace obviously replaces the _
        $labelCPU = explode(':',str_replace('_',' ',$row['itemName']));
 //displays the option in HTML
        $aa .= "<option value='{$row['partID']}'>$labelCPU</option>";
        }
?>
<select name="cpu"><? echo $aa; ?></select>

When it echoes the variable in the list, I can tell the query is still executing fine because I am getting the appropriate number of options, but they all display as "Array".

Where am I going wrong here?

有帮助吗?

解决方案

Your line below:

$labelCPU = explode(':',str_replace('_',' ',$row['itemName']));

Is changing it into an array. Explode basically takes a string and converts it to an array splitting it by the character you specify (in this case ':').

You need to do something like:

for ($i=0; $i<count($labelCPU); $i++) {
    $aa .= "<option value='{$row['partID']}'>$labelCPU[$i]</option>";
}

I suspect you are using explode to get the category name after ":". So perhaps this would work better:

    $aa .= "<option value='{$row['partID']}'>$labelCPU[1]</option>";

其他提示

php function explode returns an array.
Place
var_dump($labelCPU);
after explode statement. It will dump all the data stored in $labelCPU. Then find the element which holds your desired data

Switch out for mysql_fetch_assoc if you aren't using numeric keys, you're also just missing an index on what you've exploded (I added a comment).

Note that the mysql_fetch_assoc/array are being deprecated in favor of PDO. Might want to consider switching out if longevity is a concern.

<?php

$query  = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query parts table!");
$aa     = "";

while($row = mysql_fetch_assoc( $result ) ) 
{
    $labelCPU = explode(':',str_replace('_',' ',$row['itemName']));
    $labelCPU = $labelCPU[1]; // this is what you're missing
    $aa .= "<option value='{$row['partID']}'>$labelCPU</option>";
}
?>
<select name="cpu"><? echo $aa; ?></select>

Good luck!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top