user2735400
user2735400

Reputation: 13

MySQL query to select specific data

I would like to display the data that belongs to any of my users when they login to the site, as well as the name of each table (they completed offers on them).

This is the code I used, but when I add it it's not working.

$result = mysql_query('SELECT *,\'tbl1\' AS tablename FROM (SELECT * FROM  table1 WHERE user_id='$user_id') as tbl1 UNION SELECT *,\'tbl2\' AS tablename FROM (SELECT * FROM table1 WHERE user_id='$user_id') as tbl2'. ' ORDER BY `date` DESC');

while($sdata = mysql_fetch_array($result)){
  echo $sdata['date'];
  echo $sdata['tablename'];
  echo $sdata['user_reward'];
}

Where did I make a mistake?

Upvotes: 0

Views: 1120

Answers (1)

halfer
halfer

Reputation: 20430

You are missing the concatenation operators here, around $user_id:

$result = mysql_query(
    'SELECT *,\'tbl1\' AS tablename FROM (
        SELECT * FROM  table1 WHERE user_id=' . $user_id . '
     ) as tbl1
     UNION
     SELECT *,\'tbl2\' AS tablename FROM (
        SELECT * FROM table1 WHERE user_id=' . $user_id . '
     ) as tbl2' . ' ORDER BY `date` DESC'
);

I've wrapped the call for more clarity - I suggest you do the same in your own code. I'd be inclined to use " marks here instead, so you don't need to escape apostrophes.

The ORDER BY clause seems to be redundantly concatenated as well - remove the dot and add this part of the query to the as tbl2 part.

Here's how I would do it:

$sql = "
    SELECT *, 'tbl1' AS tablename FROM (
        SELECT * FROM  table1 WHERE user_id={$user_id}
     ) as tbl1
     UNION
     SELECT *, 'tbl2' AS tablename FROM (
        SELECT * FROM table1 WHERE user_id={$user_id}
     ) as tbl2
     ORDER BY `date` DESC
";
$result = mysql_query($sql);

Make sure that $user_id is properly escaped or cast, to avoid security problems. Also, this database library is no longer recommended, and will be removed in a future version of PHP. It would be better to move to PDO or mysqli, and use parameterisation.

Finally, it does rather look like the query itself is rather cumbersome - it looks like it could be simplified. Perhaps ask a separate question on that?

Upvotes: 1

Related Questions