Why does PHP jQuery Ajax give execute error?
I'm trying to delete PHP post using jQuery Ajax but for some reason i'm getting 2 different types of errors.
console.log shows following:
Warning PDO::prepare() expects parameter 1 to be string, object given in ajax_functions.php on line 41
Fatal error Uncaught Error: Call to a member function execute() on bool in ajax_functions.php:43
Does anyone know what causes this?
SCRIPT.JS
$('.post-remove-btn').on('click', function(e) {
e.preventDefault();
var entered_name = $('.name-input').val();
$.ajax({
method: "POST",
url: 'functions/ajax_functions.php',
data: { table1: table, tableNr1: tableNr, 'action': 'remove' },
success: function(data) {
if(data){
console.log(data);
}else{
alert('error');
}
},
error: function(requestObject, error, errorThrow) {
alert('error');
}
});
});
AJAX_FUNCTIONS.PHP
<?php
include("../database.php");
// AJAX
if( isset($_POST['action']) ) {
if($_POST['action'] == 'remove'){
$table1 = $_POST['table1'];
$tableNr1 = $_POST['tableNr1'];
if($table1 == 'post'){
$sql = $pdo->query('DELETE FROM posts WHERE id = ' . $tableNr1);
$stmt2 = $pdo->prepare($sql); // PDO::prepare() expects parameter 1 to be string
$result = $stmt2->execute(); // Uncaught Error: Call to a member function execute() on bool
if($result==true){
echo 'post deleted';
}
}elseif ($table1 == 'thread') {
echo 'thread';
}
}
}
?>
Answer
Solution:
You already executed the query with $pdo->query(...)
. You can't use the result as the argument to $pdo->prepare()
-- that's supposed to take a SQL string as an argument.
You should just use prepare()
, and use a parameter to prevent SQL injection.
if($table1 == 'post'){
$stmt2 = $pdo->prepare('DELETE FROM posts WHERE id = :number');
$result = $stmt2->execute([':number' => $tableNr1]);
if($result){
echo 'post deleted';
}
} elseif ($table1 == 'thread') {
echo 'thread';
}
Source