Unable to run mysql stored procedure from php code - php

I am not able to run MySQL stored procedure from PHP, no matter what I use. I am from .Net background and not well versant with PHP.
If I try the same query from PHP it doesn't work, whereas if I try in the SQL editor in PHPMyAdmin it works fine.
<?php
$sql="SET #p0='".$path.$imageName."'; SET #p1='".$_SESSION['uid']."'; CALL `upload_image`(#p0, #p1);";
$result = mysqli_query($con,$sql);
?>
and in Mysql Phpmyadmin tried this, which worked:-
SET #p0='images/user/Ganesh_1566681875.png'; SET #p1='1'; CALL `upload_image`(#p0, #p1);
and here is my stored procedure:-
CREATE DEFINER=`root`#`localhost` PROCEDURE `upload_image`(IN `imagepath` VARCHAR(250), IN `userid` INT)
BEGIN
UPDATE user SET profile_image_path = imagepath WHERE id = userid;
END$$
DELIMITER ;
I must be able to run the stored procedure by passing value from PHP variables and it must update the database for the user.

Update
I'm not sure why you're taking the approach you have. There is no need to assign values to variables first, you can simply call the procedure directly e.g.
$sql = "CALL `upload_image`('$path.$imageName', $_SESSION['uid'])";
$result = mysqli_query($con,$sql);
Regardless, it would be far preferable to use prepared statements to protect yourself from SQL injection. Something like this:
$stmt = $con->prepare("CALL `upload_image(?, ?)");
$stmt->bind_param("si", $path.$imageName, $_SESSION['uid']);
$stmt->execute();
$result = $stmt->get_result();
Additionally, your stored procedure being only one statement means that it would be more optimal to just execute that statement directly:
$stmt = $con->prepare("UPDATE user SET profile_image_path = ? WHERE id = ?;");
$stmt->bind_param("si", $path.$imageName, $_SESSION['uid']);
$stmt->execute();
$result = $stmt->get_result();
Original Answer
Your problem is that you are trying to run three separate queries (each SET counts as a query), which mysqli_query doesn't support. You have two options, you can use mysqli_multi_query:
$sql="SET #p0='".$path.$imageName."'; SET #p1='".$_SESSION['uid']."'; CALL `upload_image`(#p0, #p1);";
$result = mysqli_multi_query($con,$sql);
Or you can run them as three separate queries:
$sql="SET #p0='".$path.$imageName."'";
$result = mysqli_query($con,$sql);
$sql="SET #p1='".$_SESSION['uid']."'";
$result = mysqli_query($con,$sql);
$sql="CALL `upload_image`(#p0, #p1)";
$result = mysqli_query($con,$sql);
The latter is probably preferred as mysqli_multi_query makes you more vulnerable to SQL injection.

Related

PHP PDO Query isn't reading bind values

So I'm trying to execute the following sql query:
$stmt = $connect->query("SELECT `FID`,`StorageID`,`DestructionDate` FROM `files` WHERE `DestructionDate` < ':date'");
$stmt->bindValue(":date",$date);
$stmt->execute();
while ($row = $stmt->fetch()) {
$fid = $row['FID'];
echo $fid . " ";
}
The above code will return all records from files, it simply ignores the WHERE statement at all, and just to be clear, when I run the same statement on phpMyAdmin it runs just fine, in fact I even tried binding the value inside the query itself like this
$stmt = $connect->query("SELECT FID,StorageID,DestructionDate FROM files WHERE DestructionDate < '$date'");
And the query was executed correctly and only gave me the records that satisfy the WHERE condition, so the error is definitely in the bindValue() and execute() lines.
From docs:
PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object
You possibly want PDO::prepare() followed by PDOStatement::execute(). (There's normally no need to painfully bind params one by one.)
Additionally, you have bogus quotes around the placeholder:
':date'
You'll note that as soon as you execute the statement because params won't match.
2 solutions :
First:
$stmt = $connect->prepare("SELECT `FID`,`StorageID`,`DestructionDate` FROM `files` WHERE `DestructionDate` < :date");
$stmt->execute(array('date' => $date);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Second:
$stmt = $connect->prepare("SELECT `FID`,`StorageID`,`DestructionDate` FROM `files` WHERE `DestructionDate` < ?");
$stmt->execute(array($date));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
In both cases, you don't need to 'quote' the string to be replaced (:date or ?) because PDO parse the value in the right type corresponding to the column to match.

Using PHP variable in SQL query

I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

mysqli prepared statement without bind_param

I have this code for selecting fname from the latest record on the user table.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sdt=$mysqli->('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
$sdt->bind_result($code);
$sdt->fetch();
echo $code ;
I used prepared statement with bind_param earlier, but for now in the above code for first time I want to use prepared statement without binding parameters and I do not know how to select from table without using bind_param(). How to do that?
If, like in your case, there is nothing to bind, then just use query()
$res = $mysqli->query('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
$fname = $res->fetch_row()[0] ?? false;
But if even a single variable is going to be used in the query, then you must substitute it with a placeholder and therefore prepare your query.
However, in 2022 and beyond, (starting PHP 8.1) you can indeed skip bind_param even for a prepared query, sending variables directly to execute(), in the form of array:
$query = "SELECT * FROM `customers` WHERE `Customer_ID`=?";
$stmt = $db->prepare($query);
$stmt->execute([$_POST['ID']]);
$result = $stmt->get_result();
$row = $result->fetch_assoc();
The answer ticked is open to SQL injection. What is the point of using a prepared statement and not correctly preparing the data. You should never just put a string in the query line. The point of a prepared statement is that it is prepared. Here is one example
$query = "SELECT `Customer_ID`,`CompanyName` FROM `customers` WHERE `Customer_ID`=?";
$stmt = $db->prepare($query);
$stmt->bind_param('i',$_POST['ID']);
$stmt->execute();
$stmt->bind_result($id,$CompanyName);
In Raffi's code you should do this
$bla = $_POST['something'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$stmt = $mysqli->prepare("SELECT `fname` FROM `user` WHERE `bla` = ? ORDER BY `id` DESC LIMIT 1");
$stmt->bind_param('s',$_POST['something']);
$stmt->execute();
$stmt->bind_result($code);
$stmt->fetch();
echo $code;
Please be aware I don't know if your post data is a string or an integer. If it was an integer you would put
$stmt->bind_param('i',$_POST['something']);
instead. I know you were saying without bind param, but trust me that is really really bad if you are taking in input from a page, and not preparing it correctly first.

Calling MySQL procedure from PHP

As an example, suppose I want to execute the following query:
SELECT * FROM posts;
Therefore, I write the following:
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_posts`(IN `zip` INT)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
SELECT * FROM posts WHERE posts.zip = zip;
END
Is the following change the only one I have to make:
mysql_query("SELECT * FROM posts");
// to
mysql_query("CALL get_posts");
...and then I can fetch rows, etc.?
you also need to supply the parameter
mysql_query("CALL get_posts(11)");
another suggestion is by using PDO extension on this.
Example of using PDO,
<?php
$zipCode = 123;
$stmt = $dbh->prepare("CALL get_posts(?)");
$stmt->bindParam(1, $zipCode);
if ($stmt->execute(array($_GET['columnName'])))
{
while ($row = $stmt->fetch())
{
print_r($row);
}
}
?>
this will protect you from SQL Injection.
Your procedure expects an input parameter, so call it with one:
$result = mysql_query("CALL get_posts(12345)");
This will supply a result resource on a successful call, then you can run a fetch loop as you would a normal query.
if ($result) {
// fetch in a while loop like you would any normal SELECT query...
}

mySQLi Prepared Statement Select with Escape Characters

I am trying to select from a mySQL table using prepared statements. The select critera is user form input, so I am binding this variable and using prepared statements. Below is the code:
$sql_query = "SELECT first_name_id from first_names WHERE first_name = ?";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == '1') {
$stmt->bind_result($_SESSION['first_name_id']);
$stmt->fetch();
} else {
$stmt->close();
$sql_query = "INSERT INTO first_names (first_name) VALUES (?)";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$_SESSION['first_name_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
Obviously my code is just determining whether or not the first_name already exists in the first_names table. If it does, it returns the corresponding ID (first_name_id). Otherwise, the code inserts the new first_name into the first_names table and gets the insert_id.
The problem is when a user enters a name with an escape character ('Henry's). Not really likely with first names but certainly employers. When this occurs, the code does not execute (no select or insert activity in the log files). So it seems like mySQL is ignoring the code due to an escape character in the variable.
How can I fix this issue? Is my code above efficient and correct for the task?
Issue #2. The code then continues with another insert or update, as shown in the code below:
if (empty($_SESSION['personal_id'])) {
$sql_query = "INSERT INTO personal_info (first_name_id, start_timestamp) VALUES (?, NOW())";
} else {
$sql_query = "UPDATE personal_info SET first_name_id = ? WHERE personal_info = '$_SESSION[personal_id]'";
}
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('i', $_SESSION['first_name_id']);
$stmt->execute();
if (empty($_SESSION['personal_id'])) {
$_SESSION['personal_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
The issue with the code above is that I cannot get it to work at all. I am not sure if there is some conflict with the first part of the script, but I have tried everything to get it to work. There are no PHP errors and there are no inserts or updates showing in the mySQL log files from this code. It appears that the bind_param line in the code may be where the script is dying...
Any help would be very much appreciated.
you should validate/escape user input before sending it to the db.
checkout this mysql-real-escape-string()

Categories