无法使用PDO插入MySQL数据库....没有错误 [英] Cannot insert into MySQL database using PDO....No errors

查看:88
本文介绍了无法使用PDO插入MySQL数据库....没有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我没有收到任何错误,但是每当我检查数据库是否已插入行时,表都是空的.

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.

这是我上课的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

我发现了问题所在.问题出在数据数组上.如果在调用insert()函数时使用$ data ['first_name'],它将失败,但是如果我将所有这些$ data []值替换为硬代码值,它将起作用,因此问题出在$ data []

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[]

我创建了一个POST变量数组

I create an array of POST variables

// 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'];

这将传递给创建函数

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
   ));

这是它插入的地方

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();
}

推荐答案

尝试一下,

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

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

这篇关于无法使用PDO插入MySQL数据库....没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆