无法使用PDO插入MySQL数据库...没有错误

时间:2022-10-13 12:03:04

I have a problem where I cannot insert anything into a MySQL database using PDO.

我有一个问题,我无法使用PDO将任何内容插入MySQL数据库。

I get no errors but whenever I check the database if the row has been inserted, the table is empty.

我没有错误,但每当我检查数据库时是否已插入行,表格为空。

I know I have a connection to the database as I am able to select but not insert.

我知道我有一个与数据库的连接,因为我能够选择但不能插入。

Here is my class that entends PDO

这是我的班级,他们参加了PDO

class Database extends PDO
{

    public function __construct($DB_TYPE, $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS)
    {
        parent::__construct($DB_TYPE.':host='.$DB_HOST.';dbname='.$DB_NAME, $DB_USER, $DB_PASS);

        //parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTIONS);
    }

    /**
     * select
     * @param string $sql An SQL string
     * @param array $array Paramters to bind
     * @param constant $fetchMode A PDO Fetch mode
     * @return mixed
     */
    public function select($sql, $array = array(), $fetchMode = PDO::FETCH_ASSOC)
    {
        $sth = $this->prepare($sql);
        foreach ($array as $key => $value) {
            $sth->bindValue("$key", $value);
        }

        $sth->execute();
        return $sth->fetchAll($fetchMode);
    }

    /**
     * insert
     * @param string $table A name of table to insert into
     * @param string $data An associative array
     */
    public function insert($table, $data)
    {
        /*ksort($data);

        $fieldNames = implode('`, `', array_keys($data));
        $fieldValues = ':' . implode(', :', array_keys($data));

        $sth = $this->prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)");

        foreach ($data as $key => $value) {
            $sth->bindValue(":$key", $value);
        }*/

        $sth = $this->prepare("INSERT INTO user (`login`, `password`, `role`) VALUES (:login, :password, :role)");

        $sth->bindValue(':login', 'username');
        $sth->bindValue(':password', 'password');
        $sth->bindValue(':role', 'owner');

        $sth->execute();

        /*if ($sth->errorCode() != 0) {

            $arr = $sth->ErrorInfo();
            throw new Exception('SQL failure:'.$arr[0].':'.$arr[1].':'.$arr[2]);
        }*/

        $sth->debugDumpParams();
    }

Here is my table structure (kept it simple for debugging).

这是我的表结构(保持调试简单)。

CREATE TABLE IF NOT EXISTS `user` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `login` varchar(25) NOT NULL,
  `password` varchar(64) NOT NULL,
  `role` enum('default','admin','owner') NOT NULL DEFAULT 'default',
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB

EDIT:

I found out where the problem lies. The problem is with the data array. If I use $data['first_name'] when calling the insert() function, it fails but if I replace all those $data[] values with hard codes values, it works so the problem lies with $data[]

我发现了问题所在。问题出在数据阵列上。如果我在调用insert()函数时使用$ data ['first_name'],它会失败,但是如果我用硬代码值替换所有那些$ data []值,那么问题就在于$ data []

I create an array of POST variables

我创建了一个POST变量数组

// get all the post data from the registration form
$data = array();        
$data['first_name'] = $_POST['first_name'];
$data['last_name'] = $_POST['last_name'];
$data['gender'] = $_POST['gender'];
$data['email'] = $_POST['email'];
$data['interests'] = $_POST['interests'];
$data['username'] = $_POST['username'];
$data['password'] = $_POST['password'];
$data['newsletter'] = $_POST['newsletter'];
$data['terms'] = $_POST['terms'];
$data['captcha'] = $_POST['captcha'];

This gets passed to the create function

这将传递给create函数

public function create($data) {
   $this->db->insert('users', array(
    'first_name' => $data['first_name'],       //this won't work
    'first_name' => 'whatever the name is',    //this will work
    'last_name' => $data['last_name'],
    'email' => $data['email'],
    'username' => $data['username'], 
    'password' => $password,
    'user_salt' => $user_salt,
    'sex' => $data['gender'],
    'interests' => $data['interests'],
    'signup_date' => date('Y-m-d H:i:s'), 
    'verification_code' => $code
   ));

and this is where it gets inserted

这就是插入的地方

public function insert($table, $data)
{
    ksort($data);

    $fieldNames = implode('`, `', array_keys($data));
    $fieldValues = ':' . implode(', :', array_keys($data));

    $sth = $this->prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)");

    foreach ($data as $key => $value) {
        $sth->bindValue(":$key", $value);
    }

    $sth->execute();
}

2 个解决方案

#1


0  

 $fieldValues = implode(':,', array_keys($data));

#2


0  

Try this,

$fieldNames = implode(', ', array_keys($data));
$fieldValues = ':' . implode(', :', array_values($data));

$sth = $this->prepare("INSERT INTO $table ($fieldNames) VALUES ($fieldValues)");

#1


0  

 $fieldValues = implode(':,', array_keys($data));

#2


0  

Try this,

$fieldNames = implode(', ', array_keys($data));
$fieldValues = ':' . implode(', :', array_values($data));

$sth = $this->prepare("INSERT INTO $table ($fieldNames) VALUES ($fieldValues)");