Reputation: 27
I have a some problem here, where I want to update the data in CRUD, the data even adding new(like insert).
Have any idea to solve it? Thanks.
There is my code,
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$address));
Database::disconnect();
header("Location: index.php");
}
}else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM customers WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
Database::disconnect();
}
Upvotes: 0
Views: 127
Reputation: 5570
number of bound variables does not match number of tokens
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$address));
You have four tokens ? there should be four parameters, as of :
$q->execute(array($name,$email,$address,$id));
and pay attention not put header("Location: index.php");
in the same file as index.php, because that will cycle and you will get an error like:
your webhost redirected you too many times
Upvotes: 0
Reputation: 1712
binding id as well in the prepared statement
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$values = array($name,$email,$address);
if($id) {
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$values[] = $id;
} else {
$sql = "INSERT INTO customers (name, email, address)
VALUES (?,?,?)";
}
$q = $pdo->prepare($sql);
$q->execute($values);
Database::disconnect();
header("Location: index.php");
}
}else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM customers WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
Database::disconnect();
}
See line 8 (leave out the **)
edit added a insert query for the case $id is empty based on understanding of a comment
Upvotes: 2