Robert Robert - 4 months ago 21
MySQL Question

PDO UPDATE query not working

The code in question is like this:

if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_POST['id'])) {
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
}
if (empty($title) or empty($content) or empty($id)) {
$error = 'All fields are required!';
} else {

try {

$query = $pdo->prepare("UPDATE articles SET article_title = ?, article_content = ? WHERE article_id = ? ");


$query->bindValue(1, 'title');
$query->bindValue(2, 'content');
$query->bindValue(3, 'id');

$query->execute();

header('Location: index.php'); } catch (PDOException $e) {
print_r($e->errorInfo);
die(); } } }


It gives me no error whatsoever and the table does not update.

P.S. I am quite new to PHP in general so please bear with me if my errors are somewhat trivial, I just don't have anyone else to ask.

Answer

If you are new to PHP then I would suggest you try an alternative way of executing queries with placeholders (?) since it is much simpler.

First set up your connection.

try {
  # First let us connect to our database 
  $db = new \PDO("mysql:host=localhost;dbname=xx;charset=utf8", "xx", "xx", []); 
 } catch(\PDOException $e){
   echo "Error connecting to mysql: ". $e->getMessage();
 }

# And pass optional (but important) PDO attributes
$db->setAttribute(
   PDO::ATTR_EMULATE_PREPARES => false, 
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
 ); 

Now call prepare/execute methods like:

$stmt = $db->prepare("
        UPDATE articles 
        SET article_title = ?, article_content = ? 
        WHERE article_id = ?
 ");

 $stmt->execute(array($article_title, $article_content,$article_id));

 if($stmt->rowCount()) {
   echo 'success';
 } else {
   echo 'update failed';
 }