John Davidson

javascript - Managing more than two parameters in a prepared update statement in PHP

0 comments
Message:


This first example works fine:


$.ajax({
method: "POST",
url: "test.php",
data: { title: title, authors: authors},
}).done(function( data ) {
alert(data);
});

And in test.php:


$sql='UPDATE books SET title = ?, authors = ? WHERE book_id = 750';
$title = $_POST['title'];
$authors = $_POST['authors'];

$stmt = $conn->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param('ss',$title,$authors);

However, it doesn't work when I add an extra parameter in both pieces of code eg:


$.ajax({
method: "POST",
url: "test.php",
data: { title: title, authors: authors, subtitle:subtitle},
}).done(function( data ) {
alert(data);
});

In test.php:


$sql='UPDATE books SET title = ?, authors = ?, subtitle = ? WHERE book_id = 750';
$title = $_POST['title'];
$authors = $_POST['authors'];
$subtitle = $_POST['subtitle'];


$stmt = $conn->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
$stmt->bind_param('sss',$title,$authors,$subtitle);

It’s virtually the same code except for the sql statement and the bind parameters so I imagine the problem is there. I can’t find any examples in books or on the internet of more than 2 parameters in the sql statement and I have tried without commas, all with commas, with double speechmarks, with AND –and none of them are working. This is not a real application, by the way - It’s a learning project.



My Answer:
"POST", url: "update.php", data: { id: id, name: name, age: age } });

In the update.php file:

$id = $_POST['id']; $name = $_POST['name']; $age = $_POST['age'];

$sql = "UPDATE table SET name = :name, age = :age WHERE id = :id"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':id', $id); $stmt->bindParam(':name', $name); $stmt->bindParam(':age', $age); $stmt->execute();

This code snippet shows how to manage more than two parameters in a prepared update statement in PHP using AJAX and PDO.

If you have more than two parameters to update in a database table, you can simply add them to the data object in the AJAX request and then retrieve them in the update.php file using $_POST.

In the update.php file, you can then bind each parameter to the prepared statement using bindParam and execute the statement.

This approach allows you to easily manage multiple parameters in a prepared update statement in PHP.

Rate this post

3 of 5 based on 6018 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us