CitronAutobot
CitronAutobot

Reputation: 315

PDO array result as php variable

Is it possible to set a PDO result as a PHP $variable and use it outside the PDO query? Here is what I am trying to do:

SQL database contains:

names:
John
Peter
Allen

My code looks like this:

$conn = new PDO("mysql:host=$host;dbname=$db_name",$username,$password);
$conn->query('SET NAMES UTF8');
$sql = "SELECT * FROM $tbl_name";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);

while($data = $q->fetch()){
$phpvar = "$data[names], ";
}

echo $phpvar;

The result I want from "echo $phpvar;" is:

John, Peter, Allen

Upvotes: 0

Views: 1161

Answers (5)

AbraCadaver
AbraCadaver

Reputation: 78984

Aside from the fact that your query will fail and that you are setting PDO::FETCH_BOTH which is the default and will give you duplicate results in your string, just use implode(). It's also easier to just use fetchAll():

$data = $q->fetchAll(PDO::FETCH_ASSOC);
$phpvar = implode(', ', $data);

Upvotes: 0

Aniruddha Chakraborty
Aniruddha Chakraborty

Reputation: 1867

PDO is throwing an object . So you have to do this on while loop after giving a null value in $phpvar , then you have to use rtrim()

$conn = new PDO("mysql:host=$host;dbname=$db_name",$username,$password);
$conn->query('SET NAMES UTF8');
$sql = "SELECT * FROM $tbl_name";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
$phpvar = '';

while($data = $q->fetchAll()){
$phpvar .= $data->names;
$phpvar .= ',';
}

echo rtrim($phpvar, ",");

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33804

A variation on a theme but as already mentioned, declare the variable that you wish to use later and populate in the loop

$phpvar=array();
while( $rs=$q->fetch() ) $phpvar[]=$rs->names;

print_r( $phpvar );

Upvotes: 0

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9693

just declare a empty array and use it like below.

 $phpvar = array();

    while($data = $q->fetch()){
        array_push($phpvar, $data[names]);
    }

Upvotes: 0

roullie
roullie

Reputation: 2820

declare $phpvar before the loop and concat the values to it.

$phpvar = '';
while($data = $q->fetch()){
    $phpvar .= "$data[names], ";
}
echo $phpvar;

Upvotes: 1

Related Questions