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?
Related
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
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
I previously used mysqli and now i would like to use PDO instead but I did not echo any result from my database. I have read so many articles about PDO tutorial but they teach different things. I tried to pick piece by piece and came up with this code, but i did not echo any result from my database or throw any error.
try{
$stmt = $conn->query("SELECT * FROM memberpost ORDER BY poststart DESC LIMIT $start_from,$num_rec_per_page");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
if(count($row)>0){
while($row = $stmt->fetch()) {
echo $row['title']."<br>";
}
}
else{
echo "NO result found";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Here is my database connect code:
try {
$conn = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', $username, $password); //new PDO
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Edit your database connection code to this:
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
And try this code in your .php file :
$sth = $conn->prepare(SELECT * FROM memberpost)
$sth->execute();
$red = $sth->fetchAll();
print_r($red);
I found this on the internet, it might help:
// defining query
$sql = 'SELECT name, surname, zip FROM table';
// showing results
foreach($db->query($sql) as $row){
echo $row['name']. '<br>';
echo $row['surname']. '<br>';
echo $row['zip']. '<br>';
}
Source (ita): http://www.mrwebmaster.it/php/guida-utilizzo-pdo_7594_4.html
I am having a play around with PDO and currently have the following code but I am getting Call to a member function prepare() on a non-object and I don't want to use global.
Do I use a class or do I pass it as a variable?
Config.php
function connection()
{
try
{
$host = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = '';
$dbConnection = new PDO("mysql:host=" . $host . ";dbname=" . $dbname.";", $dbuser, $dbpass);
return $dbConnection;
} catch (PDOException $error)
{
echo $error->getMessage();
return FALSE;
}
}
Functions.php
<?php
include('config.php');
$db = connection();
function listCars()
{
$query = $db->prepare("SELECT `id` `rego` `engineSize` `type` `colour` `year` `additionalFeatures` FROM `cars`");
$result = $query->fetchAll();
return $result;
}
?>
Index.php
<?php
include('assets/misc/functions.php');
var_dump(listcars());
?>
You have to load the db variable into your function, in Functions.php, look at this:
Functions.php
include('config.php');
$db = connection();
function listCars($db){
$query = $db->prepare("SELECT `id` `rego` `engineSize` `type` `colour` `year` `additionalFeatures` FROM `cars`");
$result = $query->fetchAll();
return $result;
}
?>
Index.php
<?php
include('assets/misc/functions.php');
var_dump(listcars($db));
?>
However, if you're looking for a more OOP approach, try the following:
<?php
class Cars {
protected $db;
public function __construct(PDO $db){
$this->db = $db;
}
public function listCars(){
$query = $this->db->prepare("... query ...")->execute();
return $query->fetchAll();
}
}
include('config.php');
$cars = new Cars(connection());
try {
var_dump($cars->listCars());
} catch (PDOException $e) {
echo $e;
}
?>
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();