Soujirou
Soujirou

Reputation: 109

trying to put an mysql result into a string

I'm trying to put an mysql query result into an string I tried to find an answer but all the similar posts were getting subquery answers which is not what I'm trying to do.

for example

    +----------------------------------+
    |            Fruits_tbl            |
    +----+---------+---------+---------+
    | ID |  Fruit  |  Color  |  Number |
    +----+---------+---------+---------+
    |  1 |  Orange |  Orange |    3    |
    |  2 |  Apple  |  Red    |    5    |
    +----+---------+---------+---------+



    $sql = "select Fruits,Color,Number from Fruits_tbl where ID = 2";
    $result = $pdo->query($sql);
    $row = $result->fetch();
    print_r($row);

This will give me something like
Array([0]=>"Apple", [1]=>"Red", [2]=>"5", [Fruit]=>"Apple", [Color]=>"Red", [Number]=>"5")

implode will give me 2 of each
I want just need a string = "Apple, Red, 5"

what I currently have is

$string = $row['Fruit'].", ".$row['Color'].", ".$row['Number']

As you can see that's rather tedious.
Is there something like implode but only return the index array or something?

Upvotes: 0

Views: 868

Answers (2)

ernie
ernie

Reputation: 6356

You can modify your fetch to get just an associative array:

$row = $result->fetch(PDO::FETCH_ASSOC);

Or, you can get a list:

$row = $result->fetch(PDO::FETCH_NUM);

Either of those could be imploded for single values, and would not contain the overhead that an array_unique() would.

Upvotes: 2

wesside
wesside

Reputation: 5740

$row[Fruit].", ".$row[Color] needs to be $row['Fruit'].", ".$row['Color']

I misunderstood what you were trying to do.

use array_unique() and implode them.

$string = rtrim(implode(',', array_unique($your_array)),',');

Upvotes: 1

Related Questions