How to use PDO prepare more than oncee in a class - php

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

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?

Call to a member function prepare() on null working with MySQL and PHP

I don't know why I'm getting this error. I looked through some already posted answers. Not helpful.
Here is my code:
public static function validateLogin($postdata){
$dba = new DatabaseAgent("mysql",DBUSER,DBPASSWD,"localhost","projectdatabase");
$username = $postdata['username'];
$password = $postdata['password'];
//Setup the query()
$query = "SELECT * FROM users WHERE username = $username AND password = $password";
//Setup the bind parameters
$bindParams = ['username' => $postdata['username'], 'password' => $postdata['password']];
//Pull the resultset
$resultset = $dba->query($query, $bindParams);
$usertype = ($resultset[0]->type);
var_dump($resultset);
if ($resultset){
//Return true
return true;
} else {
//Return false if the user was not logged in.
return false;
}
}
And here is the PDO code:
public function __construct($dbtype, $user, $pass, $host, $dbname) {
$this->dsn = $dbtype.":host=".$host.";dbname=".$dbname;
$this->user = $user;
$this->pass = $pass;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
//Try to connect, if not barf
try {
$this->pdo = new PDO($this->dsn, $this->user, $this->pass, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
function query($strQuery, $bindParams) {
try {
$this->stmt = $this->pdo->prepare($strQuery);
$this->stmt->execute($bindParams);
} catch (Exception $ex) {
echo "Error Executing Query:".$ex->getMessage();
}
$resultset = null;
while ($result = $this->stmt->fetch(PDO::FETCH_OBJ)) {
$resultset[] = $result;
}
return $resultset;
you just assign the error message to a variable and do nothing else when $pdo throws an exception. Your code will never know whether the PDO instantiation was successfull or not.
Therefore, I assume that $pdo instantiation fails silently and your $pdo attribute is null. Replace $this->error = $e->getMessage(); with throw $e; and see what happens.

PHP Class - Use return in another function

I have one PHP Class with 2 functions DB_Connect() and LogIn(). To use LogIn() I first need to run DB_Connect and get returned value of $CONN. I do this with $this->DB_Connect(); but when I run code I'm get:
Notice: Undefined variable: CONN in
C:\XAMPP\htdocs\core\Admin.class.php on line 39
Fatal error: Call to a member function prepare() on null in
C:\XAMPP\htdocs\core\Admin.class.php on line 39
protected function DB_Connect()
{
$ROOT = dirname(__DIR__);
include $ROOT."../core/sql.php";
try {
$CONN = new PDO("mysql:host=$ServerName; dbname=$DataBase", $Username, $Password);
$CONN->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $CONN;
}
public function LogIn()
{
if($_SERVER["REQUEST_METHOD"] === "POST") {
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$this->DB_Connect();
try {
$SQL = "SELECT Password FROM Admins WHERE Username = :Username";
$SQL = $CONN->prepare($SQL);
$SQL->execute(array('Username' => $Username));
$CountRows = $SQL->rowCount();
$Result = $SQL->fetch(PDO::FETCH_ASSOC);
$PasswordCheck = $Result["Password"];
if($CountRows === "1" && password_verify($Password, $PasswordCheck)) {
$_SESSION["LoginUser"] = $Username;
$CONN = null;
header("location: home.php");
exit();
} else {
$Status = '<div class="alert alert-danger" role="alert">You have entered wrong data!</div>';
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
$CONN = null;
if(isset($Status)) {
return $Status;
}
}
$this->DB_Connect(); returns a value. It doesn't set a variable for you. You need to set a variable to its return value.
$CONN = $this->DB_Connect();

Using a function in php to create a database connection?

So really I just want to make stuff easier to read and just create a function where I can call upon the database connection, the below is what i've tried to do to do far.
So far, it doesn't work, it doesn't bring any message at all so presumably it isn't going into the try.
functions.php
function getDBConnection()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=name;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
}
catch(PDOException $e)
{
echo 'An error occured talking to the DB';
}
return $db;
}
and then do
submittest.php
require('functions.php');
getDBConnection(); //return $db
$username = 'donkey';
$password = 'donkey';
$email = 'donkey';
$county = 'donkey';
try
{
//Prepare and execute an insert into DB
$st = $db->prepare("INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:county)");
$st->execute(array(':username' => $username, ':password' => $password, ':email' => $email, ':county' => $county));
echo 'Success';
}
catch (PDOException $e)
{
echo 'An error occurred talking to the DB';
}
?>
$db = getDBConnection(); //return $db

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

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();

Categories