简体   繁体   中英

PDO Not Inserting Into Database

Hopefully someone will be able to help me because I've been banging my head against the wall all night trying to solve this little problem.

I want to insert data into a database using PDO (which I am admittedly not the most knowledgeable about). I am using a statement that I have used many times in the past, but for some reason this time it's not working. The statement is as follows:

$userID = "Johnny5"; 
$sql = "INSERT INTO user_info(user_id) VALUES(:user-id)";
         if($stmt = $this->_db->prepare($sql)) 
         {
            $stmt->bindParam(":user-id", $userID, PDO::PARAM_STR);
            $stmt->execute();
            $stmt->closeCursor();
            return TRUE;
         } else {
            return FALSE;
         }

But unfortunately this is always returning TRUE without ever entering anything into my database. I have tried every combination changes to the statement that I could think of, but I am still at a loss.

I hope someone out there can point out a really simple error that I have made.

Also, placing single quote marks around the parameter :user-id in the $sql string is the only way that I can get anything to appear into the database, but that obviously doesn't enter in any actual data into the database.

EDIT I have also changed the PDO parameter types from PDO::PARAM_STR to PDO::PARAM_INT but have still had no luck.

After further investigation, execute() is returning FALSE .

Solution Thanks to everyone for their guidance. @Nabeel was correct in saying not to use placeholders in PDO parameters.

Don't use dashes in your SQL statements.

Make this:

:user-id

as this:

:userid

$userId is a string in this code, yet you say it's in int by defining PDO::PARAM_INT . Try replacing it with PDO::PARAM_STRING or try setting $userId to a number(1 for example)

If something fails, then there most certainly was an error. First you need to find out which statement fails by checking their return values (always read about every command you use in the PHP Manual first).

If you've located which command failed, use PDOStatement->errorInfo to find out more about the concrete error.

That information should help you to solve your issue.

Update: And if you want to deal with Exceptions (as Pekka suggested): How to squeeze error message out of PDO?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM