Answer the question
In order to leave comments, you need to log in
Why sql query in php is not working correctly?
In 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
You have already applied
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();
}
//......
Answer the question
In order to leave comments, you need to log in
I had to split the request.
SELECT * FROM users WHERE email = 'hhh' OR phone = "+380714293848";
на несколько(сам запрос я оставил, зато добавил ещё несколько, чтобы решить свою проблему), чтобы при указании лишь телефона, без имайла, не получалось так, что все поля, в которых имейл пуст, будут соответствовать запросу SELECT * FROM users WHERE email = 'hhh' OR phone = "+380714293848";
В SQL только одиночные кавычки для строковых значений используются. В двойные только идентификаторы берутся. По этому phone = "+380714293848"
работать не будет.
В контексте 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 "Новая заявка";
}
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 "Заявка сохранена в системе";
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question