php - How to proceed with database statements -


using 1 of tutorials managed create working database retrieval using php, json , jquery

now question is, if have multiple query statements want execute best solution?

i have tried opening second connection in different functions , sending information array in array not work.

database.php:

<?php  function getdbconnection() {   $db = new pdo(db_driver . ":dbname=" . db_database . ";host=" . db_server, db_user);   $db->setattribute(pdo::attr_errmode, pdo::errmode_exception);    return $db; } function home_ratings() {     $db = getdbconnection();     $stmt1 = $db->prepare("select * table1");      $isok1 = $stmt1->execute();       $results_home = array();       if ($isok1)          {             $results_home = $stmt1->fetchall();         }      else          {             trigger_error('error executing statement.', e_user_error);         }     $db = null;      return $results_home;  } ?>  

get.php:

<?php require('constant.php'); require('database.php');  $home = home_ratings(); //$top_rest = top_ratings(); //$newr = new_ratings();  //echo json_encode($home); echo json_encode(array('home' => $home)); ?> 

info.js:

$( document ).ready(function() {      $.get( "php/get.php")     .done(function(data) {                       var results = jquery.parsejson(data);                      $.each(results, function(i, value) {                     //do need here                    })                 });  }); 

you need 1 database connection object if you're connecting same database in same method. instead of having function getdbconnection() instead make $db variable global , use within functions (you may need put line global $db; in function ensure can access global variable).

example of how database.php file look:

<?php   $db = new pdo(db_driver . ":dbname=" . db_database . ";host=" . db_server, db_user);   $db->setattribute(pdo::attr_errmode, pdo::errmode_exception);   function home_ratings() {     global $db; // $db scope of global     $stmt1 = $db->prepare("select * table1");      $isok1 = $stmt1->execute();       $results_home = array();       if ($isok1)          {             $results_home = $stmt1->fetchall();         }      else          {             trigger_error('error executing statement.', e_user_error);         }      return $results_home; } ?>  

Comments