简体   繁体   中英

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM