I'm running through a tutorial where it uses MySQLi but instead I'm using PDO and I have been trying to pin the issue to why I am getting this error:
Fatal error: Call to a member function errorInfo() on string in D:\Program Files (x86)\xampp\htdocs\repos\bla\web\inboxPage.php on line 34
Here is where I am trying to call the errorInfo(), I had previously used mysql_error(); as per tutorial, but this also threw the same error. Before using errorInfo() I was looking around to see if there was a PDO equivelant to mysql_error() which lead me to what you see below - Me thinking it would work. But it didn't.
Tutorials example:
$query = "SELECT id, sender, subject, message FROM messages WHERE reciever='$user'";
$sqlinbox = mysql_query($query);
if(!$sqlinbox)
{
?>
<p><?php print '$query: '.$query.mysql_error();?></p>
<?php
}
My Example:
$sql = 'SELECT id, Sender, Subject, Message FROM privatemessages WHERE Receiver = :receiver';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':receiver', $user);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$result){
?>
<p><?php print '$sql: '.$sql.errorInfo(); ?></p>
<?php
}
Here is my connection to the database:
$servername = 'localhost';
$user = 'root';
$pass = '';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
In addition, I did try the first example from the PHP Manual website -> http://php.net/manual/en/pdostatement.errorinfo.php and found that doing so gave me:
PDO::errorInfo():
Notice: Array to string conversion in D:\Program Files (x86)\xampp\htdocs\repos\bla\web\inboxPage.php on line 37
$sql: Array
...instead.
Would appreciate some help on this as I'm clearly failing to see what is happening. Thanks in advance.
In PDO a completely different method for the error reporting have to be used. In short, PDO will report its errors already, without the need to write any code.
So just take out the error reporting part, leaving only
$sql = 'SELECT id, Sender, Subject, Message FROM privatemessages WHERE Receiver = :receiver';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':receiver', $user);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
that's all you need.
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I'm new to PHP but here's my code, and I'm getting :
Fatal error: Uncaught Error: Call to a member function bindParam() on boolean
I have tested and test, not sure what is going wrong, some pointers would really help to move on - thanks in advance.
$url_slot = parse_url($str);
$urlArray = explode('/',$url_slot['path']);
$passid = $urlArray['11']; // serial no
$deviceId = $urlArray['8'];
$passtype = $urlArray['10'];
$servername = "host";
$username = "user";
$password = "******";
$dbname = "db";
try {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO Registrations (device_id, pass_id, pass_type) VALUES
(:device_id,:pass_id,:pass_type,:created,:modified)");
$stmt->bindParam(':device_id',$device_id);
$stmt->bindParam(':pass_id',$pass_id);
$stmt->bindParam(':pass_type',$pass_type);
$device_id = $deviceId;
$pass_id = $passid;
$pass_type = $passtype;
$stmt->execute();
$conn = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO Devices (push_token) VALUES
(:push_token)");
$stmt->bindParam(':push_token',$push_token);
$push_token = $content['pushToken'];
$stmt->execute();
$conn = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Any help would be great.
Whenever you get a Fatal error for sending the wrong type to a function, print the arguments you are trying to pass on the guilty line.
Whenever the wrong type in question is a boolean, check if you wrote tests for every function return that could hurt your program if the function had failed, because a variable that contains a boolean when it shouldn't usually does because the function that gave you that value failed and returned false.
In your case, it's even more simple : The error doesn't tell you that you try to pass a boolean to a function that awaits another type, it tells you that you try to call the method bind_param(), which means that you treat a boolean as an object.
$stmt->bindParam(':device_id',$device_id);
Therefore, it is $stmt which is empty.
$stmt = $conn->prepare("INSERT INTO Registrations (device_id, pass_id, pass_type) VALUES (:device_id,:pass_id,:pass_type,:created,:modified)");
The function that returns you the value you assign to $stmt being that one, I advise you to test if $stmt is different from false right after setting it, and to print the error type and message from $conn if it isn't.
In addition to that, I get the feeling that you aren't yet accustomed to work with API, you seem to lack some experience and are also trying to use PDO exceptions while working with MySQLi. Maybe you should spend some time reading their respective docmuentations.
Stack Overflow is also filled with various questions and docs regarding both.
one specific php/mydql command is not working. the sql will not be executed, nor do I get an error message. The sql command executed by HEIDI SQL gives me no error. Query before this command are executed correct. Only this one specific isn't working. I wrote it done one by one as the others which worked perfect before. Heres the code:
$sql = "INSERT INTO users (username,password,email) VALUES(?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute(array($username, $hash, $email));
The connection.php file code:
global $conn;
$config = [
$dbname = "mysql:host=localhost; dbname=starwardb;",
$login = "root",
$password = ""
];
try {
$conn = new PDO(...$config);
} catch (Exception $ex) {
echo "ERROR: " . $ex;
}
Thank you for any advice!
The mistake was, that the hashing of the password extends the string. The Database length of the password was by 50. I have increased it to 64 and now it works fine.
From: https://stackoverflow.com/revisions/45147068/3
I know there are a lot of these questions concerning this error, but neither of the answers all over stack overflow, google etc. helped me with my problem. Maybe someone here can figure out, why this error constantly occures.
I am relatively new to PHP, so for little Applications I read a lot of tutorials and use them for my cases.
I tried to do a registration page using the following tutorial: http://www.codingcage.com/2015/11/ajax-registration-script-using-jquery-php.html
After everything isset and done, I always get the Error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 !
...when I submit the registration. So I think it has to be in this part of the code:
$qry = "SELECT * FROM geraeteuser WHERE `user_email` LIKE :email";
$stmt = $db_con->prepare($qry);
$stmt->execute(array(":email"=>$user_email));
I tried everything using backtips here and there, but no matter what I do, it doesn't work.
The full Code looks like this ("geraetestatus" is the table name):
<?php
require_once "dbconfig.php";
if($_POST)
{
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_password = $_POST['password'];
$password = md5($user_password);
try
{
$qry = "SELECT * FROM geraeteuser WHERE `user_email` LIKE :email";
$stmt = $db_con->prepare($qry);
$stmt->execute(array(":email"=>$user_email));
$count = $stmt->rowCount();
if($count==0){
$stmt = $db_con->prepare("INSERT INTO `geraeteuser`(user_name,user_email,user_password) VALUES(:uname, :email, :pass");
$stmt->bindParam(":uname",$user_name);
$stmt->bindParam(":email",$user_email);
$stmt->bindParam(":pass",$password);
if($stmt->execute())
{
echo "registered";
}
else
{
echo "Query could not execute !";
}
}
else{
echo "1"; // not available
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}?>
and in the File "dbconfig.php", that is included, there is a pdo created like this:
<?php
$db_host = ***;
$db_name = ***;
$db_user = ***;
$db_pass = ***;
try{
$dsn = "mysql:host=$db_host;dbname=$db_name";
$db_con = new PDO($dsn, $db_user, $db_pass, array(PDO::ATTR_PERSISTENT => true));
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}?>
Does anyone have any suggestions for me to make this work? I tried nearly everything I could find here and in the google answers, but nothing helped.
In your Insert query String is a Missing closing bracket at the end.
You neee to Close VALUES( ... --> ) <--
I am trying to use $dbc->connect_error to check if any error occurs while trying to connect to my databease. I always get an error page saying:
Notice: Undefined property: PDO::$connect_error in
C:\xampp\htdocs\add_products_processing.php on line 7
I am using Windows7 with XAMPP v3.2.2. The full code is shown below. I am sure that the username and the password are correct. Any advice?
<?php
$dsn = 'mysql:host=localhost;dbname=technoglance';
$username = 'root';
$password = 'password';
$dbc = new PDO($dsn, $username, $password);
if ($dbc->connect_error) {
die("Connection failed: " . $dbc->connect_error);
}
$main_class =filter_input(INPUT_POST, 'main_class');
$brand =filter_input(INPUT_POST, 'brand');
$model =filter_input(INPUT_POST, 'model');
$description =filter_input(INPUT_POST, 'description');
$quantity =filter_input(INPUT_POST, 'quantity');
$adding_date =filter_input(INPUT_POST, 'adding_date');
$sell_price =filter_input(INPUT_POST, 'sell_price');
$buying_price =filter_input(INPUT_POST, 'buying_price');
if(!empty($main_class)){
try{
$query = "INSERT INTO products (main_class, brand, model, description, quantity, adding_date, sell_price, buying_price ) VALUES ('$main_class', '$brand', '$model', '$description', '$quantity', now(),'$sell_price', '$buying_price' );";
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbc->exec($query);
echo "Thank you. The record has been sent successfully.<br><br>";
}
catch(PDOException $e){
echo $query . "<br>" . $e->getMessage()."<br><br>";
}
}
else{
echo '<h1>Please use the contact form or don\'t leave an empty field!</h1>';
}
?>
Here is what your code should be
<?php
$dsn = 'mysql:host=localhost;dbname=technoglance;charset=utf8';
$username = 'root';
$password = 'password';
$dbc = new PDO($dsn, $username, $password);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// filtering omitted
if(!empty($main_class)){
$query = "INSERT INTO products (main_class, brand, model, description, quantity, adding_date, sell_price, buying_price ) VALUES (?,?,?,?,?,?,?,?);";
$data = [$main_class,$brand,$model,$description,$quantity,$adding_date,$sell_price,$buying_price];
$dbc->prepare($query)->execute($data);
echo "Thank you. The record has been sent successfully.<br><br>";}
else{
echo '<h1>Please use the contact form or don\'t leave an empty field!</h1>';
}
PDO will report it's errors already, without any extra code required.
and you should be using prepared statements
If we have a look at the PDO manual and look up for the PDO class there is no connect_error property anywhere. But if we check mysqli manual we see it right there. You have to choose a database library and stick to it, they cannot be mixed.
I always recommend to configure PDO to throw exceptions as you already do (although connection errors in particular will always through an exception no matter your settings) and not care to catch them unless you want to do something specific with them.
There is no connect_error. You should use exception:
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Or if you do not want exception you can try errorCode and errorInfo
Making the switch to PDO from MySQL in PHP. In the past, when a query was ran and wasn't executed for whatever reason, I was able to send myself an email with the mysql_error() message in the body like so:
$query = "SELECT dogs FROM animals";
$res = mysql_query($query);
if (!$res) {
$error = "Error Message: " . mysql_error();
mail("my#email.com","Database Error",$error);
}
From that I would be alerted by an emil when something was wrong with the database on a website.
My PDO setup is as follows:
setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
I have a try catch in the PDO connection itself but I would like to get error messages for prepare and execute as they happen like so:
$query = "SELECT cats FROM animals";
$sql = $pdo->prepare($query);
if (!$sql->execute()) {
$error = "Error Message: " . (pdo error message here);
mail("my#email.com","Database Error",$error);
}
Any ideas on how to assign PDO error messages in an email subject? I'm able to get a logical error message if a prepare fails be using errorInfo() but on execute errors(such as invalid parameter counts for arrays), I can't seem to get an error message.
Thanks for any and all help.
Use try/catch
try {
$sql->execute();
} catch (PDOException $e) {
$e->getMessage(); // This function returns the error message
}
You can use:
$query = "SELECT cats FROM animals";
$sql = $pdo->prepare($query);
if (!$sql->execute()) {
$arr = $sql->errorInfo();
$error = print_r($arr, true);
mail("my#email.com","Database Error",$error);
}