【问题标题】:Mysqli query function insert duplicate linesMysqli查询功能插入重复行
【发布时间】:2016-01-20 11:05:09
【问题描述】:

我一直在尝试向 mysql db 插入新行,但 insert(){...} 函数插入了重复行。

我也尝试了几种插入方法,但都不起作用。所有方法都插入了重复行。

我该如何解决这个问题?你有什么想法吗?

感谢您的帮助和建议。

protected $db;

public function __construct() {
    try {
        $this->db = new mysqli('localhost', 'root', '', 'trigger');
        $this->db->set_charset("utf8");

    } catch (mysqli_sql_exception $e) {
        throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
    }
}

public function select($table, $rows = "", $where = "", $return_type = "") {
    if (empty($rows)) {
        $rows = "*";
    }
    if (empty($where)) {
        $where = "";
    } else {
        $where = "where " . $where;
    }

    try {
        $query = $this->db->query("SELECT $rows FROM $table $where");
        if ($return_type == "json") {
            return json_encode($query);
        } else {
            return $query;
        }
    } catch (mysqli_sql_exception $exc) {
        return $exc->getMessage();
    }
}

public function insert($table, $params) {
    $_keyArr = array();
    $_valueArr = array();

    foreach ($params as $key => $value) {
        $_keyArr[] .= $key;
        $_valueArr[] .= $value;
    }

    $keys = implode("`,`", $_keyArr);
    $values = implode("','", $_valueArr);

    $query = $this->db->query("INSERT INTO `$table` (`$keys`) VALUES('$values')");

    try {
        return $query;
    } catch (mysqli_sql_exception $ex) {
        return $ex->getMessage();
    }
}

-------------回答马特--------------

我用以下代码调用:

    if ($this->db->insert("table_name", array("path" => "test", "flow_name" => "test"))) {
        echo 'ok';
    } else {
        echo 'not ok';
    }

-------------回答帕维尔-------------

“替换为”无效。问题又出现了。

【问题讨论】:

  • 请问这个函数是怎么调用的?
  • 这是什么? $_keyArr[] .= $key; $_valueArr[] .= $value; 只使用 [] = 而不是 [] .=
  • 您发布的代码中的任何内容都不会创建重复项。如果使用相同的参数多次调用insert() 函数,则会产生重复。
  • 你的try/catch 区块看起来有点不靠谱!! return $query 不会抛出异常,而 $query = $this->db->query("INSERT INTO `$table` (`$keys`) VALUES('$values')"); 很有可能
  • 如果您的表没有唯一的列集,如果您多次使用相同的测试数据运行,没有什么可以阻止它创建重复的行。 请为相关表格添加表格定义

标签: php mysql mysqli insert duplicates


【解决方案1】:

只需使用 REPLACE INTO 代替 INSERT INTO

$query = $this->db->query("REPLACE INTO `$table` (`$keys`) VALUES('$values')");

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 2013-10-07
    • 2013-10-31
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    相关资源
    最近更新 更多