PHP error from bind param [duplicate] - php

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.

Related

Call MySQL stored procedure from PHP

I have looked at several examples on how to call a MySQL stored procedure from PHP but none have helped me. The stored procedure works when run inside PHPMyAdmin but I am having trouble calling it from the web.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn,"CALL standings_build()");
if (mysqli_query($conn,$sql))
header('refresh:1; url=schedule_main_scores.php');
else
echo "failed";
?>
There's 2 problems here.
You're querying twice and using the wrong variable, being $sql instead of $result.
$result = mysqli_query($conn,"CALL standings_build()");
if (mysqli_query($conn,$sql))
^^^^^^^^^^^^ calling the query twice
^^^^ wrong variable, undefined
all that needs to be done is this:
if ($result)
and an else to handle the (possible) errors.
Error reporting and mysqli_error($conn) would have been your true friends.
http://php.net/manual/en/function.error-reporting.php
http://php.net/mysqli_error
Side note: You really should use proper bracing techniques though, such as:
if ($result){
echo "Success";
}
else {
echo "The query failed because of: " . mysqli_error($conn);
}
It helps during coding also and with an editor for pair matching.

Undefined property: PDO::$connect_error

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

Call to a member function errorInfo() on string

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.

Errror recovering mysql data with php

i had installed freestyle extension in joomla (to allow php code in articles) im trying to access to a database in mysql with the next code
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password)
$sql = "SELECT id, nombre, edad
FROM Prueba";
$q = $conn->prepare($sql);
$q->execute(array('%son'));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo sprintf('%s <br/>', $r['nombre']);
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
And i get this error in the article and i dont know why this is happening
Parse error: syntax error, unexpected T_VARIABLE on line 13
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password)
should be
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
(You're missing a ';')
Also I think your code isn't going to work exactly as planned since your SQL has no variables but you attempt to pass one to $q->execute() but I'm sure you can sort out what you're trying to do yourself...

Call to a member function query() on a non-object on trying to read data

Hi I have been learning php from this book PHP Solutions Dynamic Web Design Made Easy and gotten to the part where I have to work with mysqli api for databases.After writing a connection function and running the script I get this error:
This is my code:
function dbConnect($usertype , $connectionType = 'mysqli'){
$host = 'localhost';
$db = 'phpsols';
if($usertype == 'read'){
$user = 'psread';
$pwd = 'Aleczandru1989';
}elseif($usertype == 'write'){
$user = 'aleczandru';
$pwd = 'Aleczandru1989';
}else{
exit('Unrecognized type');
}
if($connectionType == 'mysqli'){
return new mysqli($host , $user , $pwd , $db) or die ('Cannot open database');
}else{
try{
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch (PDOException $e){
echo 'Cannot connect to database';
exit;
}
}
}
$conn = dbConnect('read');
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error()); //Line 5
$numRows = $result->num_rows;
Line 5 in this case refers to $result = $conn->query($sql) or die(mysqli_error());.
What Am I doing wrong here?
The $conn object you are attempting to create with dbConnect('read'); fails. If you would do a var_dump($conn); it probably shows it is not what you aspect it to be. The error is actually describing what is wrong. You try to access the query function with '->query(..' on $conn. But $conn has to be an object reference that actually has the query function. The points where this object will be created are:
return new mysqli($host , $user , $pwd , $db)
and
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
Since you are showing a different error then
or die ('Cannot open database');
My guess it is actually gong wrong at
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
And you will catch the exception. But the echo statement is not visible anymore due to the fatal error. You will have to do some debugging there!
I have no experience with PDO, but construction of the object seems ok. (but can this help you out: http://nl1.php.net/manual/en/class.pdo.php#84751) If the construction is ok, than check if your database engine is actually running :) ?

Categories