Object couldn't be converted to string - php

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

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

Call to a member function query() on null with PDO

I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}

Php class inside connection close or class close?

i have php class USER and Database class im doing 10000 users app, and that user will be query 3-4 times a day minumum . my class base and function base here them looking yet for thats have any problem ? or need any fix ?
MY db class
class Database
{
private $host = "";
private $db_name = "";
private $username = "";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
print'{"success": "0","message": "Service Error, Please try again later "}';
}
return $this->conn;
}
}
Also my USER class here
<?php
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID)
{
try
{
$stmt2 = $this->conn->prepare("UPDATE Products SET productCode='$code',productName='$name',productDescription='$description',specialWarning='$specialwarning',productQuantity='$quantity',productPrice='$price' WHERE ID=$productID");
$stmt2->execute();
echo'{"success": "1", "message": "Product Updated"}';
return true;
}
catch(PDOException $e)
{
}
$this->conn = null; // HERE I DID NULL FOR DISABLE MAX CONNECTIONS
}
}
AND HER MY updateproduct.php
<?php
header('Content-type: application/json');
$name = $_REQUEST['name'];
$code = $_REQUEST['code'];
$description = $_REQUEST['description'];
$quantity = $_REQUEST['quantity'];
$price = $_REQUEST['price'];
$specialwarning = $_REQUEST['specialwarning'];
$productID = $_REQUEST['productID'];
include_once 'class.user.php';
$user = new USER($DB_con);
if($user->updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID))
{
}
else
{
}
?>
Can you check my codes is good class for big users ? and good connection returns ? Can i add something ? or need any fix ?Also need to close class ?
Thanks

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

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.

Categories