简体   繁体   中英

How to handle query errors in Zend?

I have a simple question.

I am working on Zend framework 2. I am trying to make an AJAX call to fetch all booking data from table booking by passing the booking_id. Trouble is, the query is failing for reasons unknown. The actual query is complex and its working when I replace $booking_id with an actual booking_id like '22432'. Hence, I believe that the query is fine, there is some other issue.

But I don't know how to fetch the query errors/exceptions in an Ajax call. Can someone help me with this?

Javascript:

$.post("dashboard/getBookingDataByBookingId", {
        booking_id: bookingId,
    },
    function(data){
        if(data.response == true) {
         alert(data);
        } else {
         alert('failed');
        }
    }, 'json');

Controller

public function getBookingDataByBookingIdAction()
{
  $request = $this->getRequest();
  $response = $this->getResponse();
  if ($request->isPost()) 
  {
    $post_data = $request->getPost();
    $booking_id = $post_data['booking_id'];
    $booking_data = array();
    $booking_data = $this->getBookingTable()->getBookingByUserIdAndBookingId($booking_id);
    if (!$booking_data)
      $response->setContent(\Zend\Json\Json::encode(array('response' => false, 'booking_data' => $booking_data)));
    else {
      $response->setContent(\Zend\Json\Json::encode(array('response' => true, 'booking_data' => $booking_data)));
    }
  }
  return $response;
}

The bookingTable model has a public function:

public function getBookingByUserIdAndBookingId($booking_id)
{
   $sql = "Select * from booking where id='".$booking_id."';
   try {
        $statement = $this->adapter->query($sql);
        $res =  $statement->execute();    
        return $res->current();
    } catch (Exception $ex) {
        return $ex;
    }
}

You are posting a variable named 'id':

{
    id: bookingId,
}

So you should access it as:

$post_data = $request->getPost();
$booking_id = $post_data['id'];

or more concisely:

$booking_id = $request->getPost('id');

You should also be using parameterised queries to avoid SQL injection.

For Getting errors/exceptions in an Ajax call use:

In Google Chrome use: POSTMAN Extension

In FireFox user: FIREBUG Plugin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM