PHP Error Object of Class Could Not Be Converted to String - php

I am trying to create a PHP file that connects to a mysql database and inserts data into the database. I am getting these errors:
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in ( ! ) Notice: Undefined variable: host in C:\wamp\www\final_kk.php on line 21
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in C:\wamp\www\final_kk.php on line 21
Line 21 is the first line inside of the try. Any help would be appreciated. Thanks!
<?php
class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db) {
parent::__construct($host, $user, $pass, $db);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
}
$db = new foo_mysqli('localhost', 'root', '', 'users');
echo 'Success... ' . $db->host_info . "\n";
try {
$conn = new PDO("mysql:host=$host;dbname=$db;username=$user;password=$pass", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname, lname,email,username,password,SSN) VALUES ('$fname', '$lname', '$email', '$uname', '$password', '$ssn')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$db->close();
?>
Okay....I made some changes based on the comments and my code now looks like this:
<?php
class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db) {
parent::__construct($host, $user, $pass, $db);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
}
$db = new foo_mysqli('localhost', 'root', '', 'users');
echo 'Success... ' . $db->host_info . "\n";
settype($host, "string");
settype($user, "string");
settype($pass, "string");
try {
$conn = new PDO("mysql:host=$host;dbname=$db, $user, $pass");
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname, lname,email,username,password,SSN) VALUES ('$fname', '$lname', '$email', '$uname', '$password', '$ssn')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$db->close();
?>
This got rid of one of my errors however I still get
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in C:\wamp\www\final_kk.php on line 33
please help...what am I doing wrong?

You're setting $db as an instance of a foo_mysqli() object in this line:
$db = new foo_mysqli('localhost', 'root', '', 'users');
Later in
$conn = new PDO("mysql:host=$host;dbname=$db;username=$user;password=$pass", $user, $pass);
you're using $db as a database name. It's enclosed in a double-quoted string, so PHP will attempt to interpolate it and substitute a string in the PDO connection string. Since $db is now an object, it fails.
It's not clear why you're setting up an object that extends MySQLi when you're later using a PDO object anyway.
Additionally, you haven't defined $host in the scope where you're setting up your PDO connection, so PHP reports that as undefined.
Since you know what the host and database names are you could just do this:
$conn = new PDO("mysql:host=localhost;dbname=users;", $user, $pass);

Related

connection with database with OOP mysqli extending class

I know must coding part of mysql bt new at mysqli. I am not able to execute these insert query to the database. I have searched a lot but couldn't find simple suggestion, or may be i didn't understand.
Undefined variable: mysqli in C:\wamp\www\New folder\php\msqliconnect.php on line 32
Fatal error: Call to a member function mysqli_query() on a non-object in C:\wamp\www\New folder\php\msqliconnect.php on line 32
Any help is appreciated.
<?php
class connection
{
public $mysqli;
function connect()
{
$hostname = "localhost";
$username = "root";
$password = "";
$database = "demodatabase";
$mysqli = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
}
class Index extends connection
{
function __construct()
{
parent::connect();
}
function insertdata($a, $b)
{
// echo $a. ' ' .$b;
// MySqli Insert Query
$status = 0;
$insert_row = $mysqli->mysqli_query("INSERT INTO tb_user (id, user, password, status) VALUES('','" . $a . "', '" . $b . "', '')");
if ($insert_row)
{
print 'saved';
}
else
{
die('Error : (' . $mysqli->errno . ') ' . $mysqli->error);
}
}
}
?>
In both of your connect() and insertdata() methods, you're using local variable $mysqli, not the instance variable public $mysqli;. You should use $this->mysqli instead of $mysqli in your instance methods. So your connect() and insertdata() methods would be like this:
function connect(){
$hostname = "localhost";
$username = "root";
$password = "";
$database = "demodatabase";
$this->mysqli = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
and
function insertdata($a, $b){
$insert_row = $this->mysqli->query("INSERT INTO tb_user (id, user, password, status) VALUES('','".$a."', '".$b."', '')");
if($insert_row){
print 'saved';
}else{
die('Error : ('. $this->mysqli->errno .') '. $this->mysqli->error);
}
}
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

how to convert mysqli_set_charset($conn,"utf8") into PDO format in MYSQL?

I trying to solve the UTF8 problem. So far i manage to test out and it works in mysqli connection.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tesddddt";
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM customer";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["uid"]. " - Name: " . $row["username"]. " " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
I manage to Insert and Select data with characters shown in it's language format correctly with the above coding.
However, when I try to do it in PDO , it shows 1 error when I insert data.
public function __construct(){
try {
$conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user_name, $this->db_pass);
mysqli_set_charset($conn,"utf8"); // <- added here
$this->conn=$conn;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
I got this error
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, object given in...
My php project is using PDO and hence need to get this work in PDO format. Anyone know how to settle this?
You try to connect via PDO and then change the charset via mysqli, without having a mysqli connection, that is what's causing the warning.
In PDO the charset usually is being specified within the connection string, like this:
$conn = new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8");

PDO - "Call to a member function fetch() on a non-object"

I know that error occurs usually when query returned false but this time this occurs with no reason! (or just I'm making a big mistake)
if(!$security_SenderId){
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?'");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
}else{
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?' AND `ticket_sender` = '?'");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
}
if($getbaseticket === false){
return false;
}else{
$baseticket = $getbaseticket->fetch(PDO::FETCH_ASSOC);
}
I've theese lines in a function that returns support ticket information as array but as I said the error occurs when I tried to fetch the ticket information. I tried to check mysql errors just before fetch line by enabling the pdo debug mode and db->errorInfo() but it didn't work.
What can the problem be here?
Edit:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
class TICKET_MANAGER
{
function __construct($dbhost, $dbname, $dbuser, $dbpass) {
try{
$this->db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Connection failed: ' . $e->getMessage() );
}
}
function viewTicket($ticket_safeid, $security_SenderId = false)
{
try{
if(!$security_SenderId){
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ?");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
}else{
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ? AND `ticket_sender` = ?");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
}
}catch(PDOException $e){
die('Mysql error: ' . $e->getMessage() );
}
...
}
...
}
It's the quotes around all your '?' - Remove them.
Read the manual
http://php.net/pdo.prepared-statements
from the manual:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
Exceptions should have told you that error
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
and used right after you've connected to your DB.
-http://php.net/manual/en/pdo.error-handling.php
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Query:
try {
// your query
}
catch(PDOException $e){
print $e->getMessage();
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.

Call to a member function setFetchMode() error

I've been getting this error,
"Fatal error: Call to a member function setFetchMode() on a non-object in C:\Users\Public\wamp\www\audiotextCSVUpload\modified.php on line 34".
Can you please help me what is causing the error. In one of my computer, it is ok, but in our office, the error exists. Find below the code:
<?php
require_once 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = 'SELECT phone, last_name, first_names
FROM contacts';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
check for error
$q = $conn->query($sql);
if (!$q) {
echo "\nPDO::errorInfo():\n";
print_r($conn->errorInfo());
}
It seems the problem is with your query, table contacts do not exists or the fields you are retrieving aren't correct.
It's a good idea to add exceptions to PDO, add this after $conn
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
And check for the error

PHP checking mysql connection

I am building a project with installation (suck as WordPress) and the user provides database information (server, username, password and database). Now, I have to check if it can connect to the provided database. I tried this code, but it seems that it does not work (I am using Mysqli btw):
public function checkDataBaseConnection($server, $user, $pass, $db)
{
$conn = #mysqli_connect($server, $user, $pass, $db);
if(mysqli_connect_error())
{
return FALSE;
}
else
{
mysqli_close($conn);
return TRUE;
}
}
What other way can I use to check if the server can connect to the database?
One thing: Remove the #, that suppresses some php warnings.
Second thing: Try this:
public function checkDataBaseConnection($server, $user, $pass, $db)
{
$conn = #mysqli_connect($server, $user, $pass, $db);
if(!$conn)
{
return FALSE;
}
else
{
//mysqli_close($conn); why would you close the connection?
return $conn;
}
}
Have you tried something like this?
if (checkDataBaseConnection($server, $user, $pass, $db))
echo "Success!";
else
echo "Fail.";
By the way you just can do this way
mysqli_connect($server, $user, $pass) or die('Connection failed');
Well, if you look at the PHP page for mysqli_connect you can see this example:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>

Categories