1 AND clients.cancel = 0"; $andLikeFio = $search ? " and (fio like '%" . trim($search) . "%' or phone like '%" . trim($search) . "%' or email like '%" . trim($search) . "%')" : " "; $sqlUnion = " UNION SELECT requisitions.client_id FROM requisitions WHERE ((requisitions.who_work = $idAgent) OR (requisitions.who_work = 0 and requisitions.user_id in (" . implode(',', $userIds) . "))) AND requisitions.deleted <> 1 AND requisitions.cancel = 0"; $rez = mysql_query($sql . $andLikeFio . $sqlUnion); $clientIds = []; while ($client = mysql_fetch_assoc($rez)) { if (!in_array((int)$client['id'], $clientIds)) { $clientIds[] = (int)$client['id']; } } $allCount = count($clientIds); $ot = ($page - 1) * $numberOfRecords; //$all_pages = ceil($allCount / $numberOfRecords); // not used $orderBy = " ORDER BY fio, ID"; $limit = " LIMIT " . $ot . ', ' . $numberOfRecords; $sqlClients = "SELECT id, fio, phone, email FROM clients where id IN (" . implode(',', $clientIds) . ")"; $sqlClientsCount = "SELECT COUNT(id) as cnt FROM clients where id IN (" . implode(',', $clientIds) . ")"; $rez = mysql_query($sqlClients . $andLikeFio . $orderBy . $limit); $rezCount = mysql_query($sqlClientsCount . $andLikeFio); $response = []; $response['items'] = []; $response['total_count'] = mysql_fetch_assoc($rezCount)['cnt']; while ($block = mysql_fetch_assoc($rez)) { // Маскируем контактные данные клиента, если у пользователя включено скрытие mask_client_contacts_inplace($block); $response['items'][] = array( "id" => $block['id'], "text" => $block['fio'] . " (" . $block['email'] . " " . $block['phone'] . ")" ); } echo json_encode($response); exit();