php __construct what is wrong with this - php

What's wrong with my code:
class Database
{
private $db;
public function __construct()
{
$dbname = 'dbname';
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
$connStr = "mysql:$dbhost; dbname=$dbname";
try
{
$this->db = new PDO($connStr, $dbuser, $dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $ex)
{
echo $ex->getMessage();
exit;
}
}
public function getTableFromSQLQuery($query, $params)
{
$db = $this->db;
$result = $this->db->prepare($query);
if (isset($params) && count($params)>0)
foreach($params as $key=>$param)
$result->bindParam ($key, $param);
$result->execute();
return $result->fetchAll(PDO::FETCH_ASSOC);
}
}
and call this from code:
$db = new Database();
$query = "SELECT * FROM mytable";
$rowsCategories = $db->getTableFromSQLQuery($query, null);
the error: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected'
The problem in debugger it loses $db in class Database, why? If I each time use $db = new PDO(all params) it works, but if I use with constructor - it doesn't. Help, thanks

Connection string should be
$connStr = "mysql:host=$dbhost;dbname=$dbname";

Change $connStr to:
$connStr = "mysql:host=". $dbhost .";dbname=". $dbname;

Related

Mysql Fatal error: Uncaught Error: Call to a member function fetch() on boolean

<?php
$host = "localhost";
$user = "root";
$password = '';
$dbname = "rokon";
$dsn = 'mysql:host='.$host.';dbname'.$dbname;
$pdo = new PDO($dsn, $user, $password);
$query = 'SELECT * FROM customar';
$query = $pdo->query($query);
while($row = $query->fetch(PDO::FETCH_OBJ)){
echo $row->firstname;
echo '<br>';
}
?>
I get a error while running this code the error is
Fatal error: Uncaught Error: Call to a member function fetch() on
boolean
$dsn = 'mysql:host='.$host.';dbname'.$dbname;
Looks like you made a mistake to assign the database name. You forgot the = symbol.
Just update it to
$dsn = 'mysql:host='.$host.';dbname='.$dbname;
Then this code should work.
Try this code as well it will work.
<?php
$host = "localhost";
$user = "root";
$password = '';
$dbname = "rokon";
try {
$dns = "mysql:host=".$host.";dbname=".$dbname.";charset=utf8";
$pdo = new PDO($dns, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "PDOError: " . $e->getMessage()." In ".__FILE__;
}
$query = 'SELECT * FROM customar';
$query = $pdo->query($query);
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
echo $row->firstname;
echo '<br>';
}

Object couldn't be converted to string

I'm getting this error message when trying to make a PDO connection:
Object of class dbConnection could not be converted to string in (line)
This is my code:
class dbConnection
{
protected $db_conn;
public $db_name = "todo";
public $db_user = "root";
public $db_pass = "";
public $db_host = "localhost";
function connect()
{
try {
$this->db_conn = new PDO("mysql:host=$this->$db_host;$this->db_name", $this->db_user, $this->db_pass);
return $this->db_conn;
}
catch (PDOException $e) {
return $e->getMessage();
}
}
}
The error is on the PDO line. Just in case, I insert the code where I access to the connect() method:
class ManageUsers
{
public $link;
function __construct()
{
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $link;
}
function registerUsers($username, $password, $ip, $time, $date)
{
$query = $this->link->prepare("INSERT INTO users (Username, Password, ip, time1, date1) VALUES (?,?,?,?,?)");
$values = array($username, $password, $ip, $time, $date);
$query->execute($values);
$counts = $query->rowCount();
return $counts;
}
}
$users = new ManageUsers();
echo $users->registerUsers('bob', 'bob', '127.0.0.1', '16:55', '01/01/2015');
Change your connection setting to the following:
class dbConnection
{
protected $db_conn;
public $db_name = "todo";
public $db_user = "root";
public $db_pass = "";
public $db_host = "localhost";
function connect()
{
try {
$this->db_conn = new PDO("mysql:host={$this->db_host};{$this->db_name}", $this->db_user, $this->db_pass); //note that $this->$db_host was wrong
return $this->db_conn;
}
catch (PDOException $e) {
//handle exception here or throw $e and let PHP handle it
}
}
}
In addition, returning values in a constructor has no side-effects (and should be prosecuted by law).
Please follow below code , its tested on my server and running fine .
class Config
{
var $host = '';
var $user = '';
var $password = '';
var $database = '';
function Config()
{
$this->host = "localhost";
$this->user = "root";
$this->password = "";
$this->database = "test";
}
}
function Database()
{
$config = new Config();
$this->host = $config->host;
$this->user = $config->user;
$this->password = $config->password;
$this->database = $config->database;
}
function open()
{
//Connect to the MySQL server
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->database, $this->user,$this->password);
if (!$this->conn)
{
header("Location: error.html");
exit;
}
return true;
}

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 build and call a simple PHP class for a PDO DB connection

Here's what I have so far:
class DB {
var $DBUser = 'xxx';
var $DBPass = 'xxx';
var $DBServer = 'xxx';
var $DBName = 'xxx';
public function connect() {
try {
$strDSN = "mysql:host=$this->DBServer;dbname=$this->DBName;";
$username = $this->$DBUser;
$pass = $this->$DBPass;
$conn = new PDO($strDSN, $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'connected';
}
catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
} //end method
} //end class
Which is then called using this:
$db = new DB;
$conn = $db->connect;
$stmt = $conn->prepare('SELECT * FROM XXX WHERE id = :id');
$id = $_GET['id'];
$stmt->execute(array('id'=>$id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
However, I'm getting this error message:
Fatal error: Call to a member function prepare() on a non-object
Any ideas what I'm doing wrong?
When you call a method, include the parenthesis:
$conn = $db->connect();
// ^^ missing
The second problem is your connect method doesn't return the connection handle. In the try block add:
return $conn;
Finally, when referencing instance and class properties, don't include the $.
$username = $this->DBUser;
// ^ $ should not be present

Cannot redeclare conenect() error using PDO

I´m using pdo for my sql statements.
I have a connect.php file with this code:
<?php
function connect()
{
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'mysite';
try
{
$pdo = new PDO("mysql:dbname={$dbName};host={$dbHost}", $dbUser, $dbPass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $pdo;
}
?>
Now Im trying to use my connect.php in other php file like this:
include('../crud/config.php');
$pdo = connect();
And Im having this error:
Fatal error: Cannot redeclare connect() (previously declared in F:\Xampp\htdocs\projet\crud\config.php:9) in F:\Xampp\htdocs\projet\crud\config.php on line 32
Somebody there have some ideia why this is happening?
Maybe its because im using the statement like this with $pdo->
$verifyLevel = $pdo->prepare("SELECT * FROM administradores where id = :user");
$verifyLevel->bindValue(":user", $user);
$verifyLevel->execute();
$num_rows = $verifyLevel->rowCount();
$result = $verifyLevel->fetch(PDO::FETCH_ASSOC);
Because if I remove the $pdo = connect(); dont gives thar error but then gives other error but then because Im using $pdo->prepare to my sql statement I have an error because $pdo is not recognized without $pdo = connect()

Categories