douren6874 2014-01-28 18:23
浏览 42
已采纳

在一个查询中插入多个数据库行

I know this sounds like a duplicate, but I'm not looking to add multiple rows with a single query, I already have that working. The problem is that I need to only insert ONE row.

I have two pieces of code performing these actions. The first one - on the registration page:

$user = DB::getInstance()->insert('users', array(
    'username' => 'Sam',
    'password' => 'password',
    'salt' => 'salt'

));

and then a the what actually performs the query in a separate php class:

public function insert($table, $fields = array()) {

    $keys = array_keys($fields);

    $values = '';

    $x = 1;



    foreach($fields as $field) {
        $values .= "?";
        if($x < count($fields)) {
            $values .= ', ';
        }
        $x++;
    }

    $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
    if(!$this->query($sql, $fields)->error()) {
        return true;
    }
    return false;
}public function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }

        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }

    return $this;
}

Quite a bit there, but I just wanted to include everything. This is currently working, it enters records into my database, the only problem is that it enters 2 each time.

HERES A SCREENSHHOT OF MY DATABASE:

enter image description here

As you can see from the ID's I've been going over this code for a while now. I have a feeling something terrifically small is throwing it off but I just can't seem to find it and need help from a fresh pair of eyes.

  • 写回答

1条回答 默认 最新

  • dongpu3347 2014-01-30 19:28
    关注

    Fixed it. I'm running this on Wordpress and the first bit of code I had running the the header.php file. Turns out that gets run twice on the page at some point and I simply needed to include the code in a "Page" instead. (but then of course php doesn't want to run on wordpress pages so i needed to use the exec php plugin) but at any rate it's fixed. Thanks

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)