0

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
1
  • 2
    Table and Column names cannot be replaced by parameters in PDO. Commented Nov 28, 2015 at 9:37

5 Answers 5

1

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

$phpvar = '';
while($data = $q->fetch()){
    $phpvar .= "$data[names], ";
}
echo $phpvar;
Sign up to request clarification or add additional context in comments.

1 Comment

AAAAAND we have a winner! This worked like a charm! :D Thanks a million!
0

just declare a empty array and use it like below.

 $phpvar = array();

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

3 Comments

I just get "array" as a result when i try to "echo $phpvar;"
@CitronAutobot use var_dump( $phpvar );
@CitronAutobot if you want it as a string use implode() and for a json object you can use json_encode() .
0

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 );

Comments

0

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, ",");

2 Comments

Thanks, but this doesn't give any results at all. Just a blank screen. What could I be doing wrong?
just Edited the answer .. if you still didn't get the deserved answer . I think your should check the error reporting is turned on or not :-/
0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.