Answer the question
In order to leave comments, you need to log in
PHP+SQL. How to delete an entry from the database?
There is a simple database with words. The page has a form: input-text "word" and select "dictionary". It is necessary, by clicking on the "delete" button, to delete the word typed by the user, provided that the user has selected a dictionary in which this word exists.
The form data is sent to a php file, where the following code is:
session_start();
require('../connection1.php');
header('Content-Type: text/html; charset=utf8');
if (isset($_POST['word']) && isset($_POST['vocabulary'])){
$word = $_POST['word'];
$vocabulary = $_POST['vocabulary'];
$stmt = $connection->prepare("SELECT `id` FROM `words` WHERE `word` = ?");
$stmt->bind_param("i", $word);
$stmt->execute();
$result1 = $stmt->get_result();
$row = mysqli_fetch_array($result1);
$stmt = $connection->prepare("SELECT `id` FROM `words` WHERE `vocabulary` = ?");
$stmt->bind_param("i", $vocabulary);
$stmt->execute();
$result2 = $stmt->get_result();
$id = mysqli_fetch_array($result2);
if ($row === $id){
$query = "DELETE FROM `words` WHERE `words`.`id` = '$row'";
$result = mysqli_query($connection,$query) or die("Ошибка: ".mysqli_error($connection));
if($result){
$_SESSION['smsq'] = "Слово удалено!";
}else {
$_SESSION['fsmsq'] = "Ошибка!";
}
} else {
$_SESSION['fsmsq'] = "Ошибка!";
}
}
header('Location: ../edit-voc.php')
Answer the question
In order to leave comments, you need to log in
Well done for using prepared expressions, but it's too bad not to finish. Prepared expressions must be used for ALL queries involving variables.
Plus, using the $row array in the query does not make the slightest sense.
Also, I'm not sure if word should be bound with type i and not s.
And of course it's all done in one query.
if (isset($_POST['word'], $_POST['vocabulary'])){
$word = $_POST['word'];
$vocabulary = $_POST['vocabulary'];
$query = "DELETE FROM `words` WHERE `word` =? and `vocabulary` = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("ss", $word, $vocabulary);
$stmt->execute();
if($stmt->affected_rows){
$_SESSION['smsq'] = "Слово удалено!";
} else {
$_SESSION['fsmsq'] = "Ошибка!";
}
}
header('Location: ../edit-voc.php');
or die("Ошибка: ".mysqli_error($connection));
u Instead, you need to write once in the file with the connectionmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question