使用mysqli fetch放置while循环的位置?

时间:2012-08-24 19:05:01

标签: php mysqli

我正在使用mysqli和php来从数据库中选择一个列,并且还能够将数据插入到数据库中。现在在研究mysqli时,我发现在检查行数是否等于0之前,我需要包含一个while($stmt->fetch()) {

现在因为我需要代码块,一个用于SELECT和其他INSERT,我想知道while fetch循环是否要包围整个代码,或者它假设包裹SELECT代码块和INSERT单独的代码块?

更新:

    $query = "SELECT TeacherAlias FROM Teacher WHERE TeacherAlias = ?";
       // prepare query
       $stmt=$mysqli->prepare($query);
       // You only need to call bind_param once
       $stmt->bind_param("s",$getid);
       // execute query
       $stmt->execute();
       // get result and assign variables (prefix with db)
       $stmt->bind_result($dbTeacherAlias);
       //get number of rows
       $stmt->store_result();
       $numrows = $stmt->num_rows();
       $results = $stmt->fetch_all();


    foreach ($results as $row) {
       if ($numrows == 0){    

           // don't use $mysqli->prepare here
       $query = "SELECT TeacherUsername FROM Teacher WHERE TeacherUsername = ?";
       // prepare query
       $stmt=$mysqli->prepare($query);
       // You only need to call bind_param once
       $stmt->bind_param("s",$getuser);
       // execute query
       $stmt->execute(); 
       // get result and assign variables (prefix with db)
       $stmt->bind_result($dbTeacherUsername);
       //get number of rows
       $stmt->store_result();
       $numrows = $stmt->num_rows();
       $results = $stmt->fetch_all();
    }

foreach ($results as $row) {  
       if ($numrows == 0){
                                               // don't use $mysqli->prepare here
       $query = "SELECT TeacherEmail FROM Teacher WHERE TeacherEmail = ?";
       // prepare query
       $stmt=$mysqli->prepare($query);
       // You only need to call bind_param once
       $stmt->bind_param("s",$getemail);
       // execute query
       $stmt->execute(); 
       // get result and assign variables (prefix with db)
       $stmt->bind_result($dbTeacherEmail);
       //get number of rows
       $stmt->store_result();
       $numrows = $stmt->num_rows();
       $results = $stmt->fetch_all();
}

}
}
}

2 个答案:

答案 0 :(得分:0)

尝试mysqli::fetch_all(),它返回一个关联数组:

$results = $stmt->fetch_all();

foreach ($results as $row) {
    // do something...
}

答案 1 :(得分:-2)

// if no results found it will return either empty array or null (not sure, check it)
$results = $stmt->fetch_all();

// if $results is an empty array it will not enter the loop
foreach($results as $row) {
    if ($numrows == 0){   // this is never reached if results no results were found