2

这是代码片段:

$check = mysql_query("SELECT occurrence_number FROM occurrence WHERE word_id = '$word_id' AND page_id = '$page_id'");

$array_row = mysql_fetch_array($check);
if($array_row['occurrence_number']){
   mysql_query("UPDATE occurrence SET occurrence_number = occurrence_number +1  WHERE word_id = '$word_id'"); 
   print "Updating";
}else{
   mysql_query("INSERT INTO occurrence (word_id,page_id) VALUES ($word_id,$page_id)");
   print "Indexing: $cur_word<br>";
}

我希望查询执行的操作:

如果在 tableoccurrence中存在word_id ='$word_id'和的行page_id = '$page_id',则在向其添加 1 后更新该occurrence_number行的该列。

执行此查询时得到的结果:

代码从不进入if子句。每次我执行代码时,都会生成一个新行word_id,其page_id默认值occurrence_number(设置为0)和 occurrence_id(自动递增和主键)相同。

4

4 回答 4

1

尝试使用is_numeric () 之类的

if(is_numeric($array_row['occurrence_number'])){
     mysql_query("UPDATE occurrence SET occurrence_number = occurrence_number +1  WHERE word_id = '$word_id'"); 
     print "Updating";
}else{
     mysql_query("INSERT INTO occurrence (word_id,page_id) VALUES ($word_id,$page_id)");
     print "Indexing: $cur_word<br>";
}

或者你可以简单地尝试

if($array_row['occurrence_number'] || $array_row['occurrence_number'] == '0'){

最重要的是,如果您尝试使用带有while循环的mysql_fetch_array,它将遍历所有相关记录,否则它将仅返回一条记录

while($array_row = mysql_fetch_array($check)) {
    //Put here the code...if else 
}

并且也不要使用mysql_ * 函数,因为它们已被贬低。相反,您可以使用mysqli _* 或PDO语句

于 2013-06-11T07:12:33.633 回答
1

这是因为 MYSQL 返回多于 1 行。尝试使用mysql_fetch_row而不是mysql_fetch_array

或者只是这样做:

while($my_fetch_var = mysql_fetch_array($check))
{ your if clause }

PS:也尝试检查,你有多少行:

echo count($array_row);
于 2013-06-11T07:14:45.717 回答
0

我会检查是否row存在而不是检查实际值

$check = mysql_query("SELECT occurrence_number FROM occurrence WHERE word_id = '$word_id' AND page_id = '$page_id'");
if($array_row = mysql_fetch_array($check))
{
    mysql_query("UPDATE occurrence SET occurrence_number = occurrence_number +1  WHERE word_id = '$word_id'"); 
   print "Updating";
}else{
   mysql_query("INSERT INTO occurrence (word_id,page_id) VALUES ($word_id,$page_id)");
   print "Indexing: $cur_word<br>";
}

请注意该mysql_*功能已弃用,最好使用mysqliPDO

于 2013-06-11T07:15:25.883 回答
0
if( $array_row['occurrence_number'] == '0' || $array_row['occurrence_number']  ){

while($array_row = mysql_fetch_array($check)) {

mysql_query("UPDATE occurrence SET occurrence_number = occurrence_number +1  WHERE     word_id = '$word_id'"); 
print "Updating";
}
于 2013-06-11T07:50:01.880 回答