loop variable in param - php

i'm having an error "Call to a member function bind_param() on a non-object"
on this line $stmt->bind_param("ss", $influencer_id, $campaign_id);
public function getCouponDetailsMenu($influencer_id)
{
$stmt = $this->con->prepare("SELECT id, campaign_id, campaign_name, status, type_of_campaign, client, brand, influencers, max_coupons, distributed_coupons, expired_coupons, claimed_coupons, coupon_expiry, campaign_start_date, campaign_end_date FROM tbl_campaign WHERE influencers=?");
$stmt->bind_param("s",$influencer_id);
$stmt->execute();
$stmt->bind_result($id, $campaign_id, $campaign_name, $status, $type_of_campaign, $client, $brand, $influencers, $max_coupons, $distributed_coupons, $expired_coupons, $claimed_coupons, $coupon_expiry, $campaign_start_date, $campaign_end_date);
$campaigns = array();
while($stmt->fetch())
{
$temp['id']=$id;
$temp['campaign_id'] = $campaign_id;
$temp['campaign_name'] = $campaign_name;
$temp['status']=$status;
$temp['type_of_campaign']=$type_of_campaign;
$temp['client']=$client;
$temp['brand']=$brand;
$temp['influencers']=$influencers;
$temp['max_coupons']=$max_coupons;
$temp['distributed_coupons']=$distributed_coupons;
$temp['expired_coupons']=$expired_coupons;
$temp['claimed_coupons']=$claimed_coupons;
$temp['coupon_expiry']=$coupon_expiry;
$temp['campaign_start_date']=$campaign_start_date;
$temp['campaign_end_date']=$campaign_end_date;
$temp['logo'] = $this->getDistributedEmail($influencer_id, $campaign_id);
array_push($campaigns, $temp);
}
$stmt->close();
return $campaigns;
}
}
//Method to get distributed email
public function getDistributedEmail($influencer_id, $campaign_id)
{
$stmt = $this->con->prepare("SELECT user_email_address FROM tbl_coupons WHERE influencer_id=? and campaign_id=?");
$stmt->bind_param("ss", $influencer_id, $campaign_id);
$stmt->execute();
$stmt->bind_result($eadd);
$email = array();
while($stmt->fetch())
{
$temp = $eadd;
array_push($email, $temp);
}
$stmt->close();
return $email;
}

It seems $stmt not an object. try to debug it by using var_dump($stmt); right after your prepare-call.
I think it occurred because the sql statement sent to it is not valid in the current DB.
sounds like the prepare-call fails (don't know why) and so it returns
false - false is not an object, so you can't call bind_param() on
that.
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

fixed it by putting
$stmt->store_result();
after
$temp['campaign_end_date']=$campaign_end_date;

Related

Can fetch Data inside the class but when return it's send only boolean value php PDO?

I am trying to build database class using PDO this my first time using pdo so while i am building i am stuck in this problem i was able create and connect to database using class but problem is when i am trying to execute and fetch returned data error says
Call to a member function fetch() on boolean
and yet i can do this fetching inside the class this problem arise only when i am trying to fetch returned data and i have echoed the returned data it is returning 1
This is function that's trying to return (did not use parameters just using dummy)
public function init($query,$param =[]){
if(!$this->bConnected) { $this->Connect(); }
try{
$stmt = $this->pdo->prepare('SELECT * FROM business');
$stmt->execute();
return $stmt->execute();
}catch(Exception $e){
echo $e->getMessage();
}
}
Calling to class object name is $myobj
$stmt = $myobj->init('SELECT * FROM business',$value);
while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
echo( $rows['bs_name'] ." |" .$rows['bs_id']. "<br>");
}
This is same code only difference is this is inside the class.working without any errors
public function init($query,$param =[]){
if(!$this->bConnected) { $this->Connect(); }
try{
$stmt = $this->pdo->prepare('SELECT * FROM business');
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
echo( $rows['bs_name'] ." |" .$rows['bs_id']. "<br>");
}
}catch(Exception $e){
echo $e->getMessage();
}
}
Your method returns the result of $stmt->execute() (a boolean indicating success/failure of the statement execution, not the query results).
$stmt = $this->pdo->prepare('SELECT * FROM business');
return $stmt->execute();
Instead, for the method to work the way you're using it, you need to execute the statement and then return the statement itself, not the result of execute().
$stmt = $this->pdo->prepare('SELECT * FROM business');
$stmt->execute();
return $stmt;

I keep getting error on fetch_assoc() in PHP

I am trying to create a login/register feature on my android app. One of my files contains a two functions that are being used by register and login. I keep getting an error, the same error when I try to do both. I am getting this error from my error_log file and I have tried google for a while now and can't seem to find a solution to my particular issue. The error I get is:
Call to a member function fetch_assoc() on a non-object in DB_Functions.php
and the parts I get the error are here:
Login:
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc(); <----THIS LINE
$stmt->close();
return $user;
} else {
return NULL;
}
}
Register:
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc(); <----AND THIS LINE
$stmt->close();
return $user;
} else {
return false;
}

unable to display search results OOP

This code section is used on another page where results are to be displayed.
<?php
require 'core/init.php'; //all classes are contained in here.
$general->logged_out_protect();
$search = $_POST['search'];
if ($users->user_exists($_POST['search']) == false) {
$errors[] = "Sorry that username doesn't exists";
} else
if ($users->user_exists($_POST['search']) == true) {
// i would like to display username which is in the user_exists if the above condition is met.
}
}
?>
//This is function user_exists in which i determine if username is in database then after i display the username.
public function user_exists($username) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bindValue(1, $username);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
You either use PDO and execute: http://php.net/manual/en/pdo.prepare.php
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
or mysqli and bind param and then execute: http://php.net/manual/en/mysqli.prepare.php
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
note if you use prepare:
you don't need to escape your input string
you need to use ? as placeholder or :placeholder : http://php.net/manual/en/mysqli-stmt.bind-param.php
Query debugging:
to get mysqli errors use: or die(mysqli_error($db) after your execute or query call.
solution
change the order of your execute() and bind_param() (first bind_param() then execute())
your sql query should be: "SELECT * FROM users WHERE username like '%$?%'"
Several programming suggestions.
PHP is dynamic typed, so a variable or function result value, may return different variable types, stick to single type.
In some circumstances null could be used, instead of the predefined type, for example,
returning null when a search is not found, instead of an integer value.
For PHP, use comments to determine which data type a function receives or returns.
Before.
public function user_exists($username) {
After.
public /* bool */ function user_exists(/* string */ $username) {
It doesn't change your code logic, but, helps any programmer, either you or another person, to understand the logic of the function.
When using a "try" sentence in a function that returns a value (non void function), only use a single "try" sentence.
When using a "try" sentence in a function that returns a value (non void function), declare the local variables with empty values before the "try", and make all assignaments inside the "try":
Before.
public function user_exists($username) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bindValue(1, $username);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
After.
public function user_exists($username) {
$query = null;
try{
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bindValue(1, $username);
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
This allows you to read their values in the catch section when an exception is generated,
or to clean them either in the catch sections or finally sections.
Even that the PHP enviroment is garbaged collected as: Java, ".Net", and other programming enviroments, some good "House Cleaning" is welcome, and helps you have more control of your programming logic.
When using a "try" sentence in a function that returns a value (non void function), assign the exception result to a local variable, and transfer the die to a "finally" section.
Example:
public function user_exists($username) {
$query = null;
$ExceptionMsg = "";
$AnyException = false;
try{
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bindValue(1, $username);
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
$ExceptionMsg = $e->getMessage();
$AnyException = true;
} finally{
if ($AnyException)
die($ExceptionMsg);
}
}
Cheers.

PDOStatement object with bindparam [PHP]

I have a method that I'm getting to see if a user is exists:
public function login_user($user_name, $user_password){
$this->statement = $this->conn->prepare('SELECT * FROM users WHERE user_name=:user_name AND user_password=:user_password');
$this->statement = $this->conn->bindParam(':user_name', $user_name);
$this->statement = $this->conn->bindParam(':user_password', $user_password);
$this->statement->execute();
return $this->statement->fetch(PDO::FETCH_ASSOC);
}
I have never used PDO before and I'm slightly confused. I am getting the error:
Call to undefined method PDO::bindParam().
I have seen an answer saying it's because it is part of the PDOStatement class.
By changing my code to this (removing $this->conn) fixes it:
$this->statement->bindParam(':user_name', $user_name);
$this->statement->bindParam(':user_password', $user_password);
However, I have no idea why? $this->conn is by PDO object. What have I just done to make this work?
just do
$this->statement->bindParam()
to bind your parameters, then you can call your execute statement
make the following changes to your function:
public function login_user($user_name, $user_password){
//prepare the query
$query='SELECT * FROM users WHERE user_name=:user_name AND user_password=:user_password';
$statement = $this->conn->prepare($query);
//bind the parameters
$statement->bindParam(':user_name', $user_name);
$statement->bindParam(':user_password', $user_password);
//excute & fetch the data
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
return $result;
}

Prepared statement not letting me call $mysqli->stmt_init()

I have done this before but am quite new to mysqli and prepared statements (as I'm sure you can see from this issue).
Where am I going wrong?
here is my connection function (part of the 'Connect' class)
public function site_db()
{
// Connect to MySQL
$link = mysqli_connect(SITE_HOST, SITE_ID, SITE_PW, SITE_DB);
// Check for Errors
if(mysqli_connect_errno())
{
//echo mysqli_connect_error(); //shouldnt show client specific error information.
die('Error connecting to mysql database please report.');
}
}
Heres the function which is causing the error:
public function exists ($what, $who)
{
$query = "SELECT * FROM users WHERE ? = ?";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare query
if($stmt->prepare($query))
{
// Bind Parameters
$stmt->bind_param("ss", $what, $who);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($result);
// Fetch Value
$stmt->fetch();
// catch num_rows result as variable
$username_result = $result->num_rows;
// Close Statement
$stmt->close();
}
if ($username_result != 0)
{
return true;
echo 'true';
}
else
{
return false;
echo 'false';
}
}
the error I get:
PHP Fatal error: Call to a member function stmt_init() on a non-object in somefile.php on line X
It is referring to the line:
$stmt = $mysqli->stmt_init();
am I making a stupid error here? Howcome I can't call that?
EDIT//
NOTE: I didn't make this very clear, but these two functions are within different classes.
public function site_db()
{
// Connect to MySQL
$mysqli = mysqli_connect(SITE_HOST, SITE_ID, SITE_PW, SITE_DB);
// Check for Errors
if(mysqli_connect_errno())
{
//echo mysqli_connect_error(); //shouldnt show client specific error information.
die('Error connecting to mysql database please report.');
}
return $mysqli;
}
public function exists (Mysqli $mysqli, $what, $who)
{
$query = "SELECT * FROM users WHERE ? = ?";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare query
if($stmt->prepare($query))
{
// Bind Parameters
$stmt->bind_param("ss", $what, $who);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($result);
// Fetch Value
$stmt->fetch();
// catch num_rows result as variable
$username_result = $result->num_rows;
// Close Statement
$stmt->close();
}
if ($username_result != 0)
{
return true;
echo 'true';
}
else
{
return false;
echo 'false';
}
}
How to use:
Instantiate first class that have site_db() method
$db = new Class();
Then instantiate second class that have exist() method
$query = new Class();
Then simply
$query->exist($db->site_db(), $what, $who );
it's because your $mysqli is not declared inside function exists(). Try a global $mysqli inside function exists() if your $mysqli is declared outside the function.
Or, probably better - make $mysql an new object inside your Connect class:
$this->mysqli = mysqli_connect(SITE_HOST, SITE_ID, SITE_PW, SITE_DB);
and in your function exists()
$stmt = $this->mysqli->stmt_init();

Categories