Dek Dek
Dek Dek

Reputation: 101

Echo inside mysql statement?

Is it possible to echo inside a MySQL statement?

For example:

SELECT p.ID,p.post_title,p.guid,p.post_name,p.post_status,name,taxonomy, <?php echo "TEXT HERE"?> GROUP_CONCAT(DISTINCT name ORDER BY name DESC SEPARATOR '|') AS 'tags',

Is this possible to get this result {tag1|tag2|tag3} ?

Upvotes: 1

Views: 364

Answers (2)

Ross
Ross

Reputation: 47007

It sounds like this question might be relevant. However this should do what you want:

-- Table structure:
-- post(_id_), tag (_id_, tag), post_tag(post*, tag*)

SELECT post.id,
    CONCAT('{', GROUP_CONCAT(distinct tag.tag order by tag.tag separator '}{'), '}') AS tags
FROM post
JOIN post_tag ON post.id = post_tag.post
JOIN tag ON post_tag.tag = tag.id
GROUP BY post.id

Which returns:

+----+--------+
| id | tags   |
+----+--------+
|  1 | {A}{B} |
|  2 | {B}{C} |
|  3 | {C}    |
+----+--------+

Make sure to include the GROUP BY clause. I did add foreign key references but I'm unsure whether MySQL actually uses them for this.

Upvotes: 1

Joe
Joe

Reputation: 15802

Assuming you're writing this query in PHP to execute in MySQL, you can either enclose the SQL in double quotes, which will cause variables to be parsed:

$sql = " SELECT p.ID ... taxonomy, $someVariable GROUP_CONCAT ... ";

or (preferred IMO) use single quotes and concatenate it in (also makes it easier to clean it inline, as shown here)

$sql = ' SELECT p.ID ... taxonomy, ' . mysql_real_escape_string($someVariable) . ' GROUP_CONCAT ... ';

Upvotes: 0

Related Questions