F
F
fapchat2021-10-20 20:22:19
PHP
fapchat, 2021-10-20 20:22:19

Why sql query in php is not working correctly?

617050462c1fc469567239.pngIn the mysql table, if you enter the command

SELECT * FROM users WHERE email = 'hhh' OR phone = "+380714293848";
for example, it will be an empty list, however, through the php code, for some reason, the condition if ($stmt->fetch())works for me in any case, if a phone number corresponding to my regular expression was entered. Those. even if there is no number in the table, the user still receives a message:
You have already applied

There is no such problem with email, and only if it is in the table, then the user will receive a message:
You have already applied


Here is the code
if(isset($_POST['name0']) && isset($_POST['email0']) && isset($_POST['phone0']))
   {

    $name = $_POST['name0'];
    $email = $_POST['email0'];
    $phone = $_POST['phone0'];
     if((mb_strlen($name) > 1 && !ctype_digit($name) && preg_match('/^((([0-9A-Za-z]{1}[-0-9A-z\.]{1,}[0-9A-Za-z]{1})|([0-9А-Яа-я]{1}[-0-9А-я\.]{1,}[0-9А-Яа-я]{1}))@([-A-Za-z]{1,}\.){1,2}[-A-Za-z]{2,})$/u', $email) || preg_match('/((8|\+7)-?)?\(?\d{3,5}\)?-?\d{1}-?\d{1}-?\d{1}-?\d{1}-?\d{1}((-?\d{1})?-?\d{1})?/', $phone)))
       {

        $stmt = $connection->prepare("SELECT * FROM users WHERE email = ? OR phone = ?");
        $stmt->bind_param("ss", $email, $phone); 
        $stmt->execute();    
        if ($stmt->fetch()) 
        {  
          ?>
        <script>
            Swal.fire({text: 'Вы уже оставили заявку',
            confirmButtonColor: '#e31e35'})
        </script>        
        <?php
            $stmt->close();
        }   
//......

PS I know that for the name in a good way it is also worth writing a regular expression, and not doing everything my way...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
fapchat, 2021-11-02
@fapchat

I had to split the request.

SELECT * FROM users WHERE email = 'hhh' OR phone = "+380714293848";
на несколько(сам запрос я оставил, зато добавил ещё несколько, чтобы решить свою проблему), чтобы при указании лишь телефона, без имайла, не получалось так, что все поля, в которых имейл пуст, будут соответствовать запросу
SELECT * FROM users WHERE email = 'hhh' OR phone = "+380714293848";

B
bitwheeze, 2021-10-20
@bitwheeze

В SQL только одиночные кавычки для строковых значений используются. В двойные только идентификаторы берутся. По этому phone = "+380714293848" работать не будет.

S
Slava Rozhnev, 2021-10-20
@rozhnev Куратор тега PHP

В контексте mysqli Вам следует использовать $stmt->store_result(); и после $stmt->num_rows()

$stmt = $connection->prepare(
    "SELECT * FROM users WHERE email = ? OR phone = ?"
);
$stmt->bind_param("ss", $email, $phone);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows() > 0) {
    echo "Вы уже оставили заявку";
} else {
  echo "Новая заявка";
}

Share PHP code online
или объявить таблицу с уникальными ключами и обрабатывать исключения:
CREATE TABLE users (
  email varchar(255), 
  phone varchar(255), 
  UNIQUE KEY (email), 
  UNIQUE KEY (phone)
);

$stmt = $connection->prepare(
    "INSERT INTO users (email, phone) VALUES (?, ?)"
);
$stmt->bind_param("ss", $email, $phone);

try {
  $stmt->execute();
} catch (Exception $e) {
    die("Вы уже оставили заявку");
  
}

echo "Заявка сохранена в системе";

PHP fiddle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question