PHP检索结果

I am having a small trouble retrieving results that I hope someone can help me with.

I have a field called $incategory which is a comma based string, and what I want to do is explode the into an array that can be used to retrieve results as below (Hope that makes sense):

<?php 

$showlist = $row_listelements['incategory']; 

// ** e.g. $incategory = 1,3,5, 
// ** What I want to do is look at table 'category' 
// ** and retrieve results with an 'id' of either 1, 3 or 5

// ** Display Results
mysql_select_db($database_db, $db);
$query_display = "SELECT * FROM category WHERE id = ".$showlist." ORDER BY name ASC";
$display = mysql_query($query_display, $db) or die(mysql_error());
$row_display = mysql_fetch_assoc($display);
$totalRows_display = mysql_num_rows($display);

?>

You can use the IN keyword of SQL directly like this.

query_display = "SELECT * FROM category WHERE id IN (".$showlist.") ORDER BY name ASC";

Another tip would be to stop using MYSQL_QUERY as it is deprecated in PHP 5.3

Edit: If $showlist = '1,3,5,' you will need to remove the last comma from the string to make it useable in the query. Just use this query then

query_display = "SELECT * FROM category WHERE id IN ('".str_replace(",", "','", substr($showlist, -1))."') ORDER BY name ASC";

Use explode function and use , as delimiter.

refer here http://www.w3schools.com/php/func_string_explode.asp

Hope this helps.

First, you have explode the $incategory string into an array containing all of the category number. For example:

$incategory = explode(",", $incategory);

And then you just have to execute this query:

$query_display = "SELECT * FROM category WHERE id = "
               . $incategory[$i] . " ORDER BY name ASC";

The $i should be defined beforehand (usually using loop).