pdo exception "colunt not find driver in ..." - php

in mainpage.php file, I use this:
<?php
$dsn = 'mysql:host=localhost;dbname=webfilter_schema';
$username = 'root';
$password = '';
$dbh = new PDO($dsn, $username, $password); //WORKS.
and its fine. But in another php file:
<?php
class HomeController {
public $pdoObject; // handle of the db connexion
private static $instance;
public function __construct()
{
$dsn = 'mysql:host=localhost;dbname=webfilter_schema';
$user = "root";
$password = "";
$this->$pdoObject = new PDO($dsn, $user, $password);// Error line..
}
public function createLocalObject(){
$query ="INSERT INTO USERS SET NAME = ?, PASSWORD = ?,IPADDRESS=?,E_MAIL=?";
$process = $this->pdoObject->prepare($query);
$insertResult = $process->execute(array("asd","ferfr","23","sadsads#hotmail.com"));
if($insertResult)
{
return true;
}
return false;
}
}
?>
it throws an exception like
Cannot access empty property in C:\xampp\htdocs\WP\Controller\HomeController.php5 on line 25
what is it happen ?

just added language as parameter..
public function __construct() {
$dsn = 'mysql:host=localhost;dbname=webfilter_schema';
$username = 'root';
$password = '';
$options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', );
$this->pdoObjectp = new PDO($dsn, $username, $password, $options);
}
and it works.

Related

Database Connection Issue

I cannot connect to my database and I do not understand why.
I've run my php in a php checker with no errors.
I'm watching an online course and following the instructions to the letter, yet I'm getting the 'http 500 error' when I try to test and see if it works.
Heres my php:
<?php
//STEP 1. Declare params of user information
$email = htmlentities($_REQUEST["email"]);
$password = htmlentities($_REQUEST["password"]);
$test = "test";
if (empty($email) || empty($password)) {
$returnArray["status"] = "400";
$returnArray["message"] = "Missing required information";
echo json_encode($returnArray);
return;
}
//secure password
$salt = openssl_random_pseudo_bytes(20);
$secured_password = sha1($password . $salt);
//build connection
//secure way to build connection
$file = parse_ini_file("../caps.ini");
//store in php var info from ini var
$host = trim($file["dbhost"]);
$user = trim($file["dbuser"]);
$pass = trim($file["dbpass"]);
$name = trim($file["dbname"]);
// include access.php to call func from access.php file
require("secure/access.php");
$access = new access($host, $user, $pass, $name);
$access->connect();
?>
And here is the caps.ini file I made in a text editor, I've omitted the information here:
; Connection information
[section]
dbhost = omitted
dbuser = omitted
dbpass = omitted
dbname = omitted
And finally this is my php file where I reference my connection function:
<?php
//Declare class to access this php file
class access {
//connection global variables
var $host = null;
var $user = null;
var $pass = null;
var $name = null;
var $conn = null;
var $result = null;
// constructing class
function __construct($dbhost, $dbuser, $dbpass, $dbname) {
$this->host = $dbhost;
$this->user = $dbuser;
$this->pass = $dbpass;
$this->name = $dbname;
}
// Connection Function
public function connect() {
//establish connection and store it in $conn
$this->conn = new msqli($this->host, $this->user, $this->pass, $this->name);
//if error
if (mysqli_connect_errno()) {
echo 'Could not connect to database';
} else {
echo "Connected";
}
//support all languages
$this->conn->set_charset("utf8");
}
//disconnection function
public function disconnect() {
if ($this->conn != null) {
$this->conn->close();
}
}
}
Here is my folder structure as well:
My assumption is this typo around msqli vs mysqli
$this->conn = new msqli($this->host, $this->user, $this->pass, $this->name);
should be
$this->conn = new mysqli($this->host, $this->user, $this->pass, $this->name);

PDO lastInsertId returns 0

I keep getting 0 in PDO lastInsertId. Here are my codes:
public static function createNewUser($email){
$password = self::rand_string(6);
$username = explode("#", $email);
$username = $username[0];
$passwordhashed = password_hash($password. self::salt(), PASSWORD_DEFAULT);
$register = self::connect()->prepare("INSERT INTO `user`(email,username,password,password_salt,type)VALUES(?,?,?,?,?)");
$register->execute(array($email,$username,$passwordhashed,$password,'customer'));
$user_id = self::pdolastid();
if($register){
return $user_id;
}
else{
return false;
}
}
and the last insert id function is:
public static function pdolastid(){
$last = self::connect()->lastInsertId();
return $last;
}
I have tried both with the pdolastid function and with self::connect()->lastInsertId().
The connect function is:
public static function connect(){
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new \PDO("mysql:host=$servername;dbname=pw;port=3306;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $conn;
}
catch(PDOException $e)
{
$con_error = "Connection failed: " . $e->getMessage();
return $con_error;
}
}
The database has id as the primary key and is auto-increment
Someone please help

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;
}

php __construct what is wrong with this

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;

PHP mySQL connection problems

Ok, I am completely baffled.
I am setting up an OO site. I have a class that defines all my database params, as follows:
$db->host= "localhost";
$db->name= "mydatabase";
$db->user= "user";
$db->pw = "password";
The class is being instantiated correctly and the values show up in pages that appear after this class has been loaded.
BUT, when I try to connect to this database from a different class, it does not connect. Here's how I am connecting:
$dbconn = mysql_connect($db->host, $db->user, $db->pw);
mysql_select_db($db->name, $dbconn);
Everything works fine if I take out the user, pw and name variables and hard code in the correct values, but if any of them is referenced using the db construct, no connection happens. Again, the db construct appears just fine on other pages and I am seeing the variable values being presented correctly. The $db->host variable, however, always works.
Here's is how I am constructing the db class:
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host = "localhost", $name = "mydatabase", $user = "user", $pw = "password"){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
}
and then I of course do
$db = new database();
Thanks in advance for any help!
Don't use PHP4
Why don't you just use PDO
What's the point of storing password or username as a object property?
Probably the problem is a $db variable scope
How to fix all of that?
class MyClass {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function doSth() {
$this->db->query('..');
}
}
$db = new PDO('mysql:dbname=mydatabase;host=localhost', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$obj = new MyClass($db);
$obj->doSth();
I think u are not passing parameters when creating object for initializing the database class constructor.
try using
$db=new database("localhost","dbname","user","password");
and then create the class as
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host , $name , $user , $pw ){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
Also include this class as file if written separately
and for connection u can now write
$conn=mysql_connect($db->host,$db->user,$db->pw);
mysql_select_db($db->name,$conn);
Hope this helped :)
<?php
/*
link.php
Created By Nicholas English
*/
$link = null;
$connection = null;
$servername = "";
$username = "";
$dbname = "";
$pass = "";
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
$type = 3;
if ($type === 1) {
$mysqli = true;
$pdo = false;
$obj = true;
$pr = false;
} else {
if ($type === 2) {
$mysqli = true;
$pdo = false;
$obj = false;
$pr = true;
} else {
if ($type === 3) {
$mysqli = false;
$pdo = true;
$obj = false;
$pr = false;
} else {
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
}
}
}
if ($mysqli === true && $obj === true) {
$link = new mysqli($servername, $username, $pass, $dbname);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$connection = true;
} else {
if ($mysqli === true && $pr === true) {
$link = mysqli_connect($servername, $username, $pass, $dbname);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
$connection = true;
} else {
if ($pdo === true && $mysqli === false) {
try {
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $pass);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection = true;
}
catch(PDOException $e)
{
$connection = null;
echo "Connection failed: " . $e->getMessage();
}
} else {
$link = null;
$connection = null;
}
}
}
if ($connection == null && $link == null) {
$error = 1;
}
?>
Use mysqli or pdo for a more secure connection

Categories