Warning: PDO::prepare() expects parameter 1 to be string, object given - php

I have been trying to convert a old mysql too pdo as I am trying to learn how pdo works, I have been working on this one file for hours now busting my head and can not figure out what is wrong, and I'm sure its a lot.
try{
$check_user_data = $dbh->query("SELECT * FROM members WHERE username = '$username'");
$stmt = $dbh->prepare($check_user_data);
$stmt->execute();
$result->bind_result($username);
$data_exists = ($check_user_data->fetchColumn() > 0) ? true : false;
if($data_exists = false){
$final_report.="This username does not exist..";
}else{
$get_user_data = $stmt->fetch(PDO::FETCH_ASSOC);
if($get_user_data['password'] == $password){
$start_idsess = $_SESSION['username'] = "".$get_user_data['username']."";
$start_passsess = $_SESSION['password'] = "".$get_user_data['password']."";
$final_report.="You are about to be logged in, please wait a few moments.. <meta http-equiv='Refresh' content='2; URL=members.php'/>";
}
}
foreach ($dbh->query($sql) as $row){
}
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
Also getting a fatal
Fatal error: Call to a member function execute() on a non-object
Not sure if the fatal is related to the warning or not.

First, change these two lines:
$check_user_data = $dbh->query("SELECT * FROM members WHERE username = '$username'");
$stmt = $dbh->prepare($check_user_data);
to:
$stmt = $dbh->prepare("SELECT * FROM members WHERE username = :username");
$stmt->bindParam(':username', $username);
This makes use of the parameter feature of prepared statements, which prevents SQL injection.
Next, PDO doesn't have a bind_result method, that's part of MySQLI. To get the results, you should do:
$get_user_data = $stmt->fetch(PDO::FETCH_ASSOC);
$data_exists = ($get_user_data !== false);
You should then remove the call to $stmt->fetch in the else block, because it will try to get the next row of results.

The fatal is definitely related to the warning; you are passing the results of $dbh->query() (which is a PDOStatementObject) into $dbh->prepare, causing $dbh->prepare to return something which is not an object.
Just move the SQL into the $dbh->prepare call and get rid of the $dbh->query() entirely.

For people who might come over here my problem was a bit different i was trying to enable a filter on doctrine/symfony project and accidentally made a mistake on the following line :
$filter->setParameter($name, $someObject);
and when i called the function getParameter($name) in addFilterConstraint function i got the same error
Warning: PDO::prepare() expects parameter 1 to be string, object given
And later on i found the mistake. the fix would be to replace the setParameter second input from $someObject to $someString something like this:
$filter->setParameter($name, 'some string which is the real value you want to get later');

Related

Call MySql Stored Procedure from PHP (PDO)

I am trying to execute a MySQL Stored Procedure using PDO connection, i tried almost everything but not able to execute it.
The SP will only insert and update. Following is the codes I tried till now.
$config = require('protected/config/main.php');
try
{
$db_adat = new PDO($config['components']['db']['connectionString'], $config['components'] ['db']['username'], $config['components']['db']['password']);
$result= $db_adat->prepare('CALL pdv()');
$a = $result->execute();
$a->fetchAll(PDO::FETCH_ASSOC);
I tried with only fetch(), with only fetchAll(), fetchObject(), with fetch(PDO::FETCH_ASSOC), with fetchAll(\PDO::FETCH_ASSOC), but I always get following error
Fatal error: Call to a member function fetchAll() on a non-object in D:\ADAT_System\www\test\protected\controllers\ExportPDVController.php on line 35
I also tried using query() instead of execute(), but that doesn't work either.
I also tried adding a (select * ) statement in SP and tried with all above "fetch" options, but got same error.
The SP takes 7 minutes to complete, but all gave error immediately, so I am guessing it never ran the SP.
I tried as following too
$result= $this->$db_adat->prepare("CALL pdv()");
$result->execute();
but the I got following error:
Object of class PDO could not be converted to string
I am not passing any parameters in SP, just a simple call. Please let me know if any more information is required.
This part of your code is wrong
$result= $db_adat->prepare('CALL pdv()');
$a = $result->execute();
$a->fetchAll(PDO::FETCH_ASSOC);
Because execute() returns a boolean upon success or failure.
You cannot use that to fetch.here is the proper way with appropriate variable names:
$stmt= $db_adat->prepare('CALL pdv()');
$success = $stmt->execute();
if($success){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}else{
echo 'failed to run sp';
}
<?php
if(isset($_POST) && !empty($_POST)){
$SearchPO = (($_POST)['SearchPO']);
}
$stmt = $pdo->prepare("CALL spPO(?)");
$stmt->bindParam(1, $SearchPO, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT|PDO::ATTR_EMULATE_PREPARES, 4000);
$stmt->execute();
do {
$result = $stmt->fetchAll();
} while ($stmt->nextRowset() && $stmt->columnCount());
?>
You must use the nextRowset() function because the next record is 'empty' without it. Source

Initializing variable from PDO query

$q = $db->query(" SELECT username FROM users WHERE userident = '1' ");
echo $q; //error
print_r $q; //prints the query information (SELECT ... etc)
How do I go about getting the specific value of the element I am querying? Say the element under column username and where userident equals '1' contains the value "Patrick"; how do I initialize this string into a variable?
//same query as above
$user = $q;
echo $user; //prints "Patrick"
Sorry if this is something so rudimentary and mundane, but I've never done this outside of a foreach() loop. I'd normally iterate through rows to print specific details. The below works, but the foreach() is unnecessary as far as I understand.
foreach($q as $p) {
$user = $p["username"];
}
echo $print; //this correctly prints "Patrick"
Surely there's a method I missed somewhere?
Using the query method pretty much defeats the purpose of using prepared statements. Plus, I believe for what you're looking for, it isn't quite right.
<?php
if (!isset($_POST['id'])) {
exit;
}
$userId = $_POST['id'];
$db = new PDO(/* Stuff */);
$sql = '
SELECT username
FROM users
WHERE id = :id';
// Get a prepared statement object.
$statement = $db->prepare($sql);
// Bind a parameter to the SQL code.
$statement->bindParam(':id', $userId, PDO::PARAM_INT);
// Actually get the result.
$result = $statement->fetch(PDO::FETCH_ASSOC);
// Close the connection.
$statement->closeCursor();
// Print the result.
print_r($result);
Alternately you can use $statement->fetchAll() to gather more than one result.
Edit: I didn't actually run this code, so you might have to tinker with it to get it working right.

How to retrieve information using PDO method [duplicate]

This question already has answers here:
How to fetch a row with PDO
(2 answers)
Closed 8 years ago.
I am building a login script using the PDO method. I would like to register some sessions from the user account. Every time I try to pull information from the database I get blank. I am new to PDO. Here is what I have so far:
try{
$conn = new PDO(...........);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM $table WHERE USER = ':user' AND pass = ':pass'";
$UpdateSql = $conn->prepare($sql);
$UpdateSql->bindValue(':user',$user,PDO::PARAM_STR);
$UpdateSql->bindValue(':pass',$pass,PDO::PARAM_STR);
$results = $UpdateSql->execute();
/*Here is where the error comes in
foreach($results as $row)
{
$_SESSION['account'] = $row['account'];
}
*/
/*I also tried this
foreach($UpdateSql as $row)
{
$_SESSION['account'] = $row['account'];
}
*/
}catch(PDOException $e){
echo $e->getMessage();
}
When I tried the first foreach() I received an error Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\drug_center\dc_login.php on line 26 and the second foreach() gave me an empty result. Can someone please explain to me where I am making my mistake?
You'll be needing the $UpdateSql->fetchAll() method. This will give you a result set which can be traversed.
Secondly you'll be specyfing the parameters trough bindValue, so you don't need the ' around the values.
$table = (in_array($table, array('table1','table2')) ? $table : false;
//make sure you put some input-validation on the $table variabel!!
if($table){
$sql = "SELECT * FROM $table WHERE user = :user AND pass = :pass";
//lose the ' around the :pass
$UpdateSql = $conn->prepare($sql);
$UpdateSql->bindValue(':user',$user,PDO::PARAM_STR);
$UpdateSql->bindValue(':pass',$pass,PDO::PARAM_STR);
$UpdateSql->execute();
foreach($UpdateSql->fetchAll() AS $row){
// do some magic
}
}else{
throw new Exception("Error: table not allowed", 1);
}
Execute is to run a stored procedure on a SQL Server, you can
$results = $UpdateSql->fetchAll($sql);
foreach ($results as $row)
//stuff
}
The function prepare() returns an object of PDOStatement class. As it says on the PHP manual, PDOStatement::execute() does not return results, it returns a boolean instead to indicate if the query was successful or not. You need to use the fetch commands the PDOStatement has.

Query returns null

Hello I've got this query to get users by email, which is an unique field in the db.
However, when i want to get the data on it, it simply returns null.
Here's the code
public function getUserByEmail($email)
{
$statement = "SELECT id_user,nome,email,permissao,activo FROM sys_users
WHERE email=$email";
try
{
$sth = $this->db->query($statement);
$sth->setFetchMode(PDO::FETCH_OBJ);
$rcs_users = $sth->fetchAll();
return $rcs_users;
}
catch(PDOException $e)
{
"DB Error".$e->getMessage();
}
}
And the respective function call
$user_rcs = $user->getUserByEmail($email);
var_dump($user_rcs); //returns null
$_SESSION['email'] = $email;
$_SESSION['user'] = $user_rcs->nome;
$_SESSION['permissao'] = $user_rcs->permissao;
And then I get this error
Notice: Trying to get property of non-object in C:\xampp\htdocs\inacesso\admin\modules\auth\authhandler.php on line 24
Glad if you could help me!
Strings in SQL have to be quoted, so unless $email arrives in the function with ' and ' around it, the SQL will error.
But you shouldn't be building SQL by mashing together PHP strings anyway. Use PDO or mysqli_* with bound parameters (and prepared statements) and that will take care of quoting (and escaping) for you.
First off, seriously have a look at PDO.
Secondly I would imagine the email column is a string. As such, you'll need to surround $email with quotes in your query (after having sanitized it vigorously of course...)
WHERE email='$email'
PDO version:
$pdo = new PDO(...);
$query = $pdo->prepare('SELECT id_user,nome,email,permissao,activo '.
'FROM sys_users '.
'WHERE email = ?');
$result = $query->execute(array($email));

Is it possible to fetch_object while using bind_param? (PHP/MySQLi)

I have a question for you guys. I'm trying to make the way that I run MySQL as secure as I can. I'm currently wondering if it's possible to fetch an object with MySQLi after I have prepared the statement, binded the parameters, and executed the statement.
Example:
$sql = $mysqli->prepare('SELECT * FROM users WHERE username = ?;');
$sql->bind_param('s', $username);
$username = 'RastaLulz';
$sql->execute();
$object = $sql->fetch_object();
echo $object->mail;
I get the following error:
Fatal error: Call to a member function fetch_object() on a non-object in C:\xampp\htdocs\ProCMS\DevBestCMS\inc\global\class.mysql.php on line 23
However, when I add "$sql->result_metadata();" I don't get an error, but it doesn't return a result (it's just NULL).
$sql = $mysqli->prepare('SELECT * FROM users WHERE username = ?;');
$sql->bind_param('s', $username);
$username = 'RastaLulz';
$sql->execute();
$result = $sql->result_metadata();
$object = $result->fetch_object();
echo $object->mail;
This is how you'd do it without binding the parameters:
$sql = $mysqli->query("SELECT * FROM users WHERE username = 'RastaLulz';");
$object = $sql->fetch_object();
echo $object->mail;
Here's my current MySQL class - just need to get the execute function working.
http://uploadir.com/u/lp74z4
Any help is and will be appreciated!
I had the same question. I found out that I could do the following:
# prepare statement
$stmt = $conn->prepare($sql)
# bind params
$stmt->bind_param("s", $param);
# execute query
$stmt->execute();
# get result
$result = $stmt->get_result();
# fetch object
$object = $result->fetch_object();
I hope that works for you, too.
I just dug around in my Database class and this is how I do it. Honestly I don't remember why I needed to do it this way and there might be a much better way. But if it helps you here is the code. I do vaguely remember being irritated about there not being a simple way to get your results as an object.
// returns an array of objects
public function stmtFetchObject(){
$rows=array(); //init
// bind results to named array
$meta = $this->stmt->result_metadata();
$fields = $meta->fetch_fields();
foreach($fields as $field) {
$result[$field->name] = "";
$resultArray[$field->name] = &$result[$field->name];
}
call_user_func_array(array($this->stmt, 'bind_result'), $resultArray);
// create object of results and array of objects
while($this->stmt->fetch()) {
$resultObject = new stdClass();
foreach ($resultArray as $key => $value) {
$resultObject->$key = $value;
}
$rows[] = $resultObject;
}
return $rows;
}
What is the ';' at the end of your statement? You are giving mysqli an invalid query and so it is not creating an object for you.
The problem is not the fetch_object, but the prepare statement.
Remove the ';' and try again. It should work like a charm.
I've never seen a query end like that.
Try instantiating the variable before binding.
I think its just good practice but use double quotes instead of single quotes.

Categories