this class work with mysql perfect
but i wanted to connect now with mssql server
so when i try to change mysql to mssql i get error
"Fatal error: Call to a member function prepare() on a non-object"
<?php
class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct() {
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
} // Catch any errors
catch ( PDOException $e ) {
$this->error = $e->getMessage();
}
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null) {
if (is_null ( $type )) {
switch (true) {
case is_int ( $value ) :
$type = PDO::PARAM_INT;
break;
case is_bool ( $value ) :
$type = PDO::PARAM_BOOL;
break;
case is_null ( $value ) :
$type = PDO::PARAM_NULL;
break;
default :
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue ( $param, $value, $type );
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_OBJ);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
}
any idea thank You
It looks like you need to use the MSSQL specific prepare function. Just using the example from the page but you can substitute your code.
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
i found the solution
here is the constractor using dblib
public function __construct() {
$hostname = "";
$port = ;
$dbname = "";
$username = "";
$pw = "";
// Set DSN
$dsn = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->dbname;
// Set options
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$this->dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
} // Catch any errors
catch ( PDOException $e ) {
$this->error = $e->getMessage();
}
}
Related
In DB.class.php this is my database constructor"
private $database;
private $error;
private $stmt;
public function __construct()
{
$dsn = ...;
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->database = new PDO("$dsn, $this->user, $this->pass, $options");
} catch ( PDOException $e ) {
echo "error";
}
}
public function builder(string $sql)
{
$this->stmt = $this->database->prepare($sql);
$this->stmt->execute();
if (!$stmt) {
exit("Database query failed . . . !");
}
return $stmt;
}
and this is my User.class.php which is extended, my database class:
public function logIn()
{
$sql = "SELECT...;"
$login = parent::builder($sql);
//vardump($login);
$data = $login->fetch(PDO::FETCH_ASSOC);
if ($login->rowCount() == 1) {
$_SESSION['id'] = $data['id'];
Redirect::to('index.php');
} else {
echo "Incorrect user and pass . . .";
exit();
}
}
this is my child constructor
public function __construct(array $args = [])
{
$this->username = $args['username'] ?? '';
$this->email = $args['email'] ?? '';
$this->phone_number = $args['phone_number'] ?? '';
$this->password = $args['password'] ?? '';
$this->photo = $args['photo'] ?? '';
$this->gender = $args['gender'] ?? '';
}
when I var dump $login I get an error ((Uncaught Error: Call to a member function prepare() on null)) how can I fix this problem?
In PHP the MySQL method (like the PDO::lastInertID()) always returns 0 whereas MySQL returns in properly.
I tried try-catch, object initialization, but didn't work.
abstract class Database
{
private static $host = "localhost";
private static $dbname = "loquor";
private static $charset = "utf8";
private static $dbType = "mysql";
private static $dbUsername = "root";
private static $dbPassword = "";
private static function connect ()
{
$dsn = self::$dbType . ":host=" . self::$host . ";dbname=" . self::$dbname . ";charset=" . self::$charset;
$connex = new PDO( $dsn, self::$dbUsername, self::$dbPassword );
$connex->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connex;
}
public static function query ($query, $params = [], $lastInsertID = false)
{
if(!$lastInsertID)
{
$statement = self::connect()->prepare($query);
$statement->setFetchMode(\PDO::FETCH_OBJ);
$statement->execute( $params );
}
else
{
if (explode ( " ", $query )[0] === "INSERT")
{
$statement = self::connect()->query($query);
$x = self::connect()->query("SELECT LAST_INSERT_ID() AS L")->fetch()['L'];
echo $x; //always 0
}
}
if (explode (" ", $query )[0] === "SELECT")
return $statement;
}
}
Database::query("INSERT INTO test(name) VALUES ('test_name') ", [], true));
Returns 0.
I am learning php oop with mysql and I am having trouble fixing this code.
I have checked it twice and also checked this platform to confirm.
<?php
require 'databasesclass.php';
$database = new Database();
$database->query('SELECT * FROM users');
$rows = $database->resultset();
print_r($rows);
and my data base class are
<?php
class Database{
private $host = 'localhost:8889';
private $user = 'root';
private $pass = 'root';
private $dbname = 'register';
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set the DSN
$dsn = 'mysql:host='. $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
// set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($pram, $value, $type = null){
if (is_null($type)){
switch(true) {
case is_int($value):
$type = PDO::PRAM_INT;
break;
case is_bool($value):
$type = PDO::PRAM_BOOL;
break;
case is_null($value):
$type = PDO::PRAM_NULL;
break;
default:
$type = PDO::PRAM_STR;
}
}
$this->stmt->bindValue($parm, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchALL(PDO::FETCH_ASSOC);
}
}
Fatal error: Uncaught Error: Call to a member function prepare() on
null in C:\MAMP\htdocs\Practice\databasesclass.php:31 Stack trace: #0
C:\MAMP\htdocs\Practice\index.php(7): Database->query('SELECT * FROM
u...') #1 {main} thrown in C:\MAMP\htdocs\Practice\databasesclass.php
on line 31
And the Line 31 is:
$this->stmt = $this->dbh->prepare($query);
No need to pass $this->user and $this->pass into your $dns variable. Remove them from there.
So $dns variable will be
from
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
to
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
Please check and let me if you see any error there.
In the moment that you are executing the $database->query('SELECT * FROM users') the $this->dbh is null. You could check if it is an instance of PDO before do the prepare.
I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}
i have php class USER and Database class im doing 10000 users app, and that user will be query 3-4 times a day minumum . my class base and function base here them looking yet for thats have any problem ? or need any fix ?
MY db class
class Database
{
private $host = "";
private $db_name = "";
private $username = "";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
print'{"success": "0","message": "Service Error, Please try again later "}';
}
return $this->conn;
}
}
Also my USER class here
<?php
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID)
{
try
{
$stmt2 = $this->conn->prepare("UPDATE Products SET productCode='$code',productName='$name',productDescription='$description',specialWarning='$specialwarning',productQuantity='$quantity',productPrice='$price' WHERE ID=$productID");
$stmt2->execute();
echo'{"success": "1", "message": "Product Updated"}';
return true;
}
catch(PDOException $e)
{
}
$this->conn = null; // HERE I DID NULL FOR DISABLE MAX CONNECTIONS
}
}
AND HER MY updateproduct.php
<?php
header('Content-type: application/json');
$name = $_REQUEST['name'];
$code = $_REQUEST['code'];
$description = $_REQUEST['description'];
$quantity = $_REQUEST['quantity'];
$price = $_REQUEST['price'];
$specialwarning = $_REQUEST['specialwarning'];
$productID = $_REQUEST['productID'];
include_once 'class.user.php';
$user = new USER($DB_con);
if($user->updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID))
{
}
else
{
}
?>
Can you check my codes is good class for big users ? and good connection returns ? Can i add something ? or need any fix ?Also need to close class ?
Thanks