开发者

Using array in php query?

开发者 https://www.devze.com 2023-03-20 13:34 出处:网络
i want to obtain number of rows in query using mysql_num_rows.the query itself contains 2 arrays. i want to store the number in array. Here\'s my code

i want to obtain number of rows in query using mysql_num_rows.the query itself contains 2 arrays. i want to store the number in array. Here's my code

  $antecedent=array();

for($i=0;$i<=$index;$i++){
    if(isset($period[$i])|| isset($gpa[$i]) || isset($antecedent[$i])){
  $queryAntecedent=mysql_query("SELECT * FROM mytable WHERE  study_period='$period[$i]' AND ipk='$gpa[$i]'") or die (mysql_error());    

        $antecedent[$i]=mysql_num_rows($queryAntecedent);
   开发者_开发知识库     }//endif
}//endfor

print_r ($antecedent);

when i only used 1 array inside query, the code works. on the other hand, when i put 2 arrays in it..the code doesn't work(all element in array antecedent contain 0). How to slve this? is it no way using 2 arrays in query? Thank you


use { } in the interpolation or concat:

This:

"SELECT * FROM mytable WHERE  study_period='{$period[$i]}' AND ipk='{$gpa[$i]}'"

Or This:

"SELECT * FROM mytable WHERE  study_period='" . $period[$i] . "' AND ipk='" . $gpa[$i]} . "'"

An even better solution is to use PDO or something similar which will allow you to use placeholders and prepared queries. Placeholders help prevent SQL Injection which this query could be vulnerable to. And prepared queries will give you much better performance especially in a loop like you have here.


If you're not getting a mysql error when the query runs, then your query is simply returning no rows. Try building the query separately and store it in a variable, so you can view what you've built:

$sql = "SELECT * FROM mytable WHERE  study_period='$period[$i]' AND ipk='$gpa[$i]'";
$queryAntecedent=mysql_query($sql) or die (mysql_error());
echo $sql;

Note that you're doing an || (or) in your main if() statement. This will will let your query go ahead even if only ONE of your arrays have values. You'd need to change it to && (and) comparison instead, which requires that ALL the arrays have values available.

For instance, if $gpa[$i] happens to be empty, then your query becomes

 SELECT * ... AND ipk='';

which is probably NOT what you want.


If you just want count (number of rows) you should do it like this...

$sql = mysql_query("SELECT COUNT(*) AS count FROM mytable WHERE study_period = '$period[$i]' AND ipk= '$gpa[$i]'") or die (mysql_error());    
$sql = mysql_fetch_assoc($sql);
$antecedent[$i]= $sql["count"];
0

精彩评论

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