Store and iterate over result of query in mysqli

前端 未结 2 419
南笙
南笙 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);
        ...
    }
    
    0 讨论(0)
  • 2020-12-18 14:49

    I have solved the problem:

    $query = "SELECT name FROM usertable WHERE id = ?";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param('i', $id);
    $id= $_GET['id'];
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->free_result();
    $stmt->close();
    
    while ($row = $result->fetch_array(MYSQLI_NUM)) 
    {
        echo $row[0]." ";
    }
    

    Simply using get_result() and fetch_array()

    0 讨论(0)
提交回复
热议问题