PHP 5.2.13, MS SQL Server 2008 R2
I have a stored procedure that looks something like this:
CREATE PROCEDURE [dbo].[StoreThing]
#pid int = 0,
#data binary(236) = NULL,
AS
BEGIN
INSERT INTO thingTable (pid, data) VALUES (#pid, #data)
END
(Greatly simplified, but that's beside the point)
I'm trying to call this procedure from a PHP script, as such:
function storeThing($pid, $data) {
global $dbconn;
if(strlen($data) != 236) return false;
$proc = mssql_init('StoreThing', $dbconn);
mssql_bind($proc, '#pid', $pid, SQLINT4);
mssql_bind($proc, '#data', $data, SQLCHAR, false, false, 236);
$result = mssql_execute($proc);
if(!$result) die(mssql_get_last_message());
return true;
}
However, this is not working quite right. I get the following error when I run it:
Warning: mssql_execute() [function.mssql-execute]: message: Implicit conversion from data type char to binary is not allowed. Use the CONVERT function to run this query. (severity 16)
Obviously, the problem is the SQLCHAR type I set for the data field. However, since there is no SQLBINARY constant, I am not sure what to set it to.
Alternately, will I have to change the stored procedure to accommodate PHP? I could do that, but it seems a bit dumb.
You can use the Microsoft SQL Server API, see http://msdn.microsoft.com/en-us/library/cc793139%28SQL.90%29.aspx
Related
We have to execute an MSSQL stored procedure in order to insert a set of rows and return the result. The procedure is working perfectly as intended when executed inside the Microsoft SQL Server Management Studio. But it's not working when executed with sqlsrv_execute or sqlsrv_query in PHP. It's inserting only one row and returning no rows.
The Stored Procedure can be found Here
The PHP code is
//Here my SP required one argument. so i passed one argument. this #param and stored procedure argument name should be same(case sensitive)
$sql = " { call ResmaxCompareWithProduction ( ?,? ) } ";
$param1 = 'All';
$param2 = 'desk';
$params = array(array(&$param1, SQLSRV_PARAM_IN),array(&$param2, SQLSRV_PARAM_IN));
$stmt = sqlsrv_prepare($conn,$sql,$params);
if ($stmt===false) {
// handle error
print_r(sqlsrv_errors(),true);
}else{
if (sqlsrv_execute($stmt)===false) {
// handle error. This is where the error happens
print_r(sqlsrv_errors(),true);
}
else
{
$resultsetarr = array();
while($row = sqlsrv_fetch_array($stmt)){
$resultArray[] = $row;
}
print_r($resultArray);
// success! It never gets here, though.
}
}
I tried to var_dump the result the procedure returned and it output resource(4) of type (SQL Server Statement)
The sqlsrv_errors() returns NULL
sqlsrv_fetch_array returned boolean(false)
I even tried using sqlsrv_query instead of sqlsrv_prepare and sqlsrv_execute, but same result.
Could you guys help me figure out what the issue is and make the procedure run as intended.
I've written a rather complex stored procedure in SQL Server 2012 that I know selects "1" multiple times when executed. When I run it in SQL Management Studio, it executes and the rows of my table update correctly. However, when I use the code below to call it from PHP, it's not executing:
$Month = 2;
$Year = 2016;
$connectionInfo = array("Database"=>"Finances", "UID"=>"sa", "PWD"=>"abcd1234");
$connection = sqlsrv_connect("localhost", $connectionInfo);
if( $connection === false ) {
die( print_r( sqlsrv_errors(), true));
}
$stmt = sqlsrv_prepare($connection, "exec UpdateBudgetToMatchTransactions #Month=?, #Year=?", array(&$Month, &$Year));
if (sqlsrv_execute($stmt) === false) {
die( print_r( sqlsrv_errors(), true));
}
SQL Profiler says the following is happening on the server:
declare #p1 int
set #p1=NULL
exec sp_prepexec #p1 output,N'#P1 int,#P2 int',N'exec UpdateBudgetToMatchTransactions #Month=#P1, #Year=#P2',2,2016
select #p1
go
However, the rows are not affected in the way they are when I call the stored procedure directly. Further, if I take that block of SQL and execute it in it's entirety in SQL Management Studio, the rows change how I'd expect them to.
I appreciate any assistance in determining what I'm doing wrong.
My master stored procedure did not include one line that was already in the sub procedures. I have added this line in the master stored procedure as well and now this behaves very well.
Have a look at adding "SET NOCOUNT ON" in the beginning of the procedure and give it a try !!
I want to retreive some data from my mssql data base using the following code :
public function areaGetCities($json){
$request = json_decode($json);
$response = '';
$response->list = array();
if (!empty($request->language_id) &&
!empty($request->country_id) &&
!empty($request->postal_code)){
$this->db_stmt = new PDOStatement();
$this->db_stmt = $this->db->prepare('EXECUTE areaGetCities :language_id, :country_id, :postal_code');
$this->db_stmt->bindParam(':language_id', $request->language_id, PDO::PARAM_INT);
$this->db_stmt->bindParam(':country_id', $request->country_id, PDO::PARAM_INT);
$this->db_stmt->bindParam(':postal_code', $request->postal_code, PDO::PARAM_STR, 40);
$this->db_stmt->execute();
while ($obj = $this->db_stmt->fetchObject()){
$response->list[] = $obj;
unset($obj);
}
}
return json_encode($response);
}
if i print errorInfo() i get
Tried to bind parameter number 0. SQL Server supports a maximum of 2100 parameters.
IMSSP
-29
my problem is that i don't get any result from my database and i have to get (i ran the procedure with the same parameters and i get 2 result).
ideas ?
Edit : I edited my code. Now i get :
[Microsoft][SQL Server Native Client 11.0][SQL Server]The formal parameter "#postal_code" >was not declared as an OUTPUT parameter, but the actual parameter passed in requested >output.
CREATE PROCEDURE areaGetCities(#language_id TINYINT, #country_id INT, #postal_code VARCHAR(40))
Try using :param_name instead of #param_name both on queries and binds. This is recommended by the PDO manual.
Also, if the parameter is an output parameter, you should mark it as such:
$this->db_stmt->bindParam(':postal_code', $request->postal_code, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 40);
The param return will be at the $request->postal_code attribute.
Use :language_id instead of #language_id as it is also done in the PDO manual. The # is used for variables in SQL, so when you prepare
EXECUTE areaGetCities #language_id, #country_id, #postal_code
It's being interpreted as
EXECUTE areaGetCities NULL, NULL, NULL
Since the variables (most likely) aren't defined in SQL Server.
My problem was that postal_code contained numbers and i wanted to send it as a string because sometimes the numbers starts with 0. I changed the code to :
$this->db_stmt->bindParam(':postal_code', $request->postal_code);
and it worked like a charm.
Thanks a lot guys !
I'm trying to learn more about MySQL and how to protect against SQL injections so my research has brought me to Prepared Statements which seems to be the way to go.
I'm also working on learning how to write Stored Procedures and am now trying to combine the two. There isn't much info on this though.
At the moment in my PHP test app I have a function that calls an SP with a normal MySQL command like this:
mysql_query("CALL usp_inserturl('$longurl', '$short_url', '$source')");
How can I do the same with MySQLi and a Prepared Statement to make it as safe as possible to injections?
Thanks!
Try the following:
$mysqli= new mysqli(... info ...);
$query= "call YourSPWithParams(?,?,?)";
$stmt = $mysqli->prepare($query);
$x = 1; $y = 10; $z = 14;
$stmt->bind_param("iii", $x, $y, $z);
$stmt->execute();
You can use both of them in the same time: just make preparation with stored procedure:
//prepare and bind SP's parameters with your variables only once
$stmt=$db->prepare("CALL MyStoredProc(?,?)");
$stmt->bind_param('is',$i,$name);
//then change binded variables and execute statement
for($i=1;$i<9;$i++)
{
$name="Name".$i;
$stmt->execute();
}
Bear in mind that you should do the preparation only once (not again for each execution), then execute it more times (just change parameter value before).
This one was a bit tricky but I eventually figured out how to both use a stored procedure (using IN parameters) that uses a prepared statement and retrieve the data through PHP. This example uses PHP 7.4.6 and MySQL 8.0.21 Community edition.
Here is the Stored Procedure:
CREATE DEFINER=`root`#`loalhost` PROCEDURE `SP_ADMIN_SEARCH_PLEDGORS`(
IN P_email VARCHAR(60),
IN P_password_hash VARCHAR(255),
IN P_filter_field VARCHAR(80),
IN P_filter_value VARCHAR(255)
)
BEGIN
#Takes admin credentials (first tow paramaters and searches the pledgors_table where field name (P_filter_field) is LIKE value (%P_filter_value%))
DECLARE V_admin_id INT(11);
BEGIN
GET DIAGNOSTICS CONDITION 1 #ERRNO = MYSQL_ERRNO, #MESSAGE_TEXT = MESSAGE_TEXT;
SELECT 'ERROR' AS STATUS, CONCAT('MySQL ERROR: ', #ERRNO, ': ', #MESSAGE_TEXT) AS MESSAGE;
END;
SELECT admin_id INTO V_admin_id FROM admin_table WHERE password_hash = P_password_hash AND email = P_email;
IF ISNULL(V_admin_id) = 0 THEN
SET #statement = CONCAT('SELECT pledgor_id, email, address, post_code, phone, alt_phone, contact_name
FROM pledgors_table
WHERE ',P_filter_field, ' LIKE \'%', P_filter_value, '%\';');
PREPARE stmnt FROM #statement;
EXECUTE stmnt;
ELSE
SELECT 'ERROR' AS STATUS, 'Bad admin credentials' AS MESSAGE;
END IF;
END
And here is the PHP script
query = 'CALL SP_ADMIN_SEARCH_PLEDGORS(\''.
strtolower($email).'\', \''.
$password_hash.'\', \''.
$filter_field.'\', \''.
$filter_value.'\');';
$errNo = 0;
//$myLink is a mysqli connection
if(mysqli_query($myLink, $query)) {
do {
if($result = mysqli_store_result($myLink)) {
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
mysqli_free_result($result);
}
} while(mysqli_next_result($myLink));
}
else {
$errNo = mysqli_errno($myLink);
}
mysqli_close($myLink);
You might find the following answer of use:
MySql: Will using Prepared statements to call a stored procedure be any faster with .NET/Connector?
In addition:
GRANT execute permissions only so your application level user(s) can only CALL stored procedures. This way, your application user(s) can only interact with the database through your stored procedure API, they can not directly:
select, insert, delete, update, truncate, drop, describe, show etc.
Doesn't get much safer than that. The only exception to this is if you've used dynamic sql in your stored procedures which I would avoid at all costs - or at least be aware of the dangers if you do so.
When building a database e.g. foo_db, I usually create two users. The first foo_dbo (database owner) is the user that owns the database and is granted full permissions (ALL) so they can create schema objects and manipulate data as they want. The second user foo_usr (application user) is only granted execute permisisons and is used from within my application code to access the database through the stored procedure API I have created.
grant all on foo_db.* to foo_dbo#localhost identified by 'pass';
grant execute on foo_db.* to foo_usr#localhost identified by 'pass';
Lastly you can improve your code example above by using mysql_real_escape_string:
http://php.net/manual/en/function.mysql-real-escape-string.php
$sqlCmd = sprintf("call usp_inserturl('%s','%s','%s')",
mysql_real_escape_string($longurl),
mysql_real_escape_string($shorturl),
mysql_real_escape_string($source));
$result = mysql_query($sqlCmd);
I have a stored procedure:
delimiter //
create procedure userlogin(in eml varchar(50))
begin
select * from users
where email = eml;
end//
delimiter ;
And the php:
$db = new mysqli("localhost","root","","houseDB");
$eml = "tsubi#gmail.com";
$sql = $db->query("CALL userlogin('$eml')");
$result = $sql->fetch_array();
The error that I get from the browser when I run the php script:
Fatal error: Call to a member function fetch_array() on a non-object...
I am using phpmyadmin version 3.2.4 and mysql client version 5.1.41.
You have to use mysqli_multi_query, not query. Check
http://us.php.net/manual/en/mysqli.multi-query.php , they have a good example
mysqli::query returns false if the query fails (instead of returning a result object or true). You need to test whether the result actually is an object:
$sql = $db->query("CALL userlogin('$eml')");
if (is_object($sql))
$result = $sql->fetch_array();
else
printf("Error: %s\n", $sql->error);
You will probably get an error message explaining why calling the stored procedure didn*t work out.