I am using bind parameter mysqli function to execute the queries in php . But i want to print last executed query everytime.
public function __construct(){
$this->dbcon = new mysqli('localhost', '*****', '*****', 'db1');
}
public function get_oderlist($email){
$emailid = $this->dbcon->real_escape_string($email);
$stmt =$this->dbcon->prepare("SELECT order_id,email,phone FROM order_historynew where email=? GROUP BY order_id ORDER BY id DESC");
$stmt->bind_param('s',$emailid);
$stmt->execute();
$stmt -> bind_result($order_id,$email,$phone);
while ($stmt->fetch()) {
$Oderlist[]=array('Order_id'=>$order_id,'Useremail'=>$email,'Phone'=>$phone);
}
if($Oderlist){
return $Oderlist;
}else{
return false;
}
}
Related
[language : php]
i have a function that have three mysql prepare statements..
when call the function from Api while the function is already processing .. i want to wait that call and resume after the processing finish ...
actually my problem is ... in my function
my first mysql prepare statement select a value from database and bind that result..
the second prepare statement use that result ..
but another call select value from database without wait for the second prepare statement execute from first call...
//function sample...
public function saveSales($query1,$query2,$query3){
//query1 execute and return a result from database
//using that result execute query 2
//execute query 3
// i want to run this three querys without interrupt from another call
}
My Actual Code :
[index.php : slimframework(Api)]
$app->post('/savesalesnew', function(Request $request, Response $response){
$request_data = $request->getParsedBody();
$sm= $request_data['sm'];
$st= $request_data['st'];
$trans = $request_data['trans'];
$user= $request_data['user'];
$pass = $request_data['pass'];
$maxfind = $request_data['maxfind'];
$db = new DbOperations;
$queryPostResult = $db->saveSales($sm,$st,$trans,$user,$pass,$maxfind);
$response_data=$queryPostResult;
$response->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
});
[Db operations.php]
public function saveSales($sm,$st,$trans,$user,$pass,$maxfind){
$stmt = $this->con->prepare("SELECT emp_pass FROM emp WHERE emp_name ='$user'");
$stmt->execute();
$stmt->bind_result($password);
$stmt->fetch();
if(strcmp($pass, $password) !== 0) {
return false;
}
$stmt->close();
$mysqli = new mysqli(//connection parameters);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->autocommit(FALSE);
$stmt1 = $this->con->prepare("$maxfind");
$stmt1->execute();
$stmt1->bind_result($maxInvoice);
$stmt1->fetch();
$stmt1->close();
$sm = str_replace("#%#####23###3", $maxInvoice, $sm);
$st = str_replace("#%#####23###3", $maxInvoice, $st);
$trans = str_replace("#%#####23###3", $maxInvoice, $trans);
$mysqli->query("$sm");
$mysqli->query("$st");
$mysqli->query("$trans");
$mysqli->commit();
$mysqli->close();
return true;
}
//-----------------------------
if you have long process on server, you need a column flag in database if data ready or not. set "0" if data not ready "1" in progress "2" ready.
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;
An example of one of my queries...
public function db_query_select($query, $params, $param_types){
$dbc = $this->dbConnect();
if($stmt = $dbc->prepare($query)){
//prepared.
//move the types to the front of the param array
array_unshift($params, $param_types);
//call the bind param function with the parameters passed in by reference
//bind_param only allows by reference.
call_user_func_array(array($stmt, "bind_param"), $this->paramsToRefs($params));
//binded.
//attempt to execute the sql statement.
if ($stmt->execute()){
$result = $stmt->get_result();
$stmt->close();
$dbc->close();
return $result;
}
}
//must have failed...
return NULL;
}
how can I change stmt get_result(); to something that is accepted by shared servers/hosts without the native driver... mysqlnd.
Anyone know? without changing all of my functions that use this database function.
Thanks.
UPDATED:::: Thanks to #your common sense, See Answer.
I believe this is what I was after. Hope it helps anyone that was having the same problem as myself. PDO vs MySQLi, seems simpler... no user call func or anything like that.
DB HANDLER:
private function dbConnect(){
$config = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/NTConfig.ini');
try {
$dbc = new PDO('mysql:host='.$config['DB_HOST'].';dbname='.$config['DB_DATABASE'].'', $config['DB_USER'], $config['DB_PASSWORD']);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
return $dbc;
}
public function db_query_select($query, $params){
$dbc = $this->dbConnect();
if($stmt = $dbc->prepare($query)){
//prepared.
//attempt to execute the sql statement.
if ($stmt->execute($params)){
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
//$stmt->close();
//$dbc->close();
return $result;
}
}
//must have failed...
return NULL;
}
Outside the DBHANDLER
$query = "SELECT error_desc FROM nt_errors WHERE error_code = :ERROR_CODE LIMIT 1";
//array: holds parameters for the query.
$params = array(
':ERROR_CODE' => $code
);
$result = $db->db_query_select($query, $params);
if ($result == NULL){
$errorText = 'ERROR: Failed to retrieve error';
}
else{
//var_dump($result);
$errorText = $result['error_desc'];
PDO is not only much more user friendly than mysqli but also doesn't have any of such a nasty drawbacks. So I strongly suggest to use PDO instead of mysqli.
With DO, the function you're after should be as simple as this
function run($sql, $args = NULL)
{
$pdo = ...;//your means of getting the connection variable
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
After gettin the function's result, you can chain a fetch method to its call, fetchColumn() in your case.
Given your code is mostly procedural, let me suggest you a very simple PDO wrapper I wrote. So the full code would be:
$sql = "SELECT error_desc FROM nt_errors WHERE error_code = ?";
$errorText = DB::run($sql,[$code])->fetchColumn();
if (!$errorText){
$errorText = 'ERROR: Failed to retrieve error';
}
Here DB class is a better replacement of your dbConnect() function, and run() method is a replacement for db_query_select() that actually can be used for any query type, including insert, update or anything.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I'm on a Web Development class. They teach us to connect to MySQL database with PDO then make some methods within a class to access the PDO connection.
db_model.php
<?php
class DB {
protected $db;
function __construct() {
$this->db = new PDO("mysql:host=localhost;dbname=blog", "root", "");
}
function executeQuery($query) {
$statement = $this->db->prepare($query);
$statement->execute();
return $statement;
}
}
articles_model.php
<?php
require_once "db_model.php";
class ArticlesModel extends DB {
function getAll() {
$statement = $this->executeQuery("SELECT * FROM articles");
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function getArticle($id) {
$statement = $this->executeQuery("SELECT * FROM articles WHERE id = " . $id);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function insertArticle($article) {
$this->executeQuery("INSERT into articles (title, body, image) values ('".$article["title"]."', '".$article["body"]."', '".$article["file"]."');");
return $this->db->lastInsertId();
}
function updateArticle($article) {
$statement = $this->executeQuery("UPDATE articles SET title ='".$article["title"]."',body = '".$article["body"]."' WHERE id =".$article["id"]);
return $statement->rowCount();
}
function deleteArticle($article) {
$statement = $this->executeQuery("DELETE FROM articles WHERE id =".$article["id"]);
return $statement->rowCount();
}
}
I'm far from being an advanced PHP programmer but as much as I know is that the good practice is to use real prepared statements with placeholders not just concatenated PHP variables in SQL statements, so I came with this:
db_model.php
<?php
define('DB_NAME', 'blog');
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_CHAR', 'utf8');
class DB {
protected $db;
function __construct() {
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => TRUE
);
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
$this->db = new PDO($dsn, DB_USER, DB_PASS, $opt);
}
function executeQuery($query) {
$statement = $this->db->prepare($query);
$statement->execute();
return $statement;
}
}
articles_model.php
<?php
require_once 'db_model.php';
class ArticlesModel extends DB {
function getAll() {
$statement = $this->executeQuery('SELECT * FROM articles');
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function getArticle($id) {
$statement = $this->executeQuery('SELECT * FROM articles WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_INT);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function insertArticle($article) {
$statement = $this->executeQuery('INSERT into articles (title, body, image) values (:title, :body, :image)');
$statement->bindParam(':title', $article['title'], PDO::PARAM_VAR);
$statement->bindParam(':body', $article['body'], PDO::PARAM_VAR);
$statement->bindParam(':image', $article['file'], PDO::PARAM_VAR);
return $statement->lastInsertId();
}
function updateArticle($article) {
$statement = $this->executeQuery('UPDATE articles SET title = :title, body = :body WHERE id = :id');
$statement->bindParam(':title', $article['title'], PDO::PARAM_VAR);
$statement->bindParam(':body', $article['body'], PDO::PARAM_VAR);
$statement->bindParam(':id', $article['id'], PDO::PARAM_INT);
return $statement->fetchColumn();
}
function deleteArticle($article) {
$statement = $this->executeQuery('DELETE FROM articles WHERE id = :id');
$statement->bindParam(':id', $article['id'], PDO::PARAM_INT);
return $statement->fetchColumn();
}
}
Which method is safer/more correct to use? Am I wrong? BTW, I could have used cleaner code but wanted to keep my code as close as I could to teacher's code. (e.g. not use bindparam() everywhere but execute(array()))
EDIT:
I think properly would be:
<?php
require_once 'db_model.php';
class ArticlesModel extends DB {
function getAll() {
$statement = $this->executeQuery('SELECT * FROM articles');
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function getArticle($id) {
$statement = $this->executeQuery('SELECT * FROM articles WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_INT);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function insertArticle($article) {
$params = [
':title' => $article['title'],
':body' => $article['body'],
':image' => $article['file']
];
$statement = $this->executeQuery('INSERT into articles (title, body, image) values (:title, :body, :image)', $params);
return $statement->lastInsertId();
}
function updateArticle($article) {
$params = [
':title' => $article['title'],
':body' => $article['body'],
':id' => $article['id']
];
$statement = $this->executeQuery('UPDATE articles SET title = :title, body = :body WHERE id = :id', $params);
return $statement->fetchColumn();
}
function deleteArticle($article) {
$params = [':id' => $article['id']];
$statement = $this->executeQuery('DELETE FROM articles WHERE id = :id', $params);
return $statement->fetchColumn();
}
}
While it is safer by far to use prepared statements, the real benefit from them comes when they are applied to user inputs in SQL statements, thus protecting your code from a SQL injection attack. When you are typing values into your SQL statements directly, these benefits are not realized, thus prepared statements are not strictly necessary. You may still benefit from being able to reuse queries, however, which is another benefit to prepared statements.
That being said, it is good programming practice to use a uniform method throughout, and using prepared statements at all times will help prevent 2nd order SQL injection attacks.
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();