我一直在尝试向 mysql 数据库中插入一个新行,但是 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';
}
------------帕维尔的回答------------
“REPLACE INTO”无效。问题又出现了。
最佳答案
只需使用 REPLACE INTO 而不是 INSERT INTO
$query = $this->db->query("REPLACE INTO `$table` (`$keys`) VALUES('$values')");
关于php - Mysqli查询函数插入重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33259510/