1

I cannot find solution of such problem. I need that $sql variable shows all values except the specified values as username != $var2 array values.

    $user_data = user_data($session_user_id, 'user_id', 'username', 'blocked_emails');

    $var = $user_data['blocked_emails'];
    $var2 = explode(',', $var);

    $sql = mysqli_query($con1, "SELECT * FROM `test` WHERE `username` != '$var2' ORDER BY user_id");

while ($row2 = mysqli_fetch_array($sql)) {

    $uid = $row2['user_id'];
    $username = $row2['username'];
    }
1
  • 2
    you could try a NOT IN (…) instead of your !=. Commented Mar 10, 2018 at 14:57

2 Answers 2

2

The core question seems to be how the SELECT statement should look like:

SELECT * FROM `test`
  WHERE `username` NOT IN ('[email protected]', '[email protected]', …)
  ORDER BY `user_id`

How to produce this statement in PHP is left as an exercise to the reader. Lajos Arpad's answer gives a good start but it is safer to use a prepared statement ($con1->prepare(…)), so you do not have to worry about apostrophes in values, SQL injection and the like.

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

Comments

0

As Renardo suggested, you need not in, like this:

    $user_data = user_data($session_user_id, 'user_id', 'username', 'blocked_emails');

    $var = $user_data['blocked_emails'];
    $var2 = explode(',', $var);
    for ($index = 0; $index < count($var2); $index++)
        $var2 = "'".$var2[$index]."'";

    $sql = mysqli_query($con1, "SELECT * FROM `test` WHERE `username` not in (".implode(",", $var2).") ORDER BY user_id");

while ($row2 = mysqli_fetch_array($sql)) {

    $uid = $row2['user_id'];
    $username = $row2['username'];
    }

But in this solution we assume that none of the values in $var2 contain apostrophe. You will need to take further measures to sanitize your query, to ensure it will work well with any possible input and protect yourself against SQL injection at the same time.

2 Comments

Don't you need to use [$index] after $var2 in your loop? And expanding $var2 in the SELECT string yields just Array in my test.
@Renardo yes, I need that, forgot to add it. Thanks for pointing that out!

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.