Corey Hart
Corey Hart

Reputation: 193

How do I make execute with PDO output a string rather than a single-element array?

I want to select a field in my mysql database containing values separated by commas (let´s say it´s "dd,bb,ee"), so that these can be exploded and turned into an array. However, if trying to do this:

$sql = $conn->prepare("SELECT contacts FROM Users WHERE username = ?");
$sql->execute($usernametmp);
$oldcontacts = $sql->fetch(PDO::FETCH_COLUMN);

I get this error:

Warning: PDOStatement::execute() expects parameter 1 to be array, string 
given in /.../.../.../.../.../....php

on the execute line, whereas if I do the following:

$sql = $conn->prepare("SELECT contacts FROM Users WHERE username = ?");
$sql->execute(array($usernametmp));
$oldcontacts = $sql->fetch(PDO::FETCH_COLUMN);

it works, but with the db entry coming out as one array element containing "dd,bb,ee", where it´ll need to be a string in order for me to use explode on it with the comma as a delimiter.

Any idea how to fix this?

Upvotes: 0

Views: 501

Answers (1)

spencer7593
spencer7593

Reputation: 108430

I believe the PDO fetch function returns an array, not a scalar, even if the row contains a single column.

(I'm not at all familiar with the PDO::FETCH_COLUMN style with the fetch function. Is that documented somewhere? I think that style can be used with the fetchAll function. But that will still return an array.)

The PDO fetchColumn function will return a scalar, rather than an array.

Reference: http://php.net/manual/en/pdostatement.fetchcolumn.php


(And passing bind parameters into the execute is separate unrelated issue.)

Upvotes: 2

Related Questions