$ c = mysql_num_rows(mysql_query($ q));

Hai*_*ood -1 php mysql

我想知道是否这样

$c = mysql_num_rows(mysql_query("select * from action_6_weekly where code='$code'"));
Run Code Online (Sandbox Code Playgroud)

被认为是有效的PHP?

或者我需要执行以下操作?

$r = mysql_query("select * from action_6_weekly where code='$code'");
$c = mysql_num_rows($r);
Run Code Online (Sandbox Code Playgroud)

这就是我实际在做的事情:

if($entry == '9')
    $c = mysql_num_rows(mysql_query("select * from action_6_5pts where code='$code'")) or die ('MYSQL ERROR: '.mysql_error().' in '.__FILE__.' on '.__LINE__.'.');
elseif($entry == 'a')
    $c = mysql_num_rows(mysql_query("select * from action_6_10pts where code='$code'")) or die ('MYSQL ERROR: '.mysql_error().' in '.__FILE__.' on '.__LINE__.'.');
else
    $c = mysql_num_rows(mysql_query("select * from action_6_weekly where code='$code'")) or die ('MYSQL ERROR: '.mysql_error().' in '.__FILE__.' on '.__LINE__.'.');

if($c > 0) 
    $waiting_for_reply = false;
Run Code Online (Sandbox Code Playgroud)

Jim*_* W. 5

通常最好在单独的行上进行并为其分配变量.

这样您就可以更轻松地处理结果.但要获得行数,如果这就是您要寻找的,那么这将更好,更有效:

$r = mysql_query("select count(id) from action_6_weekly where code='$code'");
$c = mysql_result($r, 0, 0);
Run Code Online (Sandbox Code Playgroud)

其中id是要计数的唯一标识符字段.

编辑:鉴于你不关心有多少行,只是它存在:

$r = mysql_query("select code from action_6_weekly where code='$code' LIMIT 1");
if (mysql_num_rows($r) > 0) {
    // echo it exists!
}
Run Code Online (Sandbox Code Playgroud)


Mch*_*chl 5

它是有效的(毕竟它执行),但是很难看.

更何况


$r = mysql_query("select COUNT(*) AS cnt from action_6_weekly where code='$code'");
$row = mysql_fetch_assoc($r);
$c = $row['cnt'];
可能会减少您的数据库的压力.