This question already has answers here:
PHP PDO SQLite connection
(2 answers)
Closed 1 year ago.
I have created a database using DB browser for sqlite. I would like to connect to the database using a PDO function in php. My project currently has the php dataBaseHandler file and database file in the same folder. And then the index.php file which the database is going to be used in, is in a different folder (all under the same root folder). Basically right now when using the PDO to connect to the database i am getting an error saying Connection failed: SQLSTATE[HY000] [1049] Unknown database 'jobs.db'
Here is my PDO code
<?php
class Dbh {
private $servername;
private $username;
private $password;
private $dbname;
private $charset;
public function connect() {
$this->servername = 'localhost';
$this->usernamae = 'root';
$this->password = '';
$this->dbname = 'jobs.db';
$this->charset = 'utf8mb4';
try {
$dsn = "mysql:host=".$this->servername.";dbname=".$this->dbname.";charset=".$this->charset;
$pdo = new PDO($dsn, $this->usernamae, $this->password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
echo "Connection failed: ".$e->getMessage();
}
$dsn = "mysql:host=".$this->servername.";dbname=".$this->dbname.";charset=".$this->charset;
$pdo = new PDO($dsn, $this->usernamae, $this->password);
return $pdo;
}
}
?>
And here is a photo of my folder structure, showing where the database file is relative to the DataBaseHandler file is.Website Structure
I should also mention that my code is being run through XAMPP.
You should use something similar to $dsn = "sqlite:" . $this->dbname; to connect to the SQLite database file.
Related
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);
From a friend, I got a website (zip file) with PHP and HTML files in it. I also got a SQL script from him. Now what I'm trying to do is run the application on localhost (Xampp apache server) and the website does load, but it looks like I can't connect to the database.(I did import the SQL script and it worked, But I'm still getting this error) This is an error for example that I'm receiving on the home page:
Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'dewaai'#'localhost' (using password: YES)
Notice: Undefined index: logged in C:\xampp\htdocs\deWaai\includes\header.php on line 14
The name of the database is 'dewaai'
The username is: root
And I think there is no password...
This is the connection.php file:
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "dewaai", "dewaai", "dewaai");
$db->connect();
?>
These are database functions in the db.php file:
<?php
class db {
private $conn;
private $servername;
private $dbuser;
private $dbpass;
private $dbname;
function setDB($servername, $dbuser, $dbpass, $dbname) {
$this->servername = $servername;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbname = $dbname;
}
function connect() {
try {
$this->conn = new PDO("mysql:host=$this->servername;dbname=$this->dbname", $this->dbuser, $this->dbpass);
// set the PDO error mode to exception
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
Does anyone know how I can fix this so the database runs the application?
I really don't know why I'm getting that error.
Any kind of help is appreciated, thx
There is problem with your username or password.
$db->setDB("localhost", "root", "", "dewaai");
Try this it will help you to connect with your database
Hi the issue clearly from the error message states that your username and password given in connection.php file is incorrect.
The format for DB connection is
$db->setDB( Database host IP address or DNS name , Username , Password, DatabaseName);
From what you said i guess connection.php file should be
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "root", "", "dewaai");
$db->connect();
?>
And i think your PDO connection might have an issue as well. It should be
$this->conn = new PDO('mysql:host='.$this->servername.'; dbname='.$this->dbname, $this->dbuser, $this->dbpass);
Hope this helps.
I am receiving the following error when loading my index page:
Fatal error: Call to a member function prepare() on a non-object in /Applications/MAMP/htdocs/parse/helloworld/helloworld/libraries/Database.php on line 32
I will place all of the relevant code below, sorry for the length but it should be fairly straight forward to read. The short version is I am practicing PDO and PHP classes so I am remaking an existing project I had on a different machine. (which is why a there is a lot of calls in the index file which acts more like a controller).
I am pulling my hair out here because it works on my other machine and from what i can tell the two projects are identical... I am just getting this error. I had this in my previous project, but that was because I had misspelled the database in the config file... I am 100% positive I did not do that again but I don't know what else I missed -- clearly the PDO class is not being made if I var_dump it returns null... Any and all help would be greatly appreciated (especially if it is in regards to my PDO class style I am just following a blog which seemed to make sense when it worked).
EDIT:
After some debugging it was clear that the try block in the database class was failing because a connection could not be established. This was clear after running $this->error = $e->getMessage() which returned:
string(119) "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)"
As the accepted answer below states the error indicates localhost trying to connect via a unix socket and mysqld not being able to able to accept unix socket connections.
So the original error leads to the ultimate question of: how do you connect to a unix socket when mysqld is not accepting unix socket connections and/or why does mysqld not accept unix socket connections?
End EDIT.
This is my (relevant) PDO class:
<?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 ) {
var_dump($dsn);
$this->error = $e->getMessage();
}
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
This is the index file that gets called
<?php
require('core/init.php');
//Create objects...
$type = new Type;
$post = new Post;
$group = new Group;
$follower = new Follower;
//Create template object
$template = new Template('templates/front.php');
$template->types = $type->getAllTypes();
$template->groups = $group->getAllGroups();
$template->posts = $post->getAllPosts();
$template->replies = $post->getReplies();
$template->followers = $follower->getAllFollowers();
echo $template;
and these are the other relevant files:
config --
<?php
//DB Params
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "root");
define("DB_NAME", "dobbletwo");
define("SITE_TITLE", "Welcome To Dooble!");
init --
//include configuration
require_once('config/config.php');
//helper functions
require_once('helpers/photo_helper.php');
require_once('helpers/system_helper.php');
//Autoload Classes
function __autoload($class_name){
require_once('libraries/'.$class_name . '.php');
}
for the sake of brevity (which may be far gone at this point I will only show one of the classes i load to prove that I am constructing the db(type, post, group, follower, template...)
<?php
class Type {
//Initialize DB variable
public $db;
/*
* Constructor
*/
public function __construct(){
$this->db = new Database;
}
the mysql libraries seem to interpret localhost as meaning you want to connect via a unix socket. your error indicates your mysqld isn't setup to accept unix socket connections.
to connect via tcp/ip instead, change define("DB_HOST", "localhost"); to define("DB_HOST", "127.0.0.1");
This question already has answers here:
How to properly set up a PDO connection
(5 answers)
Closed 9 years ago.
Okay so I have some what of a dumb question, I've seen tuts and different things on making a CMS and I want to make an oop CMS, and I was wondering if someone could explain to me what the difference was between using one of the two examples?
Ex 1 -
class myClass
{
var $username;
var $password;
public function connect()
{
try {
$pdo = new PDO('mysql:host=localhost;dbname=dbname', $this->username,
$this->password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
// Then to call that function
$obj = new myClass();
$obj->username = "root";
$obj->password = "password";
$pdo = $obj->connect();
// Then run my query down here
Ex 2 -
class database
{
protected $connection = null;
//make a connection
public function __construct($hostname,$dbname,$username,$password)
{
try {
//MySQL with PDO_MYSQL
$this->connection = new PDO("mysql:host=$hostname;dbname=$dbname",
$username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$this->connection = null;
die($e->getMessage());
}
}
}
Or I've even seen people use a __construct then a seperate connect function
So what exactly is the difference? Is there a performance benefit by doing it a particular way? Or is there a way that is more correct than the other or are all three if these incorrect ways of doing it? I haven't found a reliable source to find an answer.
For the most cases 3rd example is the best:
In fact, PDO is already a database class. So, if you have no particular reason to create another on top of it, PDO itelf is just a perfect:
$pdo = new PDO('mysql:host=localhost;dbname=dbname', $username,$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
is all you actually need.
There are no noticeable performance differences between the two.
The second way is preferred by a lot of people because a database object would be kind of useless if it didn't try to connect to a database. Because attempting to connect to a database is so vital to the object's worth / existence, it makes sense to send in the connection details via the constructor so that it can attempt a connection as soon as it is being instantiated. Thus, changing:
$obj = new myClass();
$obj->username = "root";
$obj->password = "password";
$pdo = $obj->connect();
to
$obj = new myClass('localhost', 'root', 'mypassword');
I have my 'dbinterface' class with a connect function. When i run this i get a statement saying "Query didn't work. No database selected"
class dbinterface {
private $_dbLink;
private $dbHost = 'host';
private $dbUser = 'user';
private $dbName = 'name';
private $dbPass = 'pass';
private $dbUserTable = 'table';
public function connect ()
{
$this->_dbLink = mysql_connect($this->_dbHost, $this->_dbUser, $this->_dbPass);
if(!$this->_dbLink)
throw new Exception ("Could not connect to database. " . mysql_error());
}
I made a change to the public connect function.
public function connect ()
{
$this->dbLink = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
mysql_select_db($this->dbUserTable);
if(!$this->dbLink)
throw new Exception ("Could not connect to database. " . mysql_error());
}
Unfortunately it output the same result. I am new to PHP and still learning, i have tried everything i know so ANY help is very much appreciated.
Unless you use an absolute schema.table type reference in your queries, you HAVE to specify a default database with mysql_select_db(). Without that,
SELECT somefield FROM sometable
fails with "no database selected" because MySQL doesn't know WHICH database it should look in for that table.
This would work, however:
SELECT somefield FROM name_of_db.name_of_table
without a default database, as you've explicitly stated you're using the "name_of_db" database.