Store and iterate over result of query in mysqli

前端 未结 2 435
南笙
南笙 2020-12-18 14:25

This is my simple query in php, using mysqli object oriented style:

$query = \"SELECT name FROM usertable WHERE id = ?\";
$stmt = $mysqli->prepare($query)         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-18 14:47

    mysqli_stmt::store_result return a boolean. According to the doc it should be something like:

    $stmt->execute();
    $stmt->store_result();
    
    $stmt->bind_result($name);
    
    while($stmt->fetch()){
        //echo $name." ";
        // try another statement
        $query = "INSERT INTO usertable ...";
        $stmt2 = $mysqli->prepare($query);
        ...
    }
    
    $stmt->free_result();
    $stmt->close();
    

    If this doesn't work you can fetch all rows first into an array and then looping that array again:

    $stmt->execute();
    $stmt->bind_result($name);
    $names = array();
    while($stmt->fetch()){
        $names[] = $name;
    }
    $stmt->free_result();
    $stmt->close();
    
    foreach($names as $name) {
        $query = "INSERT INTO usertable ...";
        $stmt = $mysqli->prepare($query);
        ...
    }
    

提交回复
热议问题