-1

i have a mysql_query that uses union to work with two querys at the same time, like that:

$friends_a = mysql_query("(SELECT * FROM users WHERE id!='$user_q[id]' AND id='$friends_1_q[user_one_id]') UNION ALL (SELECT * FROM users WHERE id!='$user_q[id]' AND id='$friends_1_q[user_two_id]')");` 

and i want to limit this (the two querys at a only limit), what would i do? (i already tried a lot of things that i've found on internet or here). sorry for bad english :D

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Jan 29 '16 at 20:43
  • 2
    Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jan 29 '16 at 20:43
  • 2
    Add a `LIMIT` clause to each query. – Jay Blanchard Jan 29 '16 at 20:43
  • Can you please provide the table definition and some sample data? At first glance it looks like the query can be reduced to `SELECT * FROM users WHERE id IN (...,...) ORDER BY ... LIMIT 1` and the `id!='$user_q[id]'` part might be a flaw on the INSERT part of your script(s) (i.e. it should check whether someone tries to add oneself as a friend) – VolkerK Jan 29 '16 at 20:53

1 Answers1

1

You can wrap your query in parens and reference it as inline view. For example, to return at most five rows:

SELECT v.*
  FROM ( 
         -- original query goes here
       ) v 
 LIMIT 5

Consider adding an ORDER BY on the outer query (before the LIMIT clause) to make the result more deterministic.

Alternatively, ditch the UNION ALL operation entirely, and just write a single query:

SELECT u.*
  FROM users u 
 WHERE u.id != ? 
   AND u.id IN ( ? , ? )
 ORDER BY u.id
 LIMIT 2

Supply the values for the placeholders:

$user_q[id]
$friends_1_q[user_one_id]
$friends_1_q[user_two_id]

Addendum:

The mysql_ functions are deprecated. Use mysqli or PDO for new development. And use prepared statements with bind placeholders.

If that's not possible (for whatever reason), be sure that the values of the variables you include in the SQL text are properly escaped.

spencer7593
  • 106,611
  • 15
  • 112
  • 140