0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ah, never knew you could fetch like that. Should I be doing fetch like this with normal queries too? like a select * from a multi row table?
1

$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)),','); 

2 Comments

sorry I typed that off my head and left out the quotes
@user1583432 This is somewhat inefficient, as it requires storing twice the data, then uniquing it using array_unique. Modify your fetch, and you don't need to use a second function. In other word it works, but it's pretty hackish, and the code is a bit difficult to read. Order could be a little iffy here too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.