Jumana Alhaddad
Jumana Alhaddad

Reputation: 285

PHP return success even when no record is inserted in database

I am using this php code to insert new record in database. The problem is that if ($query) sometimes returns true and when I check the table, there is no new record. Why is it not inserting the record? and why is it returning true when it should return false in case of failing?

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
    }
}

Upvotes: 0

Views: 700

Answers (1)

mkasberg
mkasberg

Reputation: 17352

You need to check the return value of execute:

$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
}

Upvotes: 4

Related Questions