Fatal error: Call to a member function bindParam() [duplicate] - php

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 months ago.
I am learning to work with PHP and have a simple problem.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$db = new PDO('sqlite:/usr/users2/mieic2009/ei09072/public_html/TP1/Delicious /Database.db');
$a = $_GET['linkRef'];
$b = $_GET['tagToAdd'];
$checkIdLink = $db->prepare('SELECT idLink FROM Links WHERE nome_L = :link_n;');
$checkIdLink->bindParam(':link_n', $a, PDO::PARAM_STR);
$checkIdLink->execute();
$linkID = $checkIdLink->fetch();
$insertLink = $db->prepare('INSERT INTO Tags (nome_T, idLink) VALUES (:addTag, :link_id)');
$insertLink->bindParam(':addTag', $b, PDO::PARAM_STR);
$insertLink->bindParam(':link_id', $linkID, PDO::PARAM_INT);
$insertLink->execute();
echo 'Tag added to the specified link!';
?>
This code should add a Tag to an existing link in a database, however I am getting this error
Fatal error: Call to a member function bindParam() on a non-object in
/usr/users2/mieic2009/ei09072/public_html/TP1/Delicious/addTag.php on
line 9
I have checked over and over and can't seem to find what's wrong with this code, I googled for this error but unfortunately the answer I found weren't helpful enough. Any help would be appreciated, this is probably a simple rookie mistake.

I would check that the $db->prepare() function executed successfully. It will return false if it did not. So you could be trying to call bindParam() on a variable that equals false
http://www.php.net/manual/en/pdo.prepare.php
Also you should put the PDO object declaration in try/catch to be sure it was successful as well, as in the first example on this page:
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

Try print_r($db->errorInfo());
Probably the prepare failed so you can't use it.

Related

Error with WordPress query using $wpdb get_results [duplicate]

This question already has answers here:
Fatal error: Uncaught Error: Call to undefined function mysql_connect()
(9 answers)
Closed 4 years ago.
I have added a post in my WordPress database with the title "titleofpost". I try to use in PHP 7 $wpdb get_results, but I get the following error:
Fatal error: Uncaught Error: Call to undefined function mysql_error().
What is wrong? Any help is appreciated.
I use the code below:
global $wpdb;
$leadTitle="titleofpost";
$sql = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%$leadTitle%'";
$post_if = $wpdb->get_results($sql) or die(mysql_error()); //here dies
thy this
global $wpdb;
$leadTitle="titleofpost";
$sql = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%$leadTitle%'";
$post_if = $wpdb->get_results($sql) or die(mysqli_error()); //here dies
mysql_* functions have been removed in PHP 7.
You probably have PHP 7 in XAMPP. You now have two alternatives: MySQLi and PDO.
Additionally, here is a nice wiki page about PDO.
Handling errors with PDO
PDO has multiple ways of handling errors.
There are three error modes for PDO.
The first is PDO::ERRMODE_SILENT. This acts much like the mysql_* functions in that after calling a PDO method you need to check PDO::errorCode or PDO::errorInfo to see if it was successful.
The second error mode is PDO::ERRMODE_WARNING. This is much the same except an E_WARNING message is also thrown.
The final error mode is PDO::ERRMODE_EXCEPTION. This one throws a PDOException when an error occurs. This is the method I recommend and will be using it for further examples.
// You can set the error mode using the fourth options parameter on the constructor
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// or you can use the setAttribute method to set the error mode on an existing connection
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//METHOD 2
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
log_error("Failed to connect to database", $e->getMessage(), $e->getCode(), array('exception' => $e));
}
//METHOD 3
try {
$dbh->query("INVALID SQL");
} catch (PDOException $e) {
log_error("Failed to run query", $e->getMessage(), $e->getCode(), array('exception' => $e));
}
According to this, then mysql_error() is deprecated since PHP 5.5.0. Perhaps try error_log() instead (and then look in the php error log).
It's probably this part of your code that causes the error: or die(mysql_error());

Trying to learn prepared statements in PHP but I cannot get it to work [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
Below is my function listRecordsMatching($accNo) which connects to my mySQL server to match all records that have a specific account number. I know my problem lies in the way I write my SQL.
My table has the following structure: (int)id, (string)cheque-no, (double)amount, (date)cheque-date, (string)customer, (int)account.
NOTE: conn() is a global function in my config file that returns the mysqli object connected to my server.
EDIT: Since the conn() function is leading to some confusion:
EDIT2: I have found the answer. After doing $stmt->execute() I must bind the results to variables to use them. $stmt->bind_results($var1, $var2, ...)
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$GLOBALS['conn'] = $conn;
function conn(){
return $GLOBALS['conn'];
}
function listRecordsMatching($accNo){
//prepare statement
$stmt = conn()->prepare("SELECT * FROM `mfs-cheque-app`.`cheques` WHERE `account` = ?");
$stmt->bind_param('i', $accNo);
$stmt->execute();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
var_dump($row) // outputs NULL
echo "<form id='records'>1";
while(true){
if (!$row) break;
$c = new Cheque($row['cheque-no'],$row['amount'],$row['cheque-date'],$row['customer'],$row['account']);
echo $c->list(); // outputs formatted html
}
echo "2</form>";
}
OUT>>> NULL<form id="records">12</form>
You are using 2 different Variables $accNo and $account ...change one of them to match the other and it will probably start working.

PDO INSERT query 500 server error [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
PHP's white screen of death [duplicate]
Closed 5 years ago.
I am new to using PDO and I am getting an http 500 server error when the form is submitted.
The php page with the processing code is in the correct folder so I don't know why its throwing up a 500 error.
There is NO url rewrite going on neither .
Here is my code:
try {
$dbh = new PDO("mysql:host=$hostname;dbname=crm",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$stmt = $db->prepare("INSERT INTO testdrives (forename, surname,phone,email,add1,add2,add3,city,county,postcode,car,date) VALUES (:forename, :surname,:phone,:email,:add1,:add2,:add3,:city,:county,:postcode,:car,:date)");
$stmt->bindParam(':forename', $_POST['forename']);
$stmt->bindParam(':surname', $_POST['surname']);
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':add1', $_POST['add1']);
$stmt->bindParam(':add2', $_POST['add2']);
$stmt->bindParam(':add3', $_POST['add3']);
$stmt->bindParam(':city', $_POST['city']);
$stmt->bindParam(':county', $_POST['county']);
$stmt->bindParam(':postcode', $_POST['postcode']);
$stmt->bindParam(':car', $_POST['car']);
$stmt->bindParam(':date', $_POST['date']);
$stmt->execute();
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Edit:
I missed the incorrect variable used for the connection being $dbh and $db in the prepare; my bad.
Original answer.
This line:
if ($dbh->query($sql)) {...}
is failing for two reasons:
Calling query() on what is already being prepared/executed.
Using a non-existant variable, $sql.
Get rid of that statement with the related brace and replace it with simply and replacing the $stmt->execute(); with:
if($stmt->execute()){
// success
} else{
// error
}
and using PDO's error handling (as you are doing now) and PHP's error reporting:
http://php.net/manual/en/pdo.error-handling.php
http://php.net/manual/en/function.error-reporting.php
Check your logs also.
Found the problem
The above code shows
$stmt = $db->prepare
Needed to be changed to
$stmt = $dbh->prepare
Thanks for help with the other issue
Quick question how to i insert into a table that has an auto increment column ?

Call to a member function bind_param() on boolean error in PHP-->MySQL [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
My code is as follows:
include('config.php');
$mysqli = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$statement = $mysqli->prepare("INSERT INTO brickTable (url, description) VALUES(?,?)");
$statement->bind_param("ss", $_POST["url"], $_POST["description"]);
I keep getting the error "Call to a member function bind_param() on boolean". I've looked all over S.O., and found several examples, but none that solved my issue. I don't see any syntax or typo errors in my code. Using a var_dump, I know that the $_POST["url"] and $_POST["description"] exist and are being received properly.
Thoughts or help?
First turn on error reporting by adding the below two lines at the top of your page. Then try printing out the exact error by doing echo $mysli->error;
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqli = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$statement = $mysqli->prepare("INSERT INTO brickTable (url, description) VALUES(?,?)");
echo $mysqli->error;
$statement->bind_param("ss", $_POST["url"], $_POST["description"]);
$statement->execute();
It will tell you the error.

php function return value wont work [duplicate]

This question already has answers here:
Fatal error: Call to a member function fetch_assoc() on a non-object [duplicate]
(4 answers)
Closed 8 years ago.
ok i have been using the mysql format for quite a while but i figured its time to transfer my site over to the new mysqli format now rather then later. im trying to re write my functions to draw stats from the database but i am getting all sorts of errors.
I have looked at countless mysqli tuts but none are very descriptive and im not quite understanding the 2 parameter rule ect. below i posted my function and includes. if anyone can tell m what im doing wrong i would appreciate it.
Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\includes\stat.php on line 7
stat.php
function getStat($stat) {
require_once 'includes/config.php';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = $mysqli->query("SELECT $stat FROM players WHERE username = '".$_SESSION['username']."'");
$row = $sql->fetch_assoc();
$result = $row['$stat'];
return $result;
}
?>
and here is the test page i am using to try and get this working.
test.php
<?php
include 'includes/login-check.php';
include 'includes/config.php';
include 'includes/database.php';
include 'includes/stat.php';
echo getStat('name');
?>
ow and please dont start posting a bunch of comments bashing on the code cause as stated before ive never used mysqli so ide rather read constructive criticism then flames like half the post around here.
Change that in your getStat function.
$result = $row[$stat];
Adapt the following code to best suit your current code...
if ($stmt = mysqli_prepare($link, "SELECT $stat FROM players WHERE username = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $_SESSION['username']);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s is the current username.");
/* close statement */
mysqli_stmt_close($stmt);
}

Categories