Hi guys, I've no idea why my code isn't worked. I've checked and checked and can't see anything wrong. What possibly I've done wrong? All the variables are not empty. $sql = " INSERT INTO topics( uid, dates, title, content, tag ) VALUES( :id, :date, :title, :content, :tag ) "; try { $statement = $conn->prepare($sql); $statement->execute(array( ":id" => $id, ":date" => $date, ":title" => $title, ":content" => $content, ":tag" => $tag )); header("location: index.php"); } catch(PDOException $e) { echo $e->getMessage(); } Code (markup): It redirects without doing anything. Thanks,
Well, a simple way to check for errors is to change the prepared statement to just the actual variables, and echo out the statement afterwards - then you paste that into phpmyadmin or whatever sql-software you have available, and try running it there. If it works, you have something very wrong with your setup - most likely it won't, and you'll get an idea what went wrong. I've long since decided that the PDO-error message setup is a bit broken, so I don't use it, personally - I've got my own little function returned a slightly more understandable error. However, since you're not getting an error at all, that seems to say that the query isn't broken in any way.
Where are you specifying the data type you are trying to insert into the database? By default, PDOStatement::execute() assumes the data is all string. But it looks like your $id is an int. Is that correct? If it is string, then I see no problem. If it is int, then you may have a problem. And your header() is redirecting because you are failing to check the return value of $statement->execute() so no matter what happens, whether the query fails or not, you will be redirected. You should always check return values. Always.
Look at the PHP documentation to see what return values a function returns. If it returns true on success and false on failure, test for false and if it is false, take another course of action instead of executing your redirect (such as outputting an error message or whatever you want to do). http://php.net/manual/en/pdostatement.execute.php In such a case as this, I prefer to test explicitly for false using the === operator. http://php.net/manual/en/types.comparisons.php
You may have solved your problem, but since you asked us for help, proper forum etiquette demands that you explain to us what the problem was and how you solved it. That way, future visitors to this forum that have the same or similar problem may be able to solve their problem the same way you did.
Sorry, The code above is corrected and works fine. It's the code that I don't show here that caused error. I can't find the error at the time. It fails silently so I decided to ask the forum.