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.
Related
Im getting the follow error from my elastic beanstalk application:
Fatal error: Uncaught Error: Class 'App\PDO' not found in
/var/app/current/crawler/app/SQLConnection.php:32 Stack trace: #0
/var/app/current/crawler/init.php(18): App\SQLConnection->connect() #1
{main} thrown in /var/app/current/crawler/app/SQLConnection.php on
line 32
The app runs perfectly locally (as is usually the case with errors).
All libraries and dependencies are included in the app I uploaded.
Can anyone see where I went wrong please?
The initialzation script to create DB tables:
<?php
require 'vendor/autoload.php';
require (__DIR__.'/app/SQLConnection.php');
require (__DIR__.'/app/SQLCreateTable.php');
require (__DIR__.'/app/SQLInsert.php');
require (__DIR__.'/app/SQLRetrieve.php');
require (__DIR__.'/app/SQLDelete.php');
use App\SQLConnection;
use App\SQLCreateTable;
use App\SQLInsert;
use App\SQLRetrieve;
use App\SQLDelete;
try {
//connect to DB
$sql = new SQLCreateTable((new SQLConnection())->connect());
//get list of tables
$tables = $sql->getTableList();
//check if required tables excist
if(in_array('results',$tables) && in_array('logs',$tables)){
echo "Tables already created. You will be redirected to the home page";
header( "refresh:5;url=/index.php" );
}else {
//create tables
try {
$sql->createTables();
echo "Tables succesfully created! You will be redirected to the home page";
header( "refresh:5;url=/index.php" );
} catch (\PDOException $e) {
echo "Failed to create tables: " . $e->getMessage();
}
}
} catch (\PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Then the SQL connection script:
<?php
namespace App;
/**
* SQL connnection
*/
class SQLConnection {
/**
* PDO instance
* #var type
*/
private $pdo;
/**
* return in instance of the PDO object that connects to the SQLite database
* #return \PDO
*/
public function connect() {
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
if ($this->pdo == null) {
try {
// $this->pdo = new \PDO("mysql:host=localhost;dbname=crawler", "root", "");
$this->pdo = new PDO($dsn, $username, $password);
// set the PDO error mode to exception
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
return $this->pdo;
}
}
The 'Init' script is at root level and the SQLconnection script is in a folder called "app".
Thanks guys!
Found the solution!
$this->pdo = new PDO($dsn, $username, $password);
Needs to change
$this->pdo = new \PDO($dsn, $username, $password);
If anyone knows exactly why this is the case, please share
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 am trying to establish a PDO connection using the try block and then printing a success message after the connection gets established. My code is as follows:
index.php :
<?php
require_once './vendor/autoload.php';
$con = new \app\db\Connect();
if ($con)
{
echo 'connection successful.';
}
connect.php
<?php
namespace app\db;
class Connect
{
public function __construct()
{
// set the connection variables
$host = 'localhost';
$dbname = 'pdoposts';
$username = 'root';
$password = 'root';
// create the DSN
$dsn = 'mysql:host=' . $host . ';dbname=' .$dbname;
// create PDO connection
try {
static $con;
$con = new PDO($dsn, $username, $password);
} catch(Exception $e) {
echo $e->getMessage();
}
return $con;
}
}
My problem is that there is no way for me to use the $concreated in the try - catch command in the index.php file. I am very sorry if this question seems very basic and elemental one, but please help me understand how it can work. Thank you very much in advance.
Accoring to the answer below:
The solution here on stackoverflow
I just added the backslash right before PDO and made it to be \PDO and it is now working properly. The link below can help understanding PHP Callbacks and how they work better:
Using namespaces: fallback to global function/constant
I should have kept in mind the namespace from which I wanted to use PDO from. In this case, using a \ would tell php to use PDO from the Global Namespace and not from the namespace from which the code runs in (app\db).
I've been trying to convert my application from using the depreciated mysql syntax to PDO for connecting to the database and performing queries, and it's been a pain so far.
Right now I have a class, db_functions.php, in which I'm trying to create a PDO connection to the database, as well as perform all the CRUD operations inside of.
Here is a sampling of the code:
db_functions.php
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'config.php';
// connecting to mysql
try {
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
}
catch (PDOException $e) {
$output = 'Unable to connect to database server.' .
$e->getMessage();
exit();
}
}
// destructor
function __destruct() {
}
public function getAllUsers() {
try {
$sql = "select * FROM gcm_users";
//$result = mysql_query("select * FROM gcm_users");
$result = $this->$db->query($sql);
return $result;
}
catch (PDOException $e) {
$error = 'Error getting all users: ' . $e->getMessage();
}
}
With that code, i'm getting the following error:
Notice: Undefined variable: db in C:\xampp\htdocs\gcm\db_functions.php on line 12
Fatal error: Cannot access empty property in C:\xampp\htdocs\gcm\db_functions.php on line 12
Line 12 is:
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
How could I fix this so that I have a proper instance of a PDO connection to my database that I can use to create queries in other methods in db_functions, such as getAllUsers()
I used the answer found at How do I create a connection class with dependency injection and interfaces? to no avail.
TYPO
//$this->$db =
$this->db =
same here
//$this->$db->query($sql);
$this->db->query($sql);
and i also would use 127.0.0.1 instead of localhost to improve the performance otherwise making a connection will take very long... a couple of seconds just for connection...
I am having a strange error while creating objects. While I create an objects in chronological orders as classed defined, it is going on good. But when I change the order or object creation, it gives error.
The classes I am using are as follows:
<?php
class dbClass{
private $dbHost, $dbUser, $dbPass, $dbName, $connection;
function __construct(){
require_once("system/configuration.php");
$this->dbHost = $database_host;
$this->dbUser = $database_username;
$this->dbPass = $database_password;
$this->dbName = $database_name;
}
function __destruct(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
function mysqlConnect(){
$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("MySQL connection failed!");
mysql_select_db($this->dbName,$this->connection);
}
function mysqlClose(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
}
class siteInfo{
private $wTitle, $wName, $wUrl;
function __construct(){
require_once("system/configuration.php");
$this->wTitle = $website_title;
$this->wName = $website_name;
$this->wUrl = $website_url;
}
function __destruct(){
}
function showInfo($keyword){
if($keyword=="wTitle"){
return $this->wTitle;
}
if($keyword=="wName"){
return $this->wName;
}
if($keyword=="wUrl"){
return $this->wUrl;
}
}
}
?>
The problem is when I create objects in the following order, it is working perfectly:
include("system/systemClass.php");
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
$siteInfo = new siteInfo();
But if I change the order to following
include("system/systemClass.php");
$siteInfo = new siteInfo();
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
It gives error!
Warning: mysql_connect() [function.mysql-connect]: Access denied for user '#####'#'localhost' (using password: NO) in /home/#####/public_html/#####/system/systemClass.php on line 19
MySQL connection failed!
Your problem comes from the unconventional use of a configuration file that is read ONCE, but should be used in all classes.
When you instantiate the dbclass first, the configuration is read, probably variables get assigned, and you use these in the constructor.
After that, instantiating siteinfo will not read that file again, which is less harmful, because you only end up with an empty object that does return a lot of null, but does work.
The other way round, you get a siteinfo object with all the info, but a nonworking dbclass.
My advice: Don't use a configuration file that way.
First step: Remove the require_once - you need that file to be read multiple times.
Second step: Don't read the file in the constructor. Add one or more parameters to the constructor function and pass the values you want to be used from the outside.
Info: You can use PHP code files that configure stuff, but you shouldn't define variables in them that get used outside. This will work equally well:
// configuration.php
return array(
'database_host' => "127.0.0.1",
'database_user' => "root",
// ...
);
// using it:
$config = require('configuration.php'); // the variable now has the returned array