0

I was wondering if you think this is possible: Ok so I have a database storing usernames and I would like to echo the admins which are inside a file called admins.php IF they match the usernames inside the database so far I have got:

admins.php;
$admins = array("username","username2","username3");

and

$users="SELECT username from usrsys";
$query_users=mysql_query($users);
while loop here.

The while loop should hopefully echo the users which matches the admins.php file. I assume I should use something like (inarray()), but I am really not sure.

1
  • Heads up! Future versions of PHP are deprecating and removing the mysql_ family of functions. Now would be a great time to switch to PDO or mysqli. Commented Dec 9, 2012 at 8:38

4 Answers 4

2

You should definitely use IN clause in your SQL to do this. Selecting everything from the table in order to determine in PHP if it contains the user names you're looking for makes no sense and is very wasteful. Can you imagine what would happen if you had a table of 1 million users and you needed to see if two of them were on that list? You would be asking your DBMS to return 1 million rows to PHP so that you can search through each of those names and then determine whether or not any of them are the ones you're looking for. You're asking your DBMS to do a lot of work (send over all the rows in the table), and you're also asking PHP to do a lot of work (store all those rows in memory and compute a match), unnecessarily.

There is a much more efficient and faster solution depending on what you want.

First, if you only need to know that all of those users exist in the table then use SELECT COUNT(username) instead and your database will return a single row with a value for how many rows were found in the table. That way you have an all or nothing approach (if that's what you're looking for). Either there were 3 rows found in the table and 3 elements in the array or there weren't. This also utilizes your table indexes (which you should have properly indexed) and means faster results.

$admins = array("username","username2","username3");
// Make sure you properly escape your data before you put in your SQL
$list = array_map('mysql_real_escape_string', $admins);
// You're going to need to quote the strings as well before they work in your SQL
foreach ($list as $k => $v) $list[$k] = "'$v'";
$list = implode(',', $list);
$users = "SELECT COUNT(username) FROM usrsys WHERE username IN($list)";
$query_users = mysql_query($users);
if (!$query_users) {
    echo "Huston we have a problem! " . mysql_error(); // Basic error handling (DEBUG ONLY)
    exit;
}
if (false === $result = mysql_fetch_row($query_users)) {
    echo "Huston we have a problme! " . mysql_error(); // Basic error handling (DEBUG ONLY)
}
if ($result[0] == count($admins)) {
    echo "All admins found! We have {$result[0]} admins in the table... Mission complete. Returning to base, over...";
}

If you actually do want all the data then remove the COUNT from the SQL and you will simply get all the rows for those users (if any are found).

$admins = array("username","username2","username3");
// Make sure you properly escape your data before you put in your SQL
$list = array_map('mysql_real_escape_string', $admins);
// You're going to need to quote the strings as well before they work in your SQL
foreach ($list as $k => $v) $list[$k] = "'$v'";
$list = implode(',', $list);
$users = "SELECT username FROM usrsys WHERE username IN($list)";
$query_users = mysql_query($users);
if (!$query_users) {
    echo "Huston we have a problem! " . mysql_error(); // Basic error handling (DEBUG ONLY)
    exit;
}
// Loop over the result set
while ($result = mysql_fetch_assoc($query_users)) {
    echo "User name found: {$result['username']}\n";
}

However, I really urge you to reconsider using the old ext/mysql API to interface with your MySQL database in PHP since it is deprecated and has been discouraged from use for quite some time. I would really urge you to start using the new alternative APIs such as PDO or MySQLi and see the guide in the manual for help with choosing an API.

In PDO, for example this process would be quite simple with prepared statements and parameterized queries as you don't have to worry about all this escaping.

There's an example in the PDOStatement::Execute page (Example #5) that shows you just how to do use the IN clause that way with prepared statements... You can then reuse this statement in other places in your code and it offers a performance benefit as well as making it harder for you to inadvertently expose yourself to SQL injection vulnerabilities.

// Connect to your database
$pdo = new PDO("mysql:dbname=mydb;host=127.0.0.1", $username, $password);

// List of admins we want to find in the table
$admins = array("username","username2","username3");

// Create the place holders for your paratmers
$place_holders = implode(',', array_fill(0, count($admins), '?'));

// Create the prepared statement
$sth = $dbh->prepare("SELECT username FROM usrsys WHERE username IN ($place_holders)");

// Execute the statement
$sth->execute($admins);

// Iterate over the result set
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
    echo "We found the user name: {$row['username']}!\n";
}

Your PHP code even looks so much better with PDO :)

Sign up to request clarification or add additional context in comments.

Comments

0

Just include admins.php file and use the next construction in your loop:

while ($row = mysql_fetch_array($users)) {
if (in_array($users[0], $admins))
    echo $users[0];
}

Comments

0

Try this:

<?php
# include admins.php file that holds the admins array
include "admins.php";

# join all values in the admins array using "," as a separator (to use them in the sql statement)
$admins = join(",", $admins);

# execute the query
$result = mysql_query("
    SELECT username
    FROM usrsys
    WHERE username IN ($admins)
");

if ($result) {
    while ($row = mysql_fetch_array($result)) {
        echo $row["username"] . "<br>";
    }
}
?>

Comments

0

If your looking for syntax to pull in only the users from your $admins array then you could use something like:

$users="SELECT username FROM usrsys WHERE username IN ('".join("','",$admins)."')";

Where the php function JOIN will print username,username2,username3. Your resulting MySQL statement will look like:

SELECT username FROM usrsys WHERE username IN ('username','username2','username3')

Alternatively, if your looking to iterate through your $query_vars array and separate your admins from non-admins then you could use something like:

<?php
while($row = mysql_fetch_assoc($query_users)){
    if(in_array($row['username'],$admins)){
        //do admin stuff here
    }else{
        //do NON-admin stuff here
    }
}?>

4 Comments

That join thing looks to be closer to what I was looking for, however when I echo $users and try to use it as a SQL command in phpmyadmin it says unknown column 'username' in 'where clause'
Ah I think I know why, it is because the user is not registered in the database. Edit: actually I tried now with an actual user and it was still the same.
The reason for this is that you must quote the string values in your IN clause just like any string your SQL code. SQL needs you to quote strings just like PHP does.
@SamuelCook Just a few minor notes, use implode not join (join only remains aliased in PHP for BC reasons -- but it is semantically better to use implode in your code as only few old-time PHP4 developers will recognize the name at first sight). Secondly, this is still the wrong approach. There is no escaping being done on the data, there is no check for empty values (if I have an empty array you just returned the whole table), and using in_array is completely unnecessary here. You already know it's in the array (your SQL says so).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.