我正试图使用php为postgres数据库编写一个"INSERT"到网页。这将从用PHP编写的注册表单中输入一些数据。目前我在PHP中有以下代码:
function insert($table, $data)
{
global $db;
if ($table and is_array($data) and !empty($data))
{
$columns = implode(',',array_keys($data));
$values = implode(',', escape($data));
$sql = "INSERT INTO {$table} ($columns) VALUES ($values)";
$q = pg_query($db, $sql) or db_error_out();
$result = pg_query($db, $sql) or db_error_out();
$insert_row = pg_fetch_row($result);
$id = $insert_row[0];
return ($id > 0) ? $id : FALSE;
} else {
return FALSE;
}
}
代码工作,并插入行到postgres DB,但我也得到这个错误:
Warning: pg_query(): Query failed: ERROR: duplicate key value violates unique constraint "index_clients_on_first_name_and_last_name_and_phone_and_email"
DETAIL: Key (first_name, last_name, phone, email)=(test, test, 5461230, test@mail.com) already exists. in C:'xampp'htdocs'webpage_dev'system'database.php on line 165
第165行是$结果,我知道$db工作正确,所以我假设$sql是错误的。
我的问题是如何摆脱这个错误,并帮助与INSERT.
您执行了两次查询:
...
$q = pg_query($db, $sql) or db_error_out();
$result = pg_query($db, $sql) or db_error_out();
...
$q成功,然后$result失败,因为数据已经在数据库中。