Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
I've been trying to fix the connection script for my site to make it more secure, by storing the login for the server nd all the details in a separate config file.
My intention was to just call this file for the login details on the server connection function using $this ->, but it's giving me the following errors:
Warning: Undefined property: Database::$server in C:\Program Files\xampp\htdocs\xampp\ecommerce1\includes\conn.php on line 21
Warning: Undefined property: Database::$username in C:\Program Files\xampp\htdocs\xampp\ecommerce1\includes\conn.php on line 21
Warning: Undefined property: Database::$password in C:\Program Files\xampp\htdocs\xampp\ecommerce1\includes\conn.php on line 21
Warning: Undefined property: Database::$options in C:\Program Files\xampp\htdocs\xampp\ecommerce1\includes\conn.php on line 21
I will post both versions of my script as I had it before when it was working, and as I have it currently.
Working(prior version)
<?php
Class Database{
private $config = "mysql:host=localhost;dbname=mysite";
private $config = "root";
private $config = "password";
private $config = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
protected $conn;
public function open(){
try{
$this->conn = new PDO($this->server, $this->username, $this->password, $this->options);
return $this->conn;
}
catch (PDOException $e){
echo "There is some problem in connection: " . $e->getMessage();
}
}
public function close(){
$this->conn = null;
}
}
$pdo = new Database();
?>
My attempt to update(broken code)
<?php
$config = include 'config.php';
Class Database{
public static function make($config)
{
try
{
return new PDO(
$config['connection'].':dbname='.$config['name'],
$config['username'],
$config['password'],
$config['options']
);
}
catch (PDOException $e){
echo "There is some problem in connection: " . $e->getMessage();
}
}
public function open(){
try{
$this->conn = new PDO($this->server, $this->username, $this->password, $this->options);
return $this->conn;
}
catch (PDOException $e){
echo "There is some problem in connection: " . $e->getMessage();
}
}
public function close(){
$this->conn = null;
}
}
$pdo = new Database();
?>
I don't understand why I can't store the login values on $this, like I did in the first example, is it because I'm calling these values from another file?
I thought I would include the config too just in case. Sorry for making this post so long
<?php
return [
'database' => [
'name' => 'db',
'username' => 'root',
'password' => 'password',
'connection' => 'mysql:host=localhost;dbname=db',
'options'=> [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
]
]
?>
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I've used class to connect to database as a model. When when I called it in controller show below error
Recoverable fatal error: Object of class connect could not be converted to string in
C:\xampp\htdocs\awebarts\admin\model\connect.php on line 24 include '../model/connect.php';
<?php
include '../model/connect.php';
$host = "localhost";
$dbname = "awebarts";
$user = "root";
$pass = "";
$connect = new connect($host,$dbname,$user,$pass);
class connect {
private $host ;
private $dbname ;
private $user ;
private $pass ;
public $con ;
function __construct($host,$dbname,$user,$pass){
$this->$host = $host;
$this->$dbname = $dbname;
$this->user = $user;
$this->pass = $pass;
$this->database();
}
private function database(){
try{
$this->con = new PDO("mysql:host=$this->$host; dbname=$this->dbname", $this->user, $this->pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
echo 'cannot connect to database' . $e->getmessage();
}
}
}
Your DSN string is wrong. You can't have spaces and property interpolation in the string.
new PDO("mysql:host=".$this->host.";dbname=".$this->dbname.";charset=utf8mb4", $this->user, $this->pass);
Also see Antony's comment about a typo.
change $this->$dbname to $this->dbnamme and $this->$host to $this->host and make change in code
$this->con = new PDO("mysql:host=$this->host; dbname=$this->dbname", $this->user, $this->pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
I have a project folder name utilities.
The list of directory is:
- utilities
- tli
- database
Connection.php
index.php
The Connection.php is PDOConnection.
The code is:
<?php
namespace app\tli\database;
use PDO;
use PDOException;
Class Connection
{
private $server = "mysql:host=localhost;dbname=ytsurumaru_hanwa_coil_v.2";
private $user = "root";
private $pass = "";
private $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
protected $con;
public function openConnection()
{
try {
$this->con = new PDO($this->server, $this->user, $this->pass, $this->options);
return $this->con;
} catch (PDOException $e) {
return "There is some problem in connection: " . $e->getMessage();
}
}
public function closeConnection()
{
$this->con = null;
}
}
UPDATED SOURCE
Now, I need this Connection instance in index.php
<?php
namespace app;
use app\tli\database\Connection;
use PDOException as PDOEx;
require('tli/database/Connection.php');
try {
$connection = new Connection(); // not found
$connection->openConnection();
} catch (PDOEx $e) {
echo $e->getMessage();
}
When I run it,
D:\wamp64\www\utilities\tli>php index.php
Warning: require(tli/database/Connection.php): failed to open stream: No such file or directory in D:\wamp64\www\utilities\tli\index.php on line 8
Fatal error: require(): Failed opening required 'tli/database/Connection.php' (include_path='.;C:\php\pear') in D:\wamp64\www\utilities\tli\index.php on line 8
How to solved this, is my namepace have a problem ?
Isn't this enough to access your database connection?
require 'tli/database/Connection.php';
Then, since you are in a different name space and you are not aliasing, in your 'try catch block' you should instead of:
$connection = new Connection(); // not found
Do something like:
$connection = new \tli\database\Connection();
Make sure to set your paths right.
OR
You can alias to a different name like so:
namespace app;
require 'tli/database/Connection.php';
use tli\database\Connection as MyConnection;
$connection = new MyConnection();
You need to use one of these:
include('tli/database/Connection.php')
include_once('tli/database/Connection.php')
require('tli/database/Connection.php')
require_once('tli/database/Connection.php')
or if you want some more automation use autoloader.
You may want to look at this SO question and all the linked things.
I have searched the forum, but I have not found anything directly related to my issue. I am fairly new to PDOs and class OOP creation. I am trying to create a database connection class where I can instantiate the connection as needed. I having issues instantiating my connection.
File Organization:
parent directory (folder)
|
private (folder)
|
config.php
classes (folder)
|
class1.class.php
DatabaseConnection.class.php
db_cred.inc.php
public (folder)
|
search.php
Process:
I have created a database credential php file "db_cred.inc.php"
I have a database connection class called "DatabaseConnect" in "DatabaseConnect.class.php" file
I load those files as follows
require_once 'db_cred.inc.php'; in the "DatabaseConnect.class.php" file
spl_autoload_register for all of my class files
Expected actions:
When my "search.php" page request data from mysql via a pdo, a new database connection will instantiate a new connection via the "openConnection()" method.
The class "DatabaseConnection" will load the credentials from "db_cred.inc.php" as a sting and connect to the database
The class will then use the credentials to connect to the mysql database, and execute the requested pdo query returning the results and storing them into a variable "$row".
Issue:
When I execute the pdo, the following error is returned:
Uncaught TypeError: PDO::__construct() expects parameter 1 to be string, array given in private/classes/DatabaseConnect.class.php:21 Stack trace: #0 private\classes\DatabaseConnect.class.php(21): PDO->__construct(Array) #1 \public\search.php(53): DatabaseConnect->openConnection() #2 {main} thrown in \private\classes\DatabaseConnect.class.php on line 21
spl_autoload_register() in the config.php file
function my_autoload($class) {
if(preg_match('/\A\w+\Z/', $class)) {
require ('classes/' . $class . '.class.php');
}
}
spl_autoload_register('my_autoload');
Credential setup in "db_cred.inc.php"
<?php
// define an array for db connection.
define("DB", [
"DB_HOST" => "mysql:host=localhost",
"DB_USER" => "user",
"DB_PASS" => "pass",
"DB_DATABASE" => "mytestdb",
"DB_CHAR" => "utf8",
]);
?>
My class for database connection:
<?php
require_once 'db_cred.inc.php';
// creating db connection class
class DatabaseConnect {
private $server = 'DB_HOST';
private $database = 'DB_DATABASE';
private $pass = 'DB_PASS';
private $user = 'DB_USER';
private $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
protected $con;
public function openConnection() {
**ERROR TAKES PLACE HERE**
try {
$this->con = new PDO([$this->server, $this->database, $this->user, $this->pass]);
return $this->con;
} catch(PDOExeption $e){
echo "ERROR: " . $e->getMessage(), (int)$e->getCode();
}
}
public function closeConnection() {
$this->con = null;
}
}
?>
PDO for search.php
<?php
$dbconn = new DatabaseConnect();
$pdo = $dbconn->openConnection();
$sql = "SELECT * FROM report";
foreach ($pdo->query($sql) as $row) {
echo " PI: ".$row['pi'] . "<br>";
}
?>
I am not sure what is causing the error. I am sure it is due to my inexperience with classes and oop. It appears that the config.php file is working fine. The class is identified by the request because the error happens inside the PDO __construct method. Please help.
UPDATE - MY WORKING SOLUTION
I hope this might help someone moving forward with a similar question. I am not finished with the development of this process, but this kicked in a huge door.
My revised class
<?php
// Associating db_cred.inc.php with class
require_once('db_cred.inc.php');
// Creating db connection class
class DatabaseConnect {
/*
!! Assigning defined constants per define('DB_CONSTANT', 'value') loaded from "db_cred.inc.php" file to variables
!! "db_cred.inc.php" should not be loaded into the "config.php" file
!! BECAUSE THE VALUES OF THE VARIABLES ($variable) ARE CONSTANTS (DB_CONSTANT), DO NOT USE SINGLE OR DOUBLE QUOTES. THE PDO __CONSTRUCT FUNCTION WILL IGNORE THE VALUE OF THE VARIABLE
*/
private $host = DB_HOST;
private $database = DB_DATABASE;
private $pass = DB_PASS;
private $user = DB_USER;
private $char = DB_CHAR;
// Setting attributes and storing in variable $opt
private $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// $con variable will store PDO connection and is set to NULL
private $con;
// Create Connection to database
public function openConnection() {
// Setting $con to null
$this->con = NULL;
// If $con is not NULL make it NULL
if ($this->con === NULL){
try {
// Establish DSN
$dsn = "mysql:host={$this->host};dbname={$this->database};charset={$this->char}";
// Complete the PDO connection
$this->con = new PDO($dsn, $this->user, $this->pass,$this->opt);
// Return the connection and store it in $con
return $this->con;
// Catch any exceptions and store in $e
} catch(PDOExeption $e){
// Echo error and Exception message
echo "ERROR: " . $e->getMessage(), (int)$e->getCode();
}
// If the try/catch block fails, echo that no connection was established
} else {
echo "ERROR: No connection can be established";
}
}
// Close connection and set it to NULL
public function closeConnection() {
if($this->con !== NULL){
$this->con = NULL;
}
}
// create CRUD subclass (Create, Read, Update, Delete)
}
?>
I changed "db_cred.inc.php" eliminating the array. I may revisit the idea.
<?php
// defining DB Credential CONSTANTS to be stored in variables and instantiated by connect class
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASS", "pass");
define("DB_DATABASE", "mytestdb");
define("DB_CHAR", "utf8");
// define an array for db connection.
/*define("DB", [
"DB_HOST" => "localhost",
"DB_USER" => "user",
"DB_PASS" => "pass",
"DB_DATABASE" => "mytestdb",
"DB_CHAR" => "utf8",
]);*/
?>
The error explains itself: You're passing an array where you should be using a string instead.
You need to change this line:
$this->con = new PDO([$this->server, $this->database, $this->user, $this->pass]);
To this, (specifies the DSN first):
$dsn = "mysql:dbname={$this->database};host:{$this->host}";
$this->con = new PDO($dsn, $this->user, $this->password);
I'm learning some PHP while trying to build my own framework as apractice excersice, currently I have a config.php file where I store the database info to connect to plus some PDO settings, both stored into two different arrays.
I also have a Conectar.php file to stablish connection, in this the conexion(coection) method has to receive database and connection data from my arrays...
My ISSUE is I don't know if I a passing this info correctly and I also don't know how to pass my PDO settings array into the conection. Any help would be appreciated!
config.php
<?php
$config = array(
"driver" =>"mysql",
"host" =>"localhost",
"user" =>"root",
"pass" =>"root",
"dbname" =>"projecto1",
"charset" =>"utf8"
);
PDOoptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
);
?>
Conectar.php
<?php
class Conectar{
private $driver;
private $host, $user, $pass, $database, $charset;
public function __construct() {
require_once 'config/database.php';
$this->driver=$config["driver"];
$this->host=$config["host"];
$this->user=$config["user"];
$this->pass=$config["pass"];
$this->database=$config["database"];
$this->charset=$config["charset"];
}
public function conexion(){
if($this->driver=="mysql" || $this->driver==null)
{
try
{
$con= new PDO("mysql:host=$config['host'];dbname=$config['dbname']",$config['user'],$config['pass'],charset=$config['charset']);
}
catch(PDOException $e)
{
echo "Error:".$e->getMessage();
}
}
return $con;
}
}
?>
You are trying to access to the $config variable which is not accessible in your conexion() function. Instead, you have to use the member's variable of your class, defined in your constructor :
$con = new PDO("{$this->driver}:host={$this->host};dbname={$this->database};charset={$this->charset}",
$this->user, $this->pass, $this->PDOoptions);
Also, in your configuration file, you're missing $ in your PDOoptions variable. And store in your class :
private $PDOoptions ;
And in constructor :
$this->PDOoptions = $PDOoptions ;
So, the final code :
class Conectar{
private $driver;
private $host, $user, $pass, $database, $charset;
private $PDOoptions ; // << NEW
public function __construct() {
require_once 'config/database.php';
$this->driver=$config["driver"];
$this->host=$config["host"];
$this->user=$config["user"];
$this->pass=$config["pass"];
$this->database=$config["database"];
$this->charset=$config["charset"];
$this->PDOoptions=$PDOoptions; // << NEW
}
public function conexion(){
$con = null ;
if($this->driver=="mysql" || $this->driver==null)
{
try
{
// NEW // The 2 next lines are changed :
$con = new PDO("mysql:host={$this->host};dbname={$this->database};charset={$this->charset}",
$this->user, $this->pass, $this->PDOoptions);
}
catch(PDOException $e)
{
echo "Error:".$e->getMessage();
}
}
return $con;
}
}
Finally, the $con variable is undefined if the driver is not MySQL. So create a variable to null to avoid a notice.
$con= new PDO("mysql:host={$config['host']};dbname={$config['dbname']}",$config['user'],$config['pass'],charset=$config['charset']);
You need curly braces in the quoted string.
I am trying to connect to an MSSQL server through php but my pdo connection is giving me a hard time and errors that I don't really understand. The code I pasted below was working just fine a week ago and all of a sudden it just stopped without anyone changing anything. I can still connect to the server and run queries directly from the command line but I'm not having the same luck within php.
Anyone see something that I am missing? I spent too much time on this already and it seems like I'm running in circles.
First, this is the error I am getting from my PDOException
SQLSTATE[] (null) (severity 0)
Part of my Mssql()
private function __construct() {
try{
$this->_pdo = new PDO('dblib:host=' . Config::get('prod/host') . ':'. Config::get('prod/port') .';dbname=' . Config::get('prod/db'),Config::get('prod/username'), Config::get('prod/password'));
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
// Already an instance of this? Return, if not, create.
if (!isset(self::$instance)) {
self::$instance = new Mssql();
}
return self::$instance;
} //...This function is working and directs to __construct()
How I am calling it
/*Some random php file*/
function getClients(){
$conn = Mssql::getInstance();
//.....
And my init.php
//...
prod' => array(
'host' => 'xxxxxxx',
'port' => '1433',
'username' => 'xxxxxxx',
'password' => 'xxxxxx',
'db' => 'xxxxxxx'
),
//.....
We changed from using dblib to odbc and the code in my class changed to this:
private function __construct() {
putenv('ODBCSYSINI=/etc');
putenv('ODBCINI=/etc/odbc.ini');
$username = "xxxx";
$password = "xxxx";
try {
$this->_pdo = new PDO("odbc:production","$username","$password");
} catch (PDOException $exception) {
die($exception->getMessage());
}