Storing MySQL connection details as a function in PHP (PDO) - php

I'm trying out the PDO extension, and was wondering if it were possible to store the opening of the DB connection as a function that could be called whenever needed. I tried some basic stuff, but it doesn't seem to work. Can it?
Example Function
function DB() {
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$conn) {
echo "<br />MySQL SERVER CONNECTION ERROR.<br />\n";
}
if($conn) {
return $conn;
}
}
Example Useage
function is_post_id($submitted) {
try {
$id = $submitted;
DB();
//check to see if there is a post
//with an id matching the submitted query
$qPOST= $conn->prepare('SELECT COUNT(*) FROM posts WHERE id = :id');
$qPOST->execute(array('id' => $id));
//results counted
$cPOST= (int)$qPOST->fetchColumn();
if($cPOST > 0) {
return TRUE;
}
else {
return FALSE;
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}

call it as :
$conn = $this->DB();
OR
$conn = $className->DB();

Related

How to fetch data from a MS-SQL Server Database using PHP?

I'm trying to fetch data from a SQL Server database. After debugging, I could figure there's something wrong with the function.
Here's the code:
db.php
class Db{
public static function getConnection() {
$server='xxx';
$database='xxx';
$user='xxx';
$password='xxx';
$dsn="dblib:host=" . $server . ";dbname=" . $database;
try {
$conn = new PDO($dsn, $user, $password);
}
catch (PDOException $e) {
echo 'SQL SERVER CONNECTION ERROR: ' . $e->getMessage();
}
return $conn;
}
}
functions.php
class Functions {
function getAcademicYear() {
$db = new Db();
$conn = $db->getConnection();
$conn->beginTransaction();
$sql = "SELECT academicYear FROM AcademicYear ORDER BY academicYearId DESC LIMIT 5";
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn->commit();
echo $result;
} else {
$conn->rollback();
echo "false";
}
}
}
The function is returning false. Can you please review it and point out any mistakes?

PDO object cant acess inside function

In my project i had a file called connection.inc.php which is managing the data base connection using PDO.
include/connection.inc.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
i included this file in various other pages and it worked perfectly for me. But when i tried to acess the $conn object inside a function it not working. How to fix this problem.
You could do global $conn on top of your functions, but don't. I suggest wrapping it in a singleton instead.
<?php
class Connection {
private static $conn = null;
private $connection = null;
private function __construct() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage(); // Should look into a different error handling mechanism
}
}
public static function getConnection() {
if (self::$conn === null) {
self::$conn = new self();
}
return self::$conn->connection;
}
}
You can access it via Connection::getConnection()
This also has the advantage of not initializing the connection if the current request doesn't need to use it.
Honestly the simplest method is to set the connection inside of a function then you can use that function in other functions.
Example:
error_reporting(E_ALL);
ini_set('display_errors', 1);
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host='.DB_HOSTNAME.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step to close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
How To Use In Another Function:
function doSomething() {
$query = 'SELECT * FROM `table`';
$params = array();
$results = dataQuery($query,$params);
return $results[0]['something'];
}
You need to update your file as
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
//// define global variable
global $connection
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
/// assign the global variable value
$connection = $conn ;
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
Now you can call it any of your function like
function mytest(){
global $connection;
}
The best practice would be to pass the $conn as argument to the function.
But if you really need the function to have no arguments but still use a global variable, then adding this line in your function before using the variable should do the trick:
global $conn; // I want to use the global variable called $conn

How to use PDO prepare more than oncee in a class

class dbConnection {
function connect(){
try{
$this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
return $this->db_conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
}
class student{
public $link;
public function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
public function checkLogin($username,$password){
$query = $this->link->prepare("SELECT * FROM studentprofiles where UserName = :uname AND LogPassword = (select md5(:upassword));");
$query->execute(array(':uname' => $username, ':upassword' => $password));
$count = $query->rowCount();
if($count === 1){
$this->setSession($username);
}
return $count;
$query = null;
}
public static function display(){
$query = $this->link->prepare("SELECT ForeName, Surname FROM studentprofiles where UserName = :uname;"); //getting error here: Fatal error: Using $this when not in object context
$query->execute(array(':uname' => self::getSession()));
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
printf (" <span id='WelcomeName'> Welcome: %s %s\n </span>",$row[0],$row[1]);
}
$query = null;
}
}
Error using $this again to prepare another select statement, how do I use it again for another function in the same class? Thank You
Appreciate any help, really stuck on this problem
hi you can check you code and i prefer asign in to value the conection example
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
and in your function you make some one how this
function connect(){
try{
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
in a complete example this:
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
please try and good luck

PHP: PDO prepare() causing halt in script

I am working on a simple database helper for part of a test site. I want to be able to access a database by simply doing:
require_once 'include/database_system.php'
...
$row = DB_query("SELECT userID FROM users WHERE username = :username",
array(':username' => $ourUsername));
So I've written up a little script to do so:
<?php
session_start();
$username = "xxxx";
$password = "xxxx";
$host = "localhost";
$dbname = "xxxx";
$dboptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
var_dump($db);
}
catch(PDOException $ex)
{
die("MySQL: Failed to connect to API Testing Database");
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
var_dump($db);
// break magic quotes
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function break_magic_quotes(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
break_magic_quotes($value);
}
else
{
$value = stripslashes($value);
}
}
}
break_magic_quotes($_POST);
break_magic_quotes($_GET);
break_magic_quotes($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
function DB_query($query, $queryArgs)
{
global $db;
echo 'TRYING TO QUERY SERVER ';
var_dump($query);
var_dump($queryArgs);
var_dump($db);
try
{
echo 'PREPARE ';
$stmt = $db->prepare($query);
echo 'EXECUTE ';
$result = $stmt->execute($queryArgs);
}
catch(PDOException $ex)
{
echo "QUERY FAILED: $query";
die("Query failed: " . $query);
return;
}
echo 'SERVER QUERY OK';
return $stmt->fetch();
}
So naturally, I'm working on a bit of form action code for the login page, by doing:
require_once 'database.php'
....
$row = DB_query("SELECT * FROM users WHERE username = :username",
array(':username' => $_POST['u']) );
The output is not very conclusive at all. Not only does it fail to get past the $db->prepare() statement, but it doesn't even look like the PDO is valid.
object(PDO)#1 (0) { } object(PDO)#1 (0) { } TRYING TO LOGINobject(PDO)#1 (0) { } TRYING TO QUERY SERVER string(46) "SELECT * FROM users WHERE username = :username" array(1) { [":username"]=> string(4) "derp" } NULL PREPARE
I don't know why it would be doing any of this. I have checked the PHP settings and it looks like PDO is properly turned on. I have checked everything up and down and I haven't been able to get anywhere. If anyone has any insight, that would be great.

Want to delete a row from a table using php pdo

I want to delete a row from a table using php pdo.I am using the following code,
$dsn = 'mysql:host=127.0.0.1;dbname=as1';
$user = 'root';
$password = '';
try {
// Connect and create the PDO object
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'Database connection failed - ';
echo $e->getMessage();
exit;
}
$sql1="DELETE FROM photo WHERE id=?";
$q1=array($result);
try {
$stmt1 = $pdo->prepare($sql1);
$stmt1->execute($q1);
$stmt1->setFetchMode(PDO::FETCH_BOTH);
$result1= $stmt1->fetchColumn();
}
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
But my datas in a table are not deleting ...It shows failed to run query..
You did not provide a value for ?
$stmt1->execute($q); // Where is $q defined?
Should be something like
$q=array(1);
$stmt1->execute($q);

Categories