I am unable to understand why this error is popping up. I do know that the obvious reason why these kind of errors come up but I did look and re-look into my code and cannot understand why!
The error is:
Fatal error: Call to a member function prepare() on a non-object
Here are the code snippets.
db_connect.php
<?php
include_once 'psl-config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
customer.php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
.
.
.
function myCallBackFunction($array) {
//echo ".";
// print_r($array);
$amount=$array['amount'];
$date=$array['date'];
if(transaction($mysqli, $date, $amount))
{
echo "Transaction table Updated";
}
}
functions.php
//Function to insert transactions
function transaction($mysqli, $date, $amount) {
if($smt = $mysqli->prepare("INSERT INTO `tbltransaction` (entry_date,income) VALUES (?,?)
ON DUPLICATE KEY UPDATE income=income+?;"));
{
$stmt->bind_param('sii', $date, $amount, $amount); // Bind "$date" and "$amount" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows == 1) {
return true;
} else {
return false;
}
}
}
tbltransaction
Column Type Null Default Comments MIME
entry_date date No
income int(11) No
P.S: another function in the functions.php file is working just fine, here is the function and the way I am calling it
function
//Function to display notice
function notice($mysqli) {
$notice = null;
if ($stmt = $mysqli->prepare("SELECT notice FROM tblnotice ORDER BY ID DESC LIMIT 1")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($notice);
$stmt->fetch();
return $notice;
}
}
calling the function
<?php echo notice($mysqli); ?>
This is a variable scope issue - you need to pass the $mysqli object in to the myCallBackFunction function as a second parameter or it won't be set inside that function.
Like this:
function myCallBackFunction($array, $mysqli) {
Then where you call that function you'll need to pass in the $mysqli object:
myCallBackFunction($array, $mysqli);
you do alternatively
function notice() {
global $mysqli;
$notice = null;
if ($stmt = $mysqli->prepare("SELECT notice FROM tblnotice ORDER BY ID DESC LIMIT 1")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($notice);
$stmt->fetch();
return $notice;
}
}
Related
I tried the questions with similar titles, but they are all regular queries that are not in functions.
I am trying to create an update function in a Database class so I don't have to write out the entire process over and over. However, I am getting the error:
Invalid parameter number: number of bound variables does not match number of tokens
Here is my function.
public function updateRow($query, $params) {
try {
$stmt = $this->master_db_data->prepare($query);
foreach($params as $key => $val) {
$stmt->bindValue($key+1, $val);
$stmt->execute();
return true;
}
} catch(PDOException $e) {
die("Error: " . $e->getMessage());
}
}
And its usage:
$query = "UPDATE records SET content=?, ttl=?, prio=?, change_date=? WHERE id=?";
$params = array($SOA_content, $fields['SOA_TTL'], '1', $DATE_TIME, $id);
if($db->updateRow($query, $params)) {
echo "Success";
}
else {
echo "Fail";
}
Doing it without a function works:
$pdo = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$query = "UPDATE records SET content=:content, ttl=:ttl, prio=:prio, change_date=:change_date WHERE id=:id";
$stmt = $pdo->prepare($query);
$stmt->bindValue(":content", $SOA_content);
$stmt->bindValue(":ttl", $fields['SOA_TTL']);
$stmt->bindValue(":prio", 1);
$stmt->bindValue(":change_date", $DATE_TIME);
$stmt->bindValue(":id", $id);
$stmt->execute();
Am I wrong with my bindValue in the function? If so, how?
Always make sure your execute calls happen after all binding has been performed. In this situation, move the execute out of the binding loop.
So I have this code
$lang=new language();
$default_language=$lang->getLanguage(0);
$currencies = new currency();
$currencies = $currencies->getCurrencies();
getCurrencies() and getLanguage() are in another file with classes.
public function getCurrencies() {
$curr=new record();
return $curr -> getRecords('currencyTable','currency_order',array("currency_id","currency_name"));
}
public function getLanguage($record) {
$lang=new record();
return $lang->getRecord('languageTable',$record,'lang_order','*');
}
And getRecords and getRecord are public functions it the record class
I keep on getting the error
Fatal error: Call to a member function prepare() on null
Referring to the query of the getRecords functions.
I dont know how to fix this. Does this has to do with the connection to the database?
Also, the weird part is that if I remove the
$lang=new language();
$default_language=$lang->getLanguage(0);
part, this error goes away. Any help? Is the error in the $default_language=$lang->getLanguage(0); line and this is why it is messing up the database connection, resulting to this error?
Thanks
EDIT
Here are the getRecord and getRecords
public function getRecords($table,$sorder,$field_names) {
$conn = db::open();
//- build string of field names
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//end up with field1, field2... or *
//soreder is a field, contains int like 1 2 3
//- run statement
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
and
public function getRecord($table,$record,$sorder,$field_names) {
$conn = db::open();
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//same things for $field_string and $sorder
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." LIMIT ? OFFSET ?");
$stmt->bindValue(1, 1 , PDO::PARAM_INT);
$stmt->bindValue(2, $record, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
}
I fixed an error. In getRecord I had LIMIT 1 and I fixed it as above. I still get the same error about the getRecords line : $stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
Any thoughts?
Thanks
Your database connection failed. The error is not in your posted code. The error in your code is when the statement is being prepared.
Ex: $statement = $dbh->prepare("SELECT * FROM some_table"). I would recommend throwing an exception to see what's going wrong with your connection. You can do this by adding the options to your pdo initialization. array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
try{
$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB,
MYSQL_USERNAME,
MYSQL_PASSWORD,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}catch(Exception $e){
echo $e->getMessage();
}
Hope this helps
I am having some trouble with prepared statements. Basically, this query is returning no rows, even though I know for a fact that this query should return multiple rows. I thought this was just a problem due to SQL injections, but maybe I'm doing something else wrong here, I don't know. If I take out the check for how many rows there are, I get an error:
PHP Fatal error: Call to a member function fetch_array()
Any help would be appreciated!
$stmt = $mysqli->prepare("SELECT sid from SDS WHERE uid=? AND dst=?");
$stmt->bind_param('ss',$username,$structureType);
$stmt->execute();
$stmt->bind_result($results);
$stmt->fetch();
if ($results) {
if($results->num_rows == 0) {
print("No results here.");
return 0;
}
$recordnames = array();
while ($next_row = $results->fetch_array()) {
$recordnames[] = $next_row['sid'];
}
return $recordnames;
}
When you use $stmt->bind_result($result); you are binding the sid from the database to the variable $results. So you cannot perform operations like :
if($results->num_rows == 0) { //... }
or
$results->fetch_array();
This is how I would do it :
<?php
$stmt = $mysqli->prepare("SELECT sid from SDS WHERE uid=? AND dst=?");
$stmt->bind_param('ss', $username, $structureType);
$stmt->execute();
$stmt->bind_result($sid);
$stmt->store_result();
if ($stmt->num_rows == 0)
{
print("No results here.");
$stmt->close();
return 0;
}
else
{
$recordnames = array();
while($stmt->fetch())
{
$recordnames[] = $sid;
}
return $recordnames;
}
?>
This way uses a different logic, check if the row count is 0, if so display "No results here", if not put results into the array.
I'm creating an authentification file with php and mysql, but I have this mistake in this line:
$stmt2->bind_param('ss',$twitter_id, $name);
The error message is
Call to a member function bind_param() on a non-object in ...
Where's my mistake?
$name in my database is a VARCHAR
$twitter_id in my database is a VARCHAR
$bd is my database connection
If a user is already registered, it should show me a message saying "User already registered", and if the user isn't registered, it should insert a new id and name in my database.
session_start();
if (!isset($_SESSION['userdata'])) {
header("location: index.php");
} else {
$userdata = $_SESSION['userdata'];
$name = $userdata->name;
$twitter_id = $userdata->id;
$stmt = $bd->prepare("SELECT ID_TWITTER FROM USERS");
$stmt->execute();
$stmt->bind_result($checkUser);
if ($stmt->fetch()) {
if($checkUser!==$twitter_id){
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME) VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss',$twitter_id, $name);
$stmt2->execute();
$stmt2->close();
} else {
echo "User already exits";
}
}
$stmt->close();
}
Could it be a typo? does $bd exist or should it be $db ?
Shameless plug: I do this exact thing in a project I have on github. Feel free to use the classes for whatever you like; they are mostly copy-pastable.
Your real issue is that $bd->prepare() returned false.
Check that you actually called it correctly and set it to new mysqli(*params)
The error Call to a member function ... on a non-object in ... means that $db is not an object, which means that it was not instantiated to an object. Thus, $this->method() isn't possible. bind_param(string $format, mixed &*vars); uses pass-by-reference and if this fails, it throws an error.
Try it yourself by sticking this in there:
$stmt->bind_param("ss", "string", "string");
To get around this issue where it can fail, check if $db->prepare() returns true:
if ($query = $bd->prepare($sql)) {
//stuff
}
In addition, in the first query you do it is probably not a good idea to be adding the overhead of a prepare for a single query that only checks row count without user input.
Solved : it works now
$stmt = $bd->prepare("SELECT ID_PROVIDER FROM USERS WHERE ID_PROVIDER = ?");
$stmt->bind_param('s', $twitter_id);
$stmt->execute();
$stmt->bind_result($checkUser);
while ($stmt->fetch()) {
$result = $checkUser;
}
if (empty($result)) {
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME)
VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss', $twitter_id, $name);
$stmt2->execute();
$stmt2->close();
}else {
echo "User already exits";
}
I have a MySQL statement in a function but somehow it doesn't work. I get the following error:
Fatal error: Call to a member function
prepare() on a non-object in
D:\xampp\test.php on line 7
function isloggedin($getcookiedata) {
$data = explode("|", $getcookiedata);
$userid = $data[0];
$md5password = $data[1];
$sql = "SELECT user_id, username, email, newsletter, user_group FROM users WHERE user_id = ? AND md5password = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $userid, $md5password);
$stmt->execute();
$stmt->bind_result($r_userid, $r_username, $r_email, $r_newsletter, $r_user_group);
$stmt->store_result();
$checker = $stmt->num_rows;
$stmt->fetch();
$stmt->close();
}
When I just do the SQL statement outside a function, it works. But not inside the function.
If $mysqli is a global you're defining somewhere, you need to pull it into your function's scope with:
function isloggedin($getcookiedata) {
global $mysqli;
...
}
See PHP - Variable scope