Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles

vendredi 29 mai 2015

Get Bot Margin to AddPage - FPDF

My PDF file is a table completed with values from a server.
And if the next line created is too large to display on the end of the page, I want to add a new page, then insert my new line.

I guess I must do some maths with $height_of_cell (which I calculate), getY() and margin-bottom but I don't know, and I didn't find how to get this last value.
Does anyone know ? Thank you !

Laravel 4.2 - PHP Error reporting turned off

My Laravel 4.2 application runs happily with undefined variables or array indexes.

I have placed

ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);

in many places in my code in an attempt to get this happen.

The php.ini contains

error_reporting = E_ALL

Debugging is true in app.php.

I have grep'd all of the Laravel and vendor code and my code to look for locations where error reporting may have been turned off, but none seems relevant.

Non-Laravel web applications on the same server crash and/or report properly for these kinds of errors.

PHP is 5.6.8 on Fedora and 5.5. on Centos.

connecting to MS access with php when defined password for database

I am trying to connect Ms Access DataBase from php . My codes like this in config.php

 define('DBNAMEACCESS',  '\\'."\\xxx.xxx.xxx.xxx\\test\\test.accdb");
        define('DBACCESSPASSWORD', 'mypassword');
        define('DBACCESSUSERNAME', '');

and in process.php like this:

     include './config.php';
   if (!file_exists(DBNAMEACCESS)) {
            die("Could not find database file.");
        }
 try{
            $dbName=DBNAMEACCESS;
            $username=DBACCESSUSERNAME;
            $password=DBACCESSPASSWORD;
             $dba = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbName",$username, $password);

   if ($dba) {
/*......*/
} else
            {
                die("Could not connect to access database");
            }
             }
        catch (Exception $ex) {
//            var_export($ex);
                setmessage($ex) ;
        }

when the password is defined for access file , I get this error on this line: My error: odbc_connect(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Cannot open database '(unknown)'. It may not be a database that your application recognizes, or the file may be corrupt., SQL state S1000 in SQLConnect in this line

         $dba = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbName",$username, $password);

and when the password is not defined for access file,My codes execute correctly.

CSS IDs not working when extension is hidden

I developed my site with extensions visible, but when I finished and wanted to make it to production. Now I did a htaccess to hide extensions and add a trailing slash, when people click on a button which redirects/links to #tab1, the url becomes: http://ift.tt/1FHzXSQ

And the CSS ID doesn't open up (the tab).

Is there a way to fix this?

Thanks in advance

zend gdata and google spreadsheet not connecting

ive been using Zend Gdata for a while now, and today im getting an error of

Notice: Undefined offset: ClientLogin.php on line 150

via php, this has been working for a while now, and today without changing anything it stopped working, im guessing some deprecated service on behalf of google with the zend gdata maybe the Zend_Gdata_ClientLogin::getHttpClient( ) method or something, can any one confirm or help me with this issue. the code im using to connect is as follows:

    require_once('Zend/Loader.php');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Docs');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
require_once 'Zend/Gdata.php';
require_once 'Zend/Gdata/AuthSub.php';
require_once 'Zend/Gdata/Spreadsheets.php';
require_once 'Zend/Gdata/Spreadsheets/DocumentQuery.php';
require_once 'Zend/Gdata/Spreadsheets/ListQuery.php';
require_once 'Zend/Loader.php';


$sourceUser = "myemail";
$sourcePass = "mysuperawesomepassword";
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$sourceClient = Zend_Gdata_ClientLogin::getHttpClient($sourceUser, $sourcePass, $service);
$connection = new Zend_Gdata_Spreadsheets($sourceClient);

i am using the zend gdata with the google spreadsheets

also the error points specifically to this line

$sourceClient = Zend_Gdata_ClientLogin::getHttpClient($sourceUser, $sourcePass, $service);

as i said, i was using this for a while now, and nothing has changed on my end

foreach loop in json encode array

I am sending preformatted HTMl with AJAX JSON, JSON have below code,

I am trying pull data array from DB and echoing array data, I am not able to put foreach loop in json_encode, because seems my code is wrong at foreach loop,

How can i achieve that?

echo json_encode(array('returnnews' => '<div class="news-item-page">
                                    <h3 class="text-info" style="margin-top:0">'.$latestnews->news_subject.'</h3>
                                    '.$latestnews->news_content.'


                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <ul class="list-inline blog-tags">
                                            <li>
                                                <i class="fa fa-tags"></i>'.
                                                foreach($news_tag_array as $tag){
                                                <a href="javascript:;">
                                                echo $tag </a>
                                               }

                                            </li>
                                        </ul>
                                    </div>
                               </div>'));

Zend Form ->addValidator('Digits') not working

I am trying to add validator to my Text field as i am expecting user to only enter positive integers. But its not working neither showing any error message if we enter value like '-50'. The code is, $AddInventory = new Zend_Form_Element_Text('AddInventory'); $AddInventory->setAttrib('dojoType',"dijit.form.ValidationTextBox");
$AddInventory->setAttrib('maxlength','40') ->setAttrib('style','width:200px') ->setAttrib('required',"false") ->addValidator('NotEmpty') ->addFilter('StripTags') ->addValidator('Digits')
->removeDecorator("DtDdWrapper") ->removeDecorator("Label") ->removeDecorator('HtmlTag');

Ajax call onSubmit not working

I have a log-in form. Before do the log-in I would like to make sure that username and password are true.. I am trying to achieve this with ajax, but so far it is not working..

in my form I am calling the function check_user onSubmit. This is my code.

    function check_user(e){
        var username = $('#username').val();
        var password = $('#password').val();

        if(username.length>1 && password.length>1){
        e.preventDefault(); // I added this but still it is not working
        alert('alive'); // this is working          

                jQuery.ajax({
                    type : "POST",
                    url : "check_user.php",
                    data : 'username=' + username +"&password=" + password,
                    cache : false,
                    success : function(response) {
                        if (response == 1) {
                        return true;                    
                        } else {        
                        $('#username').css('border', '2px red solid');
                        document.getElementById("username").placeholder = "Wrong username or password";
                        $('#password').css('border', '2px red solid');
                        document.getElementById("password").placeholder = "Wrong username or password";                     
                        return false;                   
                        }
                    }
                });     
        }else{
//this is working
            $('#username').css('border', '2px red solid');
            document.getElementById("username").placeholder = "Wrong username or password";
            $('#password').css('border', '2px red solid');
            document.getElementById("password").placeholder = "Wrong username or password";
            return false;   
        }
    }

In my PHP file check_user.php I have also this code:

$fp = fopen("debug.txt", "a") or die("Couldn't open log file for writing.");
        fwrite($fp, PHP_EOL ."inside");
        fflush($fp);
        fclose($fp);

No debug.txt is created so I assume that the ajax call never happens..

I use the same ajax code when doing the registration to check if the username or email already exists in the database, and the ajax there is working ok. In my example the ajax call never happens and it goes straight to the action="login.php"

Build PHP array with string and result 2 dimensional arrays

I have a smart problem in PHP, I build an array with a string, and at the same time I cut some images. buildProject.php is include in index.php (session_start(); for _session is on the top of it).

buildProject.php

<?php
  $list_projet = array(
    0 => 'img0_pres',
    1 => 'img1_pres',
    2 => 'img2_pres',
  );
  $height_decoup = 500;
  $projet = array();

  foreach ($list_projet as $key => $value) {
    $name_source = $value;
    $img_source_file = 'images/projet/'.$name_source.'.jpg';
    $img_source = imagecreatefromjpeg($img_source_file);

    $width = imagesx($img_source);
    $height = imagesy($img_source);
    $ratio = ceil($height/$height_decoup);
    $img_dest_height = $height_decoup;

    $nb_img_decoup = 1;
    $img_source_y = 0;

    while ($nb_img_decoup <= $ratio) {
      if ($nb_img_decoup == $ratio) {
        $img_dest_height = $height - $height_decoup*($ratio-1);
      }
      $img_dest = imagecreatetruecolor($width,$img_dest_height);
      imagecopy($img_dest, $img_source, 0, 0, 0, $img_source_y, $width, $img_dest_height);
      $img_dest_file = 'images/projet/'.$name_source.'_'.$nb_img_decoup.'.jpg';
      imagejpeg($img_dest, $img_dest_file);

      $projet[$key][$nb_img_decoup] = $img_dest_file; // I SUPPOSE AN ERROR HERE
      $img_source_y += $height_decoup;
      $nb_img_decoup++;
    }
    imagedestroy($img_source);
    imagedestroy($img_dest);
  }
  echo $img_dest_file[0]; // give me an 'i' and suppose give me an error
  echo $projet[0][1][0]; // idem...

  $_SESSION['txt'] = $projet;
?>

After build it, I send it to getProjet.php to find it on main.js with getJSON. My Probleme is $img_dest_file transform alone in array and i need a string!

I thinks the problem is on buildProject.php but I put the other files maybe there are an other error can do that.

getProject.php

<?php
session_start();
$projet = $_SESSION['txt'];

if(isset($_GET['list']) && $_GET['list']>=0){
    echo json_encode($projet[$_GET['list']]);
} ?>

main.js

$.getJSON('php/getProject.php?list=' + index, function(data) {
    length = data.length;
    console.log(data+' //// '+length); // [object object] //// undefined
    console.log(data[1].length); // 29 (total of caracteres...)
    console.log(data[1]); // images/projet/img0_pres_1.jpg
    console.log(data[1][0]); // i
}

So in main.js data=([object object]) and I need data=([object]). I think it's because when i run buildProject.php $img_dest_file transform alone in array and it's normaly just a string not an array.

If someone has an idea why $img_dest_file transform alone in array?

Thanks for reading. If you have question I can specify more.

CSS not being executed in Woocommerce Wordpress template file

I have a fully functional Wordpress custom theme. I have just installed Woocommerce and followed this guide. I have followed the very basic instructions to copy page.php, rename it and modify the loop. I have done this and am able to use Woocommerce, however in the page.php file, I have a

<?php get_header(); ?>

command, which successfully displays that part of the layout in my normal wordpress pages. However, in the direct clone which is now called woocommerce.php, it is not working fully, The links show up, but without any of the associated css which is linked into the header file. Any ideas why two versions of the same file would mean only one correctly imports / interprets the css?

Here are the two web pages:

http://ift.tt/1KhbKno
http://ift.tt/1eCIbmf

Google Calendar API Time

When I try to format 2015-05-29T19:30:00+08:00 from google calendar api;

return \Carbon\Carbon::createFromTimeStamp(
        strtotime('2015-05-29T19:30:00+08:00')
        );

I get the result 2015-05-29 11:30:00 But the start date of the event in my google calendar is exactly 07:30PM One thing is that if I try to add a ->diffForHumans(); I get the result:

16 minutes ago (Note: the time I run the code is 7:46PM)

Can you help me to understand what is going on in here.

DOMDocument cannot change parentNode

I cannot change the DOMDocument parentNode from null. I have tried using both appendChild and replaceChild, but haven't had any luck.

Where am I going wrong here?

   error_reporting(E_ALL);

   function xml_encode($mixed, $DOMDocument=null) {
      if (is_null($DOMDocument)) {
          $DOMDocument =new DOMDocument;
          $DOMDocument->formatOutput = true;
          xml_encode($mixed, $DOMDocument);
          echo $DOMDocument->saveXML();
      } else {
          if (is_array($mixed)) {
              $node = $DOMDocument->createElement('urlset', 'hello');
              $DOMDocument->appendChild($node);
          }
      }
  }

  $data = array();

  for ($x = 0; $x <= 10; $x++) {
      $data['urlset'][] = array(
         'loc' => 'http://ift.tt/1FXudUi',
         'lastmod' => 'YYYY-MM-DD',
         'changefreq' => 'monthly',
         'priority' => 0.5
      );
  }

  header('Content-Type: application/xml');
  echo xml_encode($data);

?>

http://ift.tt/1FHzXCe

ZendX_JQuery_Form_Element_DatePicker doesn´t work

My datepicker doesn't work. I don't get any errors and instead of the datepicker appearing, my field looks like a dropdown and shows the formerly used dates.

I added to my bootstrap:

protected function _InitAutoload()
    {
        $view= new Zend_View();
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $view->addHelperPath(’ZendX/JQuery/View/Helper/’, ‘ZendX_JQuery_View_Helper’);
        $viewRenderer->setView($view);
        Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
    }

I changed my datefield in my formclass like follows:

$datum= new ZendX_JQuery_Form_Element_DatePicker("datum", '',
                    array('defaultDate' => date('Y/m/d', time()))); 

My formclass extends ZendX_JQuery_Form.

In my layout.phtml I added:

$this->jQuery()->setLocalPath('http://localhost/zend/js/jquery/jquery-1.2.6.js')
 ->addStylesheet('http://localhost/zend/js/jquery/themes/ui.datepicker.css');
echo $this->jQuery();

Where is my error? Is there something missing somewhere?

Running code on every kernel boot

I would like a bundle to run code on every boot of the Symfony kernel. Is there a way to accomplish this? I need to be able to use the bundle configuration, therefore the constructor of the bundle class is not an option. Adding an event listener to kernel.request would be an option but it does not work for console scripts.

Multi mysql query returns Commands out of sync

i've created below function which include several mysql queries, which seem to create an issue. Cause when i run this function it returns following error:

Errormessage: Commands out of sync; you can't run this command now

i've tried to include next_result(), but does not do any difference?

function retrievePlayerTweets(){
    global $con;
    $query = $con->prepare("Select players.fullname, players.twitter_user, team.id as teamId FROM players, team WHERE players.teamId = team.id");
    $query->execute();
    $query->bind_result($fullname, $twitter_user, $teamId);

    while ($query->fetch()) {

        foreach(retrieveUserTweets($twitter_user) as $twitterData) {
            $id = $twitterData['id_str'];
            $text = $twitterData['text'];
            $name = $twitterData['user']['name'];
            $dateString = $twitterData['created_at'];
            $favoriteCount = $twitterData['favorite_count'];
            $date = date('Y-m-d H:i:s', strtotime($dateString));



                if ($insert_tweet = $con->prepare("INSERT IGNORE INTO tweets (`fullname`, `username`, `text`, `created`, `teamId`, `twitterId`, `favoriteCount`) VALUES (?, ?, ?, ?, ?, ?, ?)")) {

                    $insert_tweet->bind_param("ssssisi", $name, $twitter_user, $text, $date, $teamId, $id, $favoriteCount);
                    $insert_tweet->execute();
                    $con->next_result();

                } else {
                    die("Errormessage: ". $con->error);
                }






}

PHP SQL Server ODBC Driver

Trying to connect to a remote SQL Server (2008) on local network through a PHP (5.6.7) script running with MAMP on Mac OS Yosemite. I ran through the tutorial here.

I am was able to install and configure successfully. I can connect to SQL SErver through terminal services and query and pull data through 'isql'.

However, I can't seem to figure out how to enable the driver in php. I don't see the odbc.so extension file in the extensions folder, where I think it should be (then enabled in .ini file). Any ideas?

function broke after updating PHP

I have a little problem with a function which doesn't seem to fully work in new php version and I receive

Notice: String offset cast occurred in D:\xampp\htdocs\decode\bencoded.php on line 266
Notice: String offset cast occurred in D:\xampp\htdocs\decode\bencoded.php on line 270

Here is my function:

function bdecode($s, &$pos=0) {
  if($pos>=strlen($s)) {
    return null;
  }
  switch($s[$pos]){
  case 'd':
    $pos++;
    $retval=array();
    while ($s[$pos]!='e'){
      $key=bdecode($s, $pos);
      $val=bdecode($s, $pos);
      if ($key===null || $val===null)
        break;
      $retval[$key]=$val;
    }
    $retval["isDct"]=true;
    $pos++;
    return $retval;

  case 'l':
    $pos++;
    $retval=array();
    while ($s[$pos]!='e'){
      $val=bdecode($s, $pos);
      if ($val===null)
        break;
      $retval[]=$val;
    }
    $pos++;
    return $retval;

  case 'i':
    $pos++;
    $digits=strpos($s, 'e', $pos)-$pos;
    // Proger_XP: changed (int) -> (float) to avoid trimming of values exceeding
    //            signed int's max value (2147483647).
    $val=(float)substr($s, $pos, $digits);
    $pos+=$digits+1;
    return $val;

//  case "0": case "1": case "2": case "3": case "4":
//  case "5": case "6": case "7": case "8": case "9":
  default:
    $digits=strpos($s, ':', $pos)-$pos;
    if ($digits<0 || $digits >20)
      return null;
    $len=(float)substr($s, $pos, $digits);
    $pos+=$digits+1;
    $str=substr($s, $pos, $len);
    $pos+=$len;
    //echo "pos: $pos str: [$str] len: $len digits: $digits\n";
    return (string)$str;
  }
  return null;
}

i understand that i get a warning in the new php, but i have no idea how to fix it.

line 266 (before case 'd'): switch($s[$pos]){

line 270 (after case '1'): while ($s[$pos]!='e'){

eajaxupload for Yii always "failed"

We are currently trying to use the extension eajaxupload for Yii but it seems to be outputting failed everytime we try to upload a file.

We have tried

a) editing the file / minimum file sizes

b) playing around with the file path (may still be incorrect, if anyone knows what the path for locally using in xampp would be, let us know. Our uploads folder is in the root of the project.)

c) changing the htiaccess php file

d) permissions

we just don't know if the code itself is appearing wrong.

controller

/* UPLOADER */
    public function actionUpload(){
        Yii::import("ext.EAjaxUpload.qqFileUploader");
//        $folder = '/uploads/';
//        $folder=Yii::getPathOfAlias() .'/upload/';
        $folder=Yii::app()->baseUrl . '/uploads/';
        $allowedExtensions = array("jpg","png");//array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
//        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
// 
//        $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
//        $fileName=$result['filename'];//GETTING FILE NAME
// 
//        echo $return;// it's array

        $result = $uploader->handleUpload($folder);

        $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
        $fileName=$result['filename'];//GETTING FILE NAME
        $result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);

        echo $result;// it's array
    }

View

*$this->widget('ext.EAjaxUpload.EAjaxUpload',
                array(
                    'id'=>'uploadFile',
                    'config'=>array(
                        'action'=>'/upload/',
//                        'action'=>Yii::app()->createUrl('controllers/uploads/'),
                        'allowedExtensions'=>array("jpg","png"),//array("jpg","jpeg","gif","exe","mov" and etc...
                        'sizeLimit'=>10*1024*1024,// maximum file size in bytes
                        //'minSizeLimit'=>10*1024*1024,// minimum file size in bytes
                        'onComplete'=>"js:function(id, fileName, responseJSON){ alert(fileName); }",
                        'messages'=>array(
                            'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
                            'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
                            'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
                            'emptyError'=>"{file} is empty, please select files again without it.",
                            'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
                        ),
                        'showMessage'=>"js:function(message){ alert(message); }"

                    )*

Fullcalendar returning epoch time values to the database

I am using fullcalendar jquery plugin for my page.When i'm inserting new events using the fullcalendar plugin.., its returning me epoch time values instead of UTC timedate values.

Below is the code that inserts new data into the database on clicking a date.

    calendar.fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        droppable: true, // this allows things to be dropped onto the calendar
        drop: function() {
            // is the "remove after drop" checkbox checked?
            if ($('#drop-remove').is(':checked')) {
                // if so, remove the element from the "Draggable Events" list
                $(this).remove();
            }
        },

        eventSources: [

            {

                url: '/v1/calendar/',
                type: 'GET',
                dataType:'json',


            },
           calendar.fullCalendar( 'addEventSource', response )
        ],

        selectable: true,
        selectHelper: true,
        select: function(start, end, allDay) {

            bootbox.prompt("New Event Title:", function(title) {
                var people_id=1;
                //var title=event.title;
                //var start=event.start;
                //var end=event.end;

                if (title !== null) {
                    calendar.fullCalendar('renderEvent',
                            {
                                people_id:people_id,
                                title: title,
                                start: start,
                                end: end,
                                allDay: allDay
                            },

                    true // make the event "stick"


                            );






                            $.ajax({
                                 url: '/v1/calendar',
                                 data: 'people_id='+people_id+'&title='+title+'&start='+start+'&end='+end,

                                 type: 'POST',
                                 dataType: 'json',
                                 success: function(response){
                                     bootbox.alert("Event Created!");

                                   console.log(response);
                                 },
                                 error: function(e){
                                   console.log(e.responseText);
                                 }
                               });  

                }
            });

The event is successfully added into the database...but the time is in epoch format.

the console response I'm getting is given below:

     {people_id: "1", evt_description: "testing", date1: "1431388800000", date2: "1431475200000", event_id: 4}

I'm using laravel framework at the backend I'm attaching my CalendarController below:

    <?php

class CalendarController extends \BaseController {

/**
 * Display a listing of calendar
 *
 * @return Response
 */
public function index()
{
    $event = DB::table('events')

    ->leftJoin('people','people.people_id','=','events.people_id')  
    ->leftJoin('people_roles','people_roles.people_id','=','events.people_id')      
    ->get(array('events.people_id','events.event_id','events.evt_description','events.date1','events.date2','events.time'));    
    //return View::make('people.show', compact('address'));
    //return Response::json($event);
    $id=array();
    $title=array();
    $start=array();
    $end=array();
    $i=0;
    foreach ($event as $events)
        {

            $id[$i]=$events->event_id;
            $title[$i]=$events->evt_description;
            $start[$i]=$events->date1;
            $end[$i]=$events->date2;
            $i++;           
        }
    return Response::json(array('id'=>$id,'title'=>$title,'start'=>$start,'end'=>$end));
}

/**
 * Show the form for creating a new calendar
 *
 * @return Response
 */
public function create()
{
    return View::make('calendar.create');
}

/**
 * Store a newly created calendar in storage.
 *
 * @return Response
 */
public function store()
{
    $events= Input::get('type');
    $events= new Events;
    $events->people_id = Input::get('people_id');
    $events->evt_description =Input::get('title');
    $events->date1 =Input::get('start');
    $events->date2 =Input::get('end');
    //$events->time =Input::get('time');

    $events->save();


    return Response::json($events);
    //return Redirect::route('calendar.index');
}

/**
 * Display the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    $calendar = Calendar::findOrFail($id);

    return View::make('calendar.show', compact('calendar'));
}

/**
 * Show the form for editing the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function edit($id)
{
    $calendar = Calendar::find($id);

    return View::make('calendar.edit', compact('calendar'));
}

/**
 * Update the specified calendar in storage.
 *
 * @param  int  $id
 * @return Response
 */
public function update($id)
{
    //$type=Input::get('type');
    $event_id= Input::get('event_id');
    $title= Input::get('title');
    $roles = DB::table('events')
                ->where('event_id','=',$event_id )
                ->update(array('evt_description' => $title));
    return Response::json(array('id'=>$event_id,'title'=>$title));



}

/**
 * Remove the specified calendar from storage.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy()
{
//  Calendar::destroy($id);
$event_id= Input::get('eventid');
DB::table('events')->where('event_id','=',$event_id)->delete();

return Response::json($event_id);

//  return Redirect::route('calendar.index');
}

}

MySQL query runs ok in phpadmin but hangs in php

I have a fairly simple query which runs okay when I test it in phpMyAdmin:

   SELECT   
        c.customers_id,
        c.customers_cid,
        c.customers_gender,
        c.customers_firstname,
        c.customers_lastname,
        c.customers_email_address,
        c.customers_telephone,
        c.customers_date_added,
        ab.entry_company,
        ab.entry_street_address,
        ab.entry_postcode, 
        ab.entry_city,
        COUNT(o.customers_id) AS orders_number,
        SUM(ot.value) AS totalvalue, 
        mb.bonus_points
   FROM     
        orders AS o,
        orders_total AS ot,
        customers AS c, 
        address_book AS ab, 
        module_bonus AS mb
   WHERE 
        c.customers_id = o.customers_id 
        AND c.customers_default_address_id = ab.address_book_id 
        AND c.customers_id = mb.customers_id    
        AND o.orders_id = ot.orders_id 
        AND ot.class = 'ot_subtotal'    
 **  AND c.customers_gender  = 'm' AND c.customers_lastname LIKE 'Famlex'
    GROUP BY o.customers_id

The row marked with ** changes depending on filtering settings of the application making the query.

Now, when I test this in phpMyAdmin, the query takes a couple of seconds to run (which is fine, since there are thousands of entries and, as far as I know, when using COUNTs and SUMs indexes don't help) and the results are perfect, but when I run the exact same query in PHP (echoed before running), the MySQL thread loads a core to 100% and doesn't stop until I kill it.

If I strip the extra stuff to calculate the COUNT and SUM, the query finishes but the results are useless to me.

EXPLAIN:

1   SIMPLE  mb  ALL     NULL                        NULL        NULL        NULL                                48713       Using temporary; Using filesort
1   SIMPLE  ot  ALL     idx_orders_total_orders_id  NULL        NULL        NULL                                811725      Using where
1   SIMPLE  o   eq_ref  PRIMARY                     PRIMARY     4           db.ot.orders_id                     1           Using where
1   SIMPLE  c   eq_ref  PRIMARY                     PRIMARY     4           db.o.customers_id                   1           Using where
1   SIMPLE  ab  eq_ref  PRIMARY                     PRIMARY     4           db.c.customers_default_address_id   1

EXPLAIN after applying indexes and using joins:

1   SIMPLE  c   ref     PRIMARY,search_str_idx              search_str_idx          98      const                                   1       Using where; Using temporary; Using filesort
1   SIMPLE  mb  ALL     NULL                                NULL                    NULL    NULL                                    48713   Using where
1   SIMPLE  ab  eq_ref  PRIMARY                             PRIMARY                 4       db.c.customers_default_address_id       1    
1   SIMPLE  ot  ref     idx_orders_total_orders_id,class    class                   98      const                                   157004  Using where
1   SIMPLE  o   eq_ref  PRIMARY                             PRIMARY                 4       db.ot.orders_id                         1       Using where