0

I have a simple bit of code:

:ul1 = 0;

$sql = "SELECT word FROM tbl WHERE 1 = 1 AND catid > :ul1 ORDER BY RAND() LIMIT 3";

$stmt1 = $pdo->prepare($sql1);
$stmt1->bindParam(':ul1', $ul1);
$stmt1->execute();
$row1 = $stmt1->fetchAll();

var_dump($row1);

That outputs:

array(3) {
  [0]=>
  array(2) {
    ["word"]=>
    string(8) "arrochar"
    [0]=>
    string(8) "arrochar"
  }
  [1]=>
  array(2) {
    ["word"]=>
    string(7) "cabinet"
    [0]=>
    string(7) "cabinet"
  }
  [2]=>
  array(2) {
    ["word"]=>
    string(10) "doghearted"
    [0]=>
    string(10) "doghearted"
  }
}

I can access an array element via:

$test = $row1[2][0];

I wondered if there is any way I can get a more simple array output - e.g. each array element seems to contain the same thing twice.

Not that it matters - I can still do what I need to do, I was just curious.

1 Answer 1

1

Although you are asking for PDO::FETCH_ASSOC constant (by calling fetchAll(PDO::FETCH_ASSOC) you'll get only single value), yet there is an even more intelligent fetch mode - PDO::FETCH_COLUMN

$ul1 = 0;
$sql = "SELECT word FROM tbl WHERE catid > ? ORDER BY RAND() LIMIT 3";
$stmt = $pdo->prepare($sql);
$stmt->execute([$ul1]);
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);

var_dump($data);

this way you'll get just a simple one-dimensional array which you can address the most natural way:

$test = $data[2];

or iterate over with

foreach ($data as $word)
{
    echo "$word</br>\n";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that - I spent a lot of time on your phpdelusions website when I was starting out with PDO earlier this year. I should have spotted the PDO::FETCH_COLUMN bit on your site as I checked it before posting here. Thanks again.
That is understandable because there is way too much information and nobody can get it all at once :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.