3

How to check multiple times (within foreach) if values from three arrays exists in three mysql columns?

One way SELECT, fetch whole column and create array with the column values. Then (in_array($value_to_check[$i], $whole_mysql_column).

Other way would be multiple SELECT Column FROM Table WHERE Column = ? and ? is $value_to_check[$i]

Suppose both ways uses much resources. Is there better way?

5
  • the latter would be the more efficient. Commented Aug 12, 2013 at 16:33
  • But, if for example 1000 SELECT... not good. Commented Aug 12, 2013 at 16:34
  • yes you completely right. for some range of low numbers it would be better then at some point indeed the former will become better. I don't think there is any other way than the 2 you have put. Commented Aug 12, 2013 at 16:38
  • How are the three arrays you are wanting to check against the three mysql columns created, and where does the data come from? Commented Aug 13, 2013 at 14:14
  • The 3 arrays comes from excel file (php receives data from excel). If you can click on edit below the question, you may see initial long question, where I described all process. Commented Aug 13, 2013 at 15:53

1 Answer 1

2

Why make so much queries to begin with? Why not make a single giant SQL query that uses IN instead, e.g.

$sqlValuesToCheck = '(';
foreach ($value_to_check as $value) {
    $sqlValueToCheck .= "'" . $mysqli->real_escape_string($value) . "',";
}
$sqlValueToCheck = rtrim($sqlValueToCheck, ',') . ')';

$result = $mysqli->query("SELECT `Column` FROM `Table` WHERE `Column` IN {$sqlValueToCheck}");

The above will get all `Table`.`Column` values that are also in the array. You mentioned that you'd like to check 3 columns... depending on how you want to use the result, you could use a UNION or simply list the other columns before the FROM.

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

1 Comment

Will experiment with advice. Thanks

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.