Reputation: 315
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
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
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
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
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
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