0
votes

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
    }
}
1
wrap the if statement around the execute() statement.Rotimi
vote to close as typoRotimi
You are checking the wrong condition. if ($query) evaluates $query as TRUE because $this->conn->prepare($sql) succeeded and returned an object (which is never FALSE). You should check the value returned by $query->execute().axiac
@AkintundeOlawale Thank you!Jumana Alhaddad
@axiac Thank you!Jumana Alhaddad

1 Answers

4
votes

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
}