0

我使用 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();
}

}
}
}
4

2 回答 2

0

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

$results = $stmt->fetch_all();

foreach ($results as $row) {
    // do something...
}
于 2012-08-24T19:15:52.320 回答
-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
于 2012-08-25T00:55:02.037 回答