Home > OS >  How do I output 4 random records from the database and store them in 4 different variables?
How do I output 4 random records from the database and store them in 4 different variables?

Time:12-15

I would like to output 4 random records from the database and store them in 4 different variables. I would like to continue working with the variables. How do I get this done?

$stmt = $pdo->prepare("SELECT * FROM carditems WHERE status = ? ORDER BY rand() LIMIT 4 ");
$stmt->execute([1]);

while($row = $stmt->fetch()){
    var_dump($row['idItem']);
}

CodePudding user response:

$stmt = $pdo->prepare("SELECT * FROM carditems WHERE status = ? ORDER BY rand() LIMIT 4 ");
    $stmt->execute([1]);
    $array = [];
    while($row = $stmt->fetch()){
     $array[] = $row['idItem'];
    }
  var_dump($array);

It's not 4 variables, but 4 array elements to be used further in your code

CodePudding user response:

You can do this using PDO method fetchAll() and PHP method list:

$stmt = $pdo->prepare("SELECT * FROM carditems WHERE status = ? ORDER BY rand() LIMIT 4 ");
$stmt->execute([1]);


list($v1, $v2, $v3, $v4) = $stmt->fetchAll();

var_dump($v1, $v2, $v3, $v4);

fetchAll get all records into array, list decomposits array to separate variables. In case when array have less values then list variables count the variables will be NULL

PHP PDO test online

  • Related