我正在使用这个PHP代码在数据库中插入新记录。问题是if ($query)
有时返回 true ,当我检查表时,没有新记录。为什么不插入记录?如果在失败的情况下应该返回false,为什么它返回true?
public function insertUserMileage($alias, $address, $distance, $city,
$latitude, $longitude, $id) {
$sql = 'INSERT INTO user_mileage (user_id, alias, address, distance,
city, lat, lng) VALUES (:id, :alias, :address, :distance, :city,
:latitude, :longitude)';
$query = $this->conn->prepare($sql);
$query->execute(array(':id' => $id, ':alias' => $alias,
':address' => $address, ':distance' => $distance, ':city' => $city,
':latitude' => $latitude, ':longitude' => $longitude));
if ($query) {
return true; // Insert success
} else {
return false; // Insert fail
}
}
答案 0 :(得分:4)
您需要检查执行的返回值:
$result = $query->execute(array(':id' => $id, ':alias' => $alias,
':address' => $address, ':distance' => $distance, ':city' => $city,
':latitude' => $latitude, ':longitude' => $longitude));
if ($result) {
return true; // Insert success
} else {
return false; // Insert fail
}