Mysql statement inside a function doesn't work - php

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

Related

Cannot execute prepared statement "Fatal error: Call to a member function prepare() on null" error

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

which object is missing?

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;
}
}

When I run the PDO script alone it work fine but when I put it in a function it will not work

When I run the PDO script alone it runs just fine But when I run it in a function I get this error Fatal error: Call to a member function prepare() on a non-object. I can not figure out why it is happening.
$pid = 6;
$custid = 1;
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;
$pid = 6;
$custid = 1;
function test($custid,$pid){
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;
}
echo test($custid,$pid);
The variable $db is not visible inside your function. you need to add
function test($custid,$pid){
global $db;
[...]
}
inside your function or you should pass the db object to your function via parameter:
function test($db, $custid,$pid){
[...]
}
another nice way ist to work with the factory patterns:
create a class db with a static method dbFactory and call it whenever you need to access your db
class db {
public static function dbFactory($host, $dbase, $user, $pass) {
$pdo = new PDO("mysql:host=$host;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
$db = db::dbFactory('localhost','mydbname','myusername','mypassword');

check if user exists with php and mysql stmt

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";
}

mysqli prepared statement - nested function does not perform

Nested function inside of fetch (which is inside of another function) does not perform.
fn_smth1 is nested inside of fn_smth2 and should output result via fn_smth2
Example below is a simplified version.
function fn_smth1 ($id){
global $mysqli;
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT code FROM at WHERE id = ?")){
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->bind_result($code);
if ($stmt->fetch()){
$code_displ = $code;
}
}
$stmt->close;
return $code_displ;
}
function fn_smth2($id){
global $mysqli;
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT idx, name FROM at WHERE id = ?")){
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->bind_result($idx, $name);
if ($stmt->fetch()){
$code_displ = $name.' === '.fn_smth1($idx);
}
}
$stmt->close;
return $code_displ;
}
echo fn_smth2(1);
//expected
some name here === some code here
//received
some name here === null (function fn_smth1 does not give a value)
You're trying to execute second prepared statement, while the resultset from the first one has not been stored yet. Use mysqli_stmt::store_result() before trying to execute second statement.

Categories