简体   繁体   中英

PHP SELECT * Using Prepared statement then store results in array

Ok so currently if i want to fetch all data from database table and store result in array i do this

$mysqliCon = new mysqli(blah blah);
    $example = $mysqliCon->query("SELECT * FROM `tabl` WHERE `example`='example';");
    $exampleArray = Array();
    while($result = $example->fetch_assoc()){
        $exampleArray[] = $result['exampleData'];
    }

and if i want to access exampleData it will be stored in array $exampleArray , so for example
echo $exampleArray[1];

But my question is how can i do this pretty much the same using prepared statements?

This is actually a good question, thanks to the fact that getting results from a prepared statement in mysqli is a tricky thing.

So, basically you have two possibilities.

In case there is a mysqli_result() function available in your system, you can do like this:

$example = 'example';
$stmt = $mysqli->prepare("SELECT * FROM `tabl` WHERE `example`=?");
$stmt->bind_param("s", $example);
$stmt->execute();
$exampleArray = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

But this function is not guaranteed to be available. In this case forget mysqli and start using PDO instead. Here is your code using PDO

$stmt = $pdo->prepare("SELECT * FROM `tabl` WHERE `example`=?");
$stmt->execute(['example']);
$exampleArray = $stmt->fetchAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM