Cannot get mysqli bind_param bind a variable - php

I am writing following code to fetch a row from table:
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
echo 'Num rows = '.$stmt->num_rows();
Here's the code for Connection();
define('SERVER', 'localhost');
define('USER', 'root');
define('PASS', 'xxx');
define('DB', 'xxx');
class Connection{
var $mysqli = null;
function __construct(){
try{
if(!$this->mysqli){
$this->mysqli = new MySQLi(SERVER, USER, PASS, DB);
if(!$this->mysqli)
throw new Exception('Could not create connection using MySQLi', 'NO_CONNECTION');
}
}
catch(Exception $ex){
echo "ERROR: ".$e->getMessage();
}
}
}
If I echo the query and run it on Navicat with ID equal to the value of $_SESSION['id'], it does return me a row. But on the web-page, it show output as:
Num rows = 0
What's wrong with the code? Plz note that echo $_SESSION['id'] displays the value.
Thanks

Store your result set with store_result(), then access $stmt->num_rows as a property, not a method. (don't use ())
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
// Call store_result() before accessing num_rows()
$stmt->store_result();
// And access num_rows as a property, not a method
echo 'Num rows = '.$stmt->num_rows;

Related

How to use a created database class to query data from MySQL database

I have difficulties to select data, and even to put data in my database when I use classes. Here are two examples, one works (without classes) and the other does not (with classes).
Let's start with the one that works.
In the file name index1.php we have these code lines.
$con = new PDO("mysql:host=localhost;dbname=database","user","pass");
echo "Connection success ";
$sql = "SELECT email FROM users WHERE email=:email";
$email= "mail#gmail.com";
$stmt = $con->prepare($sql);
//var_dump($stmt);
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;
This returns $count = 2, which is true. I have 2 users in the database with mail#gmail.com as email.
Now to the case that does not work.
This is the file Database.php
<?php
class Database{
protected $pdo;
protected static $instance;
protected function __construct(){
$this->pdo = new PDO("mysql:host".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
echo "success";
}
public static function instance(){
if(self::$instance===null){
self::$instance = new self;
}
return self::$instance;
}
public function __call($method, $args){
return call_user_func_array(array($this->pdo, $method), $args);
}
}
?>
And I use it in the file index2.php
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASS", "pass");
define("DB_NAME", "database");
include_once "Database.php";
$pdo = Database::instance();
$sql = "SELECT email FROM users WHERE email=:email";
$email = "mail#gmail.com";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;
This $count returns 0.And I get no error. I used var_dump() and $stmt->debugDumpParams() but could not found where the problem is). Am I doing something wrong ?

How to CRUD using PDO Connection?

I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.
Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");
Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}

Select or update single value using object oriented mysqli concept

I have these two methods which are used to set a flag in my users table.
I can see my setEmailSent function is working well, but isEmailSent always return 0, even its value is set to 1.
class Mydatabase{
function connect(){
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("error_log","/log/php_error_log");
error_reporting(E_ALL | E_STRICT);
error_reporting('1');
$connect_error = 'Sorry we are experiencing down time.';
$host = "some.com";
$username = "username";
$password ='password';
$db = "loginregister";
$mysqli = new mysqli($host, $username, $password, $db) or die($connect_error);
return $mysqli;
}
}
function isEmailSent($username){
//**********************************************************************************
// #Desc - will check if email already sent to the user
// #Parms - str username
// #return - details int
//**********************************************************************************
//set up database connection
$db = new Mydatabase();
$mysqli = $db->connect();
//sql statement
$sql = "SELECT `emailSent` FROM `users` WHERE `username` = ?";
//sql prepare statement
$stmt= $mysqli->prepare($sql);
//bind sql params
$stmt->bind_param('s', $username);
//sql execute statement
$stmt->execute();
//store sql result
$stmt->store_result();
//bind sql result
$stmt->bind_result($emailSent);
return $emailSent;
}
function setEmailSent($userName){
//**********************************************************************************
// #Desc - will set that email already sent to the user
// #Parms - str username
//**********************************************************************************
//set up database connection
$db = new Mydatabase();
$mysqli = $db->connect();
$stmt = $mysqli->prepare("UPDATE `users` SET `emailSent`=? WHERE `username`=?");
if ($stmt === false) {
trigger_error($mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('is', $emailSent,$userName);
$emailSent = 1;
$stmt->execute();
}
Can anyone tell me where I am wrong ???
You need to fetch data after bind_result as
$stmt->bind_result($emailSent);
$stmt->fetch();// fetch data
return $emailSent;// then return
Read bind_result

PHP PDO with Microsoft SQL Server: Prepare Statement issues?

I am fairly new to PDO. I am trying to run a query(Microsoft Sql Server). Eventually i am going to add more fields after WHERE.
$complex = 'Shipping';
$username= 'username';
$password = 'password';
try {
$conn = new PDO('sqlsrv:Server=server,1433;Database=dbname', $username, $password);
$query = "SELECT DATA FROM TrimTable WHERE COMPLEX LIKE ?";
$stmt = $conn->prepare($query, array($complex));
$stmt->execute();
while($row = $stmt->fetch())
{
echo "$row\n";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
I keep getting this error:
Fatal error: Call to a member function execute() on a non-object in
What am i doing wrong?
UPDATE
I tried this as well:
try {
$conn = new PDO('sqlsrv:Server=mzrefd39,1433;Database=ger_mapv', $username, $password);
$sth = $conn->prepare("SELECT AREA FROM TrimTable WHERE COMPLEX LIKE ?");
$sth->execute(array($complex));
$data = $sth->fetchAll();
print_r($data);
}
In my page i get Array( ). I am not getting any values?
You can use bindParam() before execute, Try this code
$conn = new PDO('sqlsrv:Server=server,1433;Database=dbname', $username, $password);
$query = "SELECT DATA FROM TrimTable WHERE COMPLEX LIKE ?";
$stmt = $conn->prepare($query); // check $complex is removed from this line
$stmt->bindParam(1, $complex);
$stmt->execute();
Use bindParam(); for condition to execute query for conditions

retrieve values mysqli_fetch

I'm trying to get the id value from a table called usuario in the database, passing $username as parameter, the function $conexion->connect() returns a mysqli object. The functions give me no errors but it doesn't return the value from database. Am I missing something? or making any mistake.
Thanks for help.
public function checkUserNameExists($username){
$conexion = new Connection();
$conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conexion->connect()->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
This is the function connect() what is located in a class file "Connection"
public function connect(){
$mysqli = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli
}
public function checkUserNameExists($username){
$conexion = new Connection();
$conn = $conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conn->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
You should store the return value of new mysqli in a variable, and then use that variable to make queries or prepares from.

Categories