Check if list of identifiers exists in MySQL and PHP

What is the most efficient way to MySQLand PHPcheck if there is a list of all identifiers? I want the result of returning the function to truebe if all exists , otherwise false.

I thought:

  $ids = array(2233, 5545, 9478, 5343, 3545);
  do_all_groups_exist($ids);

  function do_all_groups_exist(array $ids = array()) {
      if(empty($ids)) {
          return true;
      }

      $SQL = "SELECT count(`id`) as count
                FROM groups
               WHERE `id` IN (" . implode(',', $ids) . ")";

      ...

      $row = mysqli_fetch_object($result);
      return (intval($row->count) === count($ids)) ? true : false;
 }

Is there a better way?

+4
source share
1 answer

You can get the result in the sql statement itself

$countids= count($ids);

     $sql= "SELECT CASE WHEN (
                SELECT count(id) as cnt
                FROM groups
                WHERE id IN (" . implode(',', $ids) . ") )=$countids

            THEN 'true'
            ELSE 'false'  END as result"
    ...

$row=mysqli_fetch_array($result);
    echo $row['result'];

You will get the result on behalf of coloumn 'result'

It will return true only when all identifiers exist in the table.

+3
source

Source: https://habr.com/ru/post/1530888/


All Articles