stkmedia stkmedia - 11 months ago 45
PHP Question

Select id and matching username order?

How do you know if

matches the row of
? Is this the correct way to do this query?

$sql = "SELECT id FROM users WHERE username='$user1',username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$id1 = $row[0];
$id2 = $row[1];

  • can I use
    ORDER BY username='$user1'


As I stated in comments, your syntax is invalid. A WHERE clause uses AND or OR as separators, not commas.

So what you need to do here, is adjust your query and compare them thereafter:

Sidenote: You may need to add extra columns to the SELECT as that may throw you an undefined offset notice. Also make sure that if you have more than 2 rows, your LIMIT of 2 may fail on you.

$sql = "SELECT id FROM users WHERE username='$user1' OR username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$id1 = $row[0];
$id2 = $row[1];

if($user1 == $id1) {

    echo "User 1 is the same ";


if($user2 == $id2) {

    echo "User 2 is the same";



As per your edit:

can I use ORDER BY username='$user1'

No, you need to use ORDER by column_name, and not an "equal to" and a variable.

If your column name is the same as the variable, then that is possible but I won't know that for sure until your db schema / contents are.

The syntax is:

ORDER BY column accepts ASC or DESC depending on the order you want.


If your query has any user intervention/input, you will need to use a prepared statement, since that would leave you open to an SQL injection.