简体   繁体   English

PHP如何检查mysql结果的值?

[英]PHP how to check mysql result for values?

I want to see whether there are rows with certain values in mysql result, for example whether any row in the result has product_category=25 Can I do that without using mysql_fetch_array and if I can't then why can't I use mysql_fetch_array twice on the same result? 我想查看mysql结果中是否存在具有某些值的行,例如结果中的任何行是否具有product_category = 25可以不使用mysql_fetch_array而做到这一点,如果不能,为什么我不能在两次使用mysql_fetch_array同样的结果? Is there a workaround? 有解决方法吗? Can I copy the result into another variable and run mysql_fetch_array on that? 我可以将结果复制到另一个变量中并在其上运行mysql_fetch_array吗? I tried that but the copy changes as the original changes (as mysql_fetch_array goes through it). 我试过了,但是副本随着原始更改而更改(因为mysql_fetch_array通过它)。

You can't use mysql_fetch_array twice (and get the same row), because it advances the pointer to the row in your result. 您不能两次使用mysql_fetch_array(并获得同一行),因为它会将指针前进到结果中的该行。 (So if you retrieve multiple rows, the first call will fetch the first row, and the second will fetch the second row.) (因此,如果您检索多行,则第一个调用将获取第一行,第二个调用将获取第二行。)

As Shakti already pointed out, use a loop to go over all rows, and test for the expected value: 正如Shakti已经指出的那样,使用循环遍历所有行,并测试期望值:

while ($row = mysql_fetch_array($result)) {
    if ($row['product_category'] == 25) { /* execute your code here */ }
}

Without knowing your code, I need to guess. 不知道您的代码,我需要猜测。

The mysql-result-resource is a cursor to the concrete result. mysql-result-resource是具体结果的指针。 This means, that you can only access the current entry directly. 这意味着您只能直接访问当前条目。 You must iterate over the result (eg via mysql_fetch_array() ) to access every single result item. 您必须遍历结果(例如,通过mysql_fetch_array() )以访问每个结果项。 If you can't call it twice, you probably have just one single item as the result of your query, because you can call it as many times as you want, but if you don't have any more rows to retrieve from the resource, it will always return false . 如果您不能两次调用它,那么您的查询结果可能只有一个项目,因为您可以多次调用它,但是如果没有更多行可以从资源中检索,它将始终返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM