开发者

MYSQL, how to get rows with field value of 'x' in this case?

I am using PHP to query a mysql db.

After the query, I am using mysql_fetch_array in a while loop to display all results inside a table.

Now, depending on a variable ($adtypes) I want the query-results-array to change...

Explanation: ($query_results is the name of the array containing the query results, basically something like SELECT * FROM table so it selects everything!

$adtypes = $_GET['adtypes'];
//$adtypes is irrelevant to query, the query is already done before all thi开发者_运维知识库s.
switch ($adtypes){
case "Private":
$query_results = //Here I want the array to only contain values where the mysql row field = 'Private'
    break;
    case "company":
    $query_results = // Same thing as above, but only company ads
    break;
    }

Then I do a loop through the array to display the results like this:

while($row = mysql_fetch_array($query_results)){

How can I make sure the array (query_results) only contain the info I want WITHOUT doing another query ?

Thanks

If you need more input, tell me and I will update this Q.

UPDATE

I cannot have another query, because my queries are very large, and they DO affect performance in a negative way.

I Think a foreach is what I am after...

Also, the reason I cant manipulate the current query is because I am displaying the nr of private ads and nr of company ads on my site, and all that info comes from the query.

So, if I query my db where I only search for private ads, then I cant display how many company ads there where ( IF i dont do another query )!

Thanks anyways guys...


SELECT * FROM table WHERE field = 'Private'

no need to use php for this. but if you really need to, you could use array_filter:

$query_result = array_filter($query_result, create_function('$var', 'return $var['field'] != \'Private\''));

edit: as stated in the comments, to get the number of private and company ads, use mysql’s COUNT:

  SELECT `adtype`, COUNT(*) as `nr_of_ads`
    FROM `ads`
GROUP BY `adtype`


It seems questionable that you either can't do another query, or use the filter on the query in the first place; this leads me to think that your design needs to be slightly revisited.

In any case, the value that you pass to mysql_fetch_array is a resource identifier; it is pointing to the resource that represents the output of the original query, but it isn't actually the output of the original query. If this is really the only query that you can run, and you really want to only have results that contain the $adtypes value, then you will need to filter these from the original query results (within the loop on mysql_fetch_array). You can't change the resource that $query_results is pointing to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜