i am developing a search option using php. there i need to do search using user given criteria user can be search when user give id,name,status any of combination of these three parameters.below is my code
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
$where = array();
$values = array();
$types = '';
if (!empty($_POST['serviceNumber'])) {
$where[] = 'serviceNumber = ?';
$values[] = $_POST['serviceNumber'];
$types .= 'i';
}
if (!empty($_POST['name'])) {
$where[] = 'Username = ?';
$values[] = $_POST['name'];
$types .= 's';
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$types .= 's';
}
$query .= implode(' AND ',$where);
printf("rows inserted: %d\n", $query);
printf("rows inserted: %d\n", $values);
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
below line i was going confused,because $values is an array.i need to pass user given paremeters to this in order to execute.
$stmt->bind_param($types,$values);
so in order to get correct results how do i need to do this.
You can use call_user_func_array() to call a function with an array of parameters. The parameters need to be stored as references in order to be passed to the bind_param method. Long story short, you need an array where the 1st value is a string and the rest are references to your parameters.
For example:
$bindParams = [$types];
foreach ($values as $key => $value) {
$bindParams[$key] = &$value;
}
call_user_func_array(
[$stmt, 'bind_param'], //array with the object and the method - callable
$bindParams
);
Try using below:
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
if (!empty($_POST['serviceNumber'])) {
$query .="serviceNumber='$searchkey' ";
}
if (!empty($_POST['name'])) {
$query .="and Username='$name' ";
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$query .=" and status='$status' ";
}
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
Hope this helps.
Related
i get this error while running my program.
Fatal error: Uncaught Error: Call to undefined method
CarModel::InsertCar() in
C:\xampp\htdocs\CoffeeWebsite\Controller\CarController.php:119 Stack
trace: #0 C:\xampp\htdocs\CoffeeWebsite\CarAdd.php(43):
CarController->InsertCar() #1 {main} thrown in
C:\xampp\htdocs\CoffeeWebsite\Controller\CarController.php on line 119
//Source code for CarModel and CarController
<?php
require ("Entities/CarEntity.php");
//Contains database related code for the Car page.
class CarModel {
//Get all car types from the database and return them in an array.
function GetCarTypes() {
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$result = mysqli_query($con,"SELECT DISTINCT type FROM car") or die(mysqli_error($con));
$types = array();
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
array_push($types, $row[0]);
}
//Close connection and return result.
mysqli_close($con);
return $types;
}
//Get carEntity objects from the database and return them in an array.
function GetCarByType($type) {
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$query = "SELECT * FROM car WHERE type LIKE '$type'";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
$carArray = array();
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$colour = $row[4];
$details = $row[5];
$image = $row[6];
$review = $row[7];
//Create car objects and store them in an array.
$car = new CarEntity(-1, $name, $type, $price, $colour, $details, $image, $review);
array_push($carArray, $car);
}
//Close connection and return result
mysqli_close($con);
return $carArray;
}
function GetCarByID($id)
{
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$query = "SELECT * FROM car WHERE id=$id";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$colour = $row[4];
$details = $row[5];
$image = $row[6];
$review = $row[7];
//Create car
$car = new CarEntity($id, $name, $type, $price, $colour, $details, $image, $review);
}
//Close connection and return result
mysqli_close($con);
return $car;
}
}
function InsertCar(CarEntity $car) {
$query = sprintf("INSERT INTO car
(name, type, price,colour,details,image,review)
VALUES
('%s','%s','%s','%s','%s','%s','%s')",
mysqli_real_escape_string($car->name),
mysqli_real_escape_string($car->type),
mysqli_real_escape_string($car->price),
mysqli_real_escape_string($car->colour),
mysqli_real_escape_string($car->details),
mysqli_real_escape_string("Images/Coffee/" . $car->image),
mysqli_real_escape_string($car->review));
$this->PerformQuery($query);
}
function UpdateCar($id, CarEntity $car) {
$query = sprintf("UPDATE car
SET name = '%s', type = '%s', price = '%s', colour = '%s',
details = '%s', image = '%s', review = '%s'
WHERE id = $id",
mysqli_real_escape_string($car->name),
mysqli_real_escape_string($car->type),
mysqli_real_escape_string($car->price),
mysqli_real_escape_string($car->colour),
mysqli_real_escape_string($car->details),
mysqli_real_escape_string("Images/Coffee/" . $car->image),
mysqli_real_escape_string($car->review));
$this->PerformQuery($query);
}
function DeleteCar($id) {
$query = "DELETE FROM car WHERE id = $id";
$this->PerformQuery($query);
}
function PerformQuery($query) {
require ('Credentials.php');
$con=mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
mysqli_select_db($con,$database);
//Execute query and close connection
mysqli_query($query) or die(mysqli_error($con));
mysqli_close($con);
}
?>
<?php
require ("Model/CarModel.php");
//Contains non-database related function for the Coffee page
class CarController {
function CreateCarDropdownList() {
$carModel = new CarModel();
$result = "<form action = '' method = 'post' width = '200px'>
Please select a type:
<select name = 'types' >
<option value = '%' >All</option>
" . $this->CreateOptionValues($carModel->GetCarTypes()) .
"</select>
<input type = 'submit' value = 'Search' />
</form>";
return $result;
}
function CreateOptionValues(array $valueArray) {
$result = "";
foreach ($valueArray as $value) {
$result = $result . "<option value='$value'>$value</option>";
}
return $result;
}
function CreateCarTables($types)
{
$carModel = new CarModel();
$carArray = $carModel->GetCarByType($types);
$result = "";
//Generate a carTable for each carEntity in array
foreach ($carArray as $key => $car)
{
$result = $result .
"<table class = 'carTable'>
<tr>
<th rowspan='6' width = '150px' ><img runat = 'server' src = '$car->image' /></th>
<th width = '75px' >Name: </th>
<td>$car->name</td>
</tr>
<tr>
<th>Type: </th>
<td>$car->type</td>
</tr>
<tr>
<th>Price: </th>
<td>$car->price</td>
</tr>
<tr>
<th>Colour: </th>
<td>$car->colour</td>
</tr>
<tr>
<th>Details: </th>
<td>$car->details</td>
</tr>
<tr>
<th>Review: </th>
<td colspan='2' >$car->review</td>
</tr>
</table>";
}
return $result;
}
function GetImages() {
//Select folder to scan
$handle = opendir("Images/Coffee");
//Read all files and store names in array
while ($image = readdir($handle)) {
$images[] = $image;
}
closedir($handle);
//Exclude all filenames where filename length < 3
$imageArray = array();
foreach ($images as $image) {
if (strlen($image) > 2) {
array_push($imageArray, $image);
}
}
//Create <select><option> Values and return result
$result = $this->CreateOptionValues($imageArray);
return $result;
}
//<editor-fold desc="Set Methods">
function InsertCar() {
$name = $_POST["txtName"];
$type = $_POST["ddlType"];
$price = $_POST["txtPrice"];
$colour = $_POST["txtColour"];
$details = $_POST["txtDetails"];
$image = $_POST["ddlImage"];
$review = $_POST["txtReview"];
$car = new CarEntity(-1, $name, $type, $price, $colour, $details, $image, $review);
$carModel = new CarModel();
$carModel->InsertCar($car);
}
function UpdateCar($id) {
}
function DeleteCar($id) {
}
//</editor-fold>
//<editor-fold desc="Get Methods">
function GetCarById($id) {
$carModel = new CarModel();
return $carModel->GetCarById($id);
}
function GetCarByType($type) {
$carModel = new CarModel();
return $carModel->GetCarByType($type);
}
function GetCarTypes() {
$carModel = new CarModel();
return $carModel->GetCarTypes();
}
//</editor-fold>
}
?>
To elaborate on my comment.
First you want to use Prepared statements. Here is an example:
/* Connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($stmt = $mysqli->prepare("UPDATE..."))
{
/* Bind your params */
$stmt->bind_param('ss', $username, $password);
/* Error handling if execute failed */
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
else
{
/* Error handling if Prepare failed */
die('prepare() failed: ' . htmlspecialchars($DBConnect->error));
}
$stmt->close();
Read more about returning result here
Now since you want to pass in args from your functions which are unknown to the PerformQuery function, you'll want to dynamically generate the Bind Params for use of using prepared statements. I've done something similar for dynamically generating the Bind Params using Reflection.
If you pass an Args value into the PerformQuery function you could have a function that looks like this:
public function PerformQuery($sql, $args = null)
{
/* Connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($stmt = $mysqli->prepare($sql))
{
/* Bind your params dynamically */
if (isset($args))
{
$method = new \ReflectionMethod('mysqli_stmt', 'bind_param');
$method->invokeArgs($stmt, $this->refValues($args));
}
/* Error handling if execute failed */
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
else
{
/* Error handling if Prepare failed */
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$stmt->close();
}
For the dynamic binding to work you'll also need the following function
private function refValues($arr)
{
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
Now from your other methods, for example DeleteCar you'd pass in the query and args as follows:
public function DeleteCar($id)
{
$query = "DELETE FROM car WHERE id = ?"; // ? to show where mysqli will bind
$args = array('i', $id); // i means an int
$this->PerformQuery($query, args);
}
Using prepared statements will make your code much more secure and dynamically binding the variants in the Preform Query function means that you don't have to completely refactor your code to pass a connection around so you can use mysqli_real_escape_string.
Good luck :)
I have code, which is basically a copy of a php.net's code, but for some reason it does not work. Here is the code on php.net:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
The first change I made was the connection:
$mysqli = new mysqli("localhost", "root", "", "fanfiction");
The second change I made was the queries:
$query = "SELECT first FROM tests;";
$query .= "SELECT second FROM tests;";
$query .= "SELECT third FROM tests;";
$query .= "SELECT fourth FROM tests";
EDIT: The full code with my changes
<?php
$mysqli = new mysqli("localhost", "root", "", "fanfiction");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first FROM tests;";
$query .= "SELECT second FROM tests;";
$query .= "SELECT third FROM tests;";
$query .= "SELECT fourth FROM tests";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
The error I get:
Strict standards: mysqli::next_result(): There is no next result set.
Please, call mysqli_more_results()/mysqli::more_results() to check
whether to call this function/method in
address on line line number
I searched a solution over the net, and particularly here on StackOverflow, but I did not find helpful solutions. Most of the solutions I found were one of those two:
In this solution,#Hammerite says to change the loop from do-while to while. This suggest that php.net's code has a problem in its logic, and I find it very hard to believe. But more importantly, it just does not work for me.
In this solution, #mickmackusa suggests to add a condition in the while and change $mysqli->next_result() to $mysqli->next_result() && $mysqli->more_results(), but this solution do not work quite well. It does indeed removes the error but it omits the last result.
Try it with
} while ($mysqli->more_results() && $mysqli->next_result());
sscce:
<?php
ini_set('display_errors', 'on');
error_reporting(E_ALL|E_STRICT);
$mysqli = new mysqli("localhost", "localonly", "localonly", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query('CREATE TEMPORARY TABLE City (ID int auto_increment, `Name` varchar(32), primary key(ID))') or die($mysqli->error);
$stmt = $mysqli->prepare("INSERT INTO City (`Name`) VALUES (?)") or die($mysqli->error);
$stmt->bind_param('s', $city) or die($stmt->error);
foreach(range('A','Z') as $c) {
$city = 'city'.$c;
$stmt->execute() or die($stmt->error);
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if (!$mysqli->multi_query($query)) {
trigger_error('multi_query failed: '.$mysqli->error, E_USER_ERROR);
}
else {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("'%s'\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
prints
'localonly#localhost'
-----------------
'cityU'
'cityV'
'cityW'
'cityX'
'cityY'
without warnings/notices.
I have tried the following code to output each student father_contact by firstly merging them and secondly separating each number by comma and could not make it working. Please help me.
$sql = "SELECT Fathers_Contact FROM student WHERE Class ='$class' AND Section='$s' and Year='$y'";
$result = mysql_query($sql);
if (!$result) {
die("Query not working");
}
$mbno_arr = array();
while ($row = mysql_fetch_array($result)) {
$mbno_arr[] = $row[0];
}
$mbno_list = implode(',', $mbno_arr);//expect here is: 9867656543,9867656443,9867654543
if(empty($mbno_list)){
echo "No number is there";
exit;
}
if(empty($msg)){
echo "Message empty!";
exit;
}
Father_contact is ten digit mobile no.
// Escapes special characters in a string for use in an SQL statement
$SQL = sprintf(
"SELECT Fathers_Contact
FROM student
WHERE Class = '%s' AND Section = '%s' and Year = '%s'",
mysql_real_escape_string($class),
mysql_real_escape_string($s),
mysql_real_escape_string($y)
);
// Result or die (print mysql error)
$result = mysql_query($SQL) or die( mysql_error() );
// Check if result has rows
if( mysql_numrows($result) > 0 )
{
$mbno_arr = array();
while ( $row = mysql_fetch_array($result) )
$mbno_arr[] = $row[0];
if( count($mbno_arr) > 0)
echo implode(',', $mbno_arr);
else
echo 'No number is there';
}
else
{
echo 'No result for query';
}
// free result
mysql_free_result($result);
NB use PDO or mysqli. mysql_* is deprecated
Firstly, mysql_* is now officially deprecated. Please use PDO or MySQLi.
Can you try this:
<?php
// Connect
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Query
$query = "SELECT Fathers_Contact FROM student WHERE Class = ? AND Section = ? and Year = ?";
if ($stmt = $mysqli->prepare($query)) {
{
// Bind params
$stmt->bind_param("sss",
$class,
$s,
$y);
// Execute statement
$stmt->execute();
// fetch associative array
$mbno_arr = array();
$result = $stmt->fetch_result();
while ($row = $result->fetch_assoc())
{
// Build data
$mbno_arr[] = $row['Fathers_Contact'];
}
// close statement
$stmt->close();
// Debug?
$mbno_list = implode(',', $mbno_arr);
if (empty($mbno_list)) {
echo "No number is there";
} else {
echo "Query Results: $mbno_list";
}
}
// Close Connection
$mysqli->close();
?>
Hi I have the following code below in a php file
global $server, $mysqlusername, $mysqlpassword, $db;
$conn = new mysqli($server, $mysqlusername, $mysqlpassword, $db);
function getCategories() {
global $conn;
$categories = array();
$sql = "SELECT categoryName FROM reportcategorys";
$maincat = $conn->query($sql);
while($row = $maincat->fetch_array(MYSQLI_ASSOC)) {
// do something with the $row
array_push($categories, $row);
}
$sql1 = "SELECT * FROM reportsubcategorys";
$subcats = $conn->query($sql1);
// Loop through sub categories and append to parent array
while($row = $subcats->fetch_array(MYSQLI_ASSOC)) {
$parent = $row['categoryName'];
$name = $row['subCategoryName'];
// Append subcategory name as child to the parent category
for ($i=0; $i<count($categories); $i++) {
if ($categories[$i]['categoryName'] == $parent) {
array_push($categories[$i], $name);
}
}
}
//print_r($categories);
return $categories;
}
It is giving me an error message saying
"Fatal error: Call to a member function fetch_array() on a non-object in"
Any idea what may be causing this?
Thanks
It is likely that your query has not executed properly.
mysqli->query() will return a boolean value FALSE if the query has not been executed properly, else it will return a mysqli_result object. So after every query, before calling fetch_array() method, check the result of the query. Something like this.
$maincat = $conn->query($sql) or die($conn->error);
or
$maincat = $conn->query($sql);
if(!$maincat){
echo $conn->error;
}
Also, when you established your connection with the database, check if the connection was error-free.
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
Are you using fetch_array for any reason in particular?
Try it like this one...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* verificar la conexión */
if (mysqli_connect_errno()) {
printf("Conexión fallida: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* obtener array asociativo */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* liberar el resultset */
$result->free();
}
/* cerrar la conexión */
$mysqli->close();
?>
If I am doing an old query to return a row I would do something like this:
$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" LIMIT 1';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
echo $row['id'];
How do I do that with a Prepared Statement? I can get this far...
$stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? LIMIT 1");
if ($stmt->execute(array($_POST['email']))) {
// what goes in here to pull out this one row?
}
Secondly, if I have multiple rows I would do it like this:
$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" ';
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
echo $row['id'];
}
Likewise, with PDO I get to a similar place...
$stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? ");
if ($stmt->execute(array($_POST['email']))) {
// what goes in here to loop through the rows??
//
// something like this...?
//
while ($row = $stmt->fetch()) {
echo $row['id'];
}
}
Assuming you're connected to the DB and $dbh is your PDO object.
<?php
$email = 'myEmail#somesite.com';
$stmt = $dbh->prepare("SELECT `id` FROM `table` WHERE `email` = ?");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(1, $email, PDO::PARAM_STR);
$stmt->execute();
/* One row. */
$result = $stmt->fetch();
if ($result !== FALSE) {
$stmt->closeCursor();
echo $result['id'];
}
/* Multiple rows. */
$result = $stmt->fetchAll();
if ($result !== FALSE) {
foreach ($result as $row) {
echo $row['id'];
}
}
?>
Here is what I use:
For more info on PDO see: http://php.net/manual/en/book.pdo.php
How to use:
//create connection
$connection = new Connection($settings,true);
$conn = $connection->conn;
//query
$sql = "SELECT StateName as State, StateAbbr as Abb FROM State";
$values = array(":Abbr" => "AL");
$query = new Query($conn);
$testArr = $query->getArrayFromQuery($sql, $values);
CONNECTION: (Connection.php)
class Connection
{
public $conn = null;
/**
* Creates PDO Database Connection
*
* #param array $params Connection Data (host,database,username,password)
* #param bool $useErrorReporting True to Show Errors (optional)
* #sets Database Connection
* #access public
*/
public function __construct($params,$useErrorReporting=false)
{
try
{
$host = "";
$database = "";
$username = "";
$password = "";
if(isset($params) && is_array($params))
{
$host = $params['database_connection']['host'];
$database = $params['database_connection']['database'];
$username = $params['database_connection']['username'];
$password = $params['database_connection']['password'];
$dsn = 'mysql:dbname='.$database.';host='.$host;
$dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => true));
//display errors if true
if($useErrorReporting)
{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
else
{
$dbh = null;
}
}
catch (PDOException $e)
{
throw new Exception('Connection Failed: '.$e->getMessage());
}
$this->conn = $dbh;
}
QUERY: Query.php
Class Query
{
private $conn = null;
/**
* sets query properties
*
* #param object $conn pdo connection object
* #return void
* #access public
*/
public function __construct($conn)
{
$this->conn = $conn;
}
/**
* getArrayFromQuery
* gets array from given query
*
* #param string $sql sql statement
* #param array $values array values to replace (":value" => 2)
* #return array
* #access public
*/
public function getArrayFromQuery($sql, $values)
{
$retValue = array();
$conn = $this->conn;
$statement = "";
try
{
//prepare sql statement
$statement = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
//add values
if(isset($values) && is_array($values))
{
$statement->execute($values);
}
//set return array to result array
$retValue = $statement->fetchAll();
}
catch (PDOException $e)
{
throw new Exception("PDO Query Error: ".$e->getMessage());
}
catch(Exception $e)
{
throw new Exception("Process Query Error: ". $e->getMessage());
}
return $retValue;
}
}