Cant get stored procedure resultset via PDO PHP - php

I cant seem to get any output from my stored procedure (MYSQL) using PDO (PHP).
Stored procedure:
CREATE PROCEDURE getUserId(serviceId VARCHAR(64), serviceInput VARCHAR(32))
BEGIN
SELECT id FROM users WHERE servid = serviceId AND service = serviceInput;
END
PHP code:
$mysqlConn = mysqlPDOLogin();
$stmt = $mysqlConn->prepare("CALL getUserId(?,?);");
$stmt->bindParam(1, $USERID);
$stmt->bindParam(2, $USERPROVIDER);
$stmt->execute();
$returned_a = $stmt->fetch();
echo $returned_a['id'];
It doesnt get anything back. Ive copied the basic select code out of the stored procedure and used it directly in the PHP code and it works, but cant get it to work via stored procedure.
Any help would be appreciated...

You're not doing any apparent error checking. Prepare(), bindParam() and execute() will all alert you to errors by either returning false or throwing an exception, depending on the error reporting mode PDO is in.
I'm going to assume you're in "return false" mode.
You need to check that $stmt is a PDOStatement object, that the bindParam statements didn't return false and that execute didn't return false. If any of them did then you need to use errorCode() and errorInfo() to find out what went wrong.
Also, it looks somewhat excessive to me to be using a stored procedure for what is basically a simple query. Why not just do the following?
$stmt = mysqlConn->prepare ('SELECT id FROM users WHERE servid = ? AND service = ?');

Related

Why does mysqli_result::free_result not work on mysqli_stmt::get_result

I have the following code:
$post_title = "Some dynamic POST data";
$stmt = $conn->prepare("SELECT * FROM `posts` WHERE title=? ");
$stmt->bind_param("s", $post_title);
$stmt->execute();
$rows = $stmt->get_result()->num_rows;
$stmt->get_result()->free_result(); // throws error: commands out of sync
$stmt = $conn->prepare("... some new condition");
$stmt->bind_param(...);
$stmt->execute();
$rows = $stmt->get_result()->num_rows;
I know I can simply use $stmt->free_result, but the php docs https://www.php.net/manual/en/mysqli-result.free.php mention you can use free_result on mysqli_result object as well so why can't we use it on mysqli_stmt->get_result(), which is a result object as well?
mysqli_stmt::get_result() is not idempotent. You can only call it once. If you call it again you will get an error:
Commands out of sync; you can't run this command now
This error has nothing to do with free_result() which you probably should not be using in the way you showed anyway.
You need to store the result in a variable and only then you can perform all the operations you want.
$stmt = $mysqli->prepare("SELECT ? ");
$stmt->bind_param("s", $post_title);
$stmt->execute();
$result = $stmt->get_result();
$rows = $result->num_rows;
$result->free_result();
I would also recommend that you don't ever use free_result().
Explanation:
When mysqli makes a call to MySQL server to execute a prepared statement, the server will produce a result set. This is not the outcome of the EXECUTE call, but the actual output of the SQL. By default, mysqli prepared statements are running in unbuffered mode, which means that upon execution PHP will not fetch the results from the server. You must use one of the functions to retrieve it from the MySQL server. You can do it row by row using fetch(), you can tell PHP to buffer the result set in internal memory using store_result() or you can ask PHP to buffer the result encapsulated in a mysqli_result object using get_result(). The connection line will be busy as long as there are pending rows on the MySQL server.
Once you fetch the results from MySQL, there is nothing else to read. If you try to read again, you will get OOS error mentioned above. This is why you can't call get_result() multiple times and expect the same result. Once the data is fetched to PHP, it's gone from the line, and is now stored in PHP memory. The prepared statement can of course be executed again and a new result set will be produced.
See also mysqli - Executing statements.

How to run Transact-SQL with PHP PDO

I have a pl/sql script which is made up of multiple statments:
SET #sql = NULL;
**Select values into variable**;
**Build a statment**;
**Prepare and execute statment**;
Run directly from the my-sql database this ouputs a standard table of results.
But as I understand it, PDO has issues/limitations when it comes to running multiple statments and returns zero results for me,
what would be the best way to return this queries results as a normal result set?
My experience with PDO has been limited to standard querires so i appologise if this is the wrong approach.
First how you can pl-sql statements on MySQL DB ?
However If you have some MySQL statements, You can better create a MySQL Procedure and put code into that. Then call the procedure through PDO. Like following example from PDO Prepared Statments
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);
// call the stored procedure
$stmt->execute();

PDO PostgreSQL binding error

I found that when I'm trying to run update query with params, I'm getting error
inconsistent types deduced for parameter
Maybe that's because the type of target field (character varying), everything works fine with text column type. But I don't want to change column type only because of this. Then I was told that I should pass params directly (using bindValue or bindParam, determining the type of each value) instead of sending params array to execute method.
But when I do so I'm getting error
ERROR: bind message supplies 0 parameters, but prepared statement
"pdo_stmt_00000001" requires 1
The test code is
$Stmt = $DB->prepare("SELECT * FROM test_table WHERE test_field=:test_field");
$Stmt->bindValue(':test_field', 'test', PDO::PARAM_STR);
$Stmt->execute();
var_dump($DB->errorInfo());
So, as far as understand, binding does not work at all. Or I'm doing it wrong.
But maybe there is a way of solving it?
I'm running PHP 5.4.12 with PostgreSQL 9.2.3, libpq 8.4.16.
Well, it seems that the only solution is to cast all text values to text like this:
update test_table set test_field = :test_field::text
Otherwise error about inconsistent types is occurring.
I do it this way:
$stmt = $DB->prepare("SELECT * FROM test_table WHERE test_field=:test_field");
$stmt->execute(array(":test_field" => 'test'));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['id'];
// Or whatever you're trying to get.
}
return null;
You just have to throw in an array of parameters in the execute function, no need to add a special line for the binding.
Tell me if it works for you (or not).

Calling stored procedure with Out parameter using PDO

I've been using PDO for awhile now and am refactoring a project so that it uses stored procs instead of inline SQL. I am getting an error that I can't explain.I am using PHP version 5.3.5 and MySQL version 5.0.7.
I'm just trying to get a basic stored proc with an output to work. Here is the stored proc:
DELIMITER //
CREATE PROCEDURE `proc_OUT` (OUT var1 VARCHAR(100))
BEGIN
SET var1 = 'This is a test';
END //
Here is the code I am using to call the proc, $db is an instance of PDO:
$stmt = $db->prepare("CALL proc_OUT(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);
// call the stored procedure
$stmt->execute();
echo $returnvalue;
Simple right? However, it results in the following error:
exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1414 OUT or INOUT argument 1 for routine mydb.proc_OUT is not a variable or NEW pseudo-variable in BEFORE trigger
If I call the proc directly like so:
CALL proc_OUT(#res);
SELECT #res;
it works as expected which leads me to believe that there is a problem with how it is being called with PHP, however I can't seem to find what the issue is. I am following the instructions in the manual but am still getting this error. Could anyone suggest what I could be doing wrong? Any advice would be very much appreciated. Thanks much!
It would seem that there is a bug at work here, best solution I've found is this:
http://www.php.net/manual/en/pdo.prepared-statements.php#101993
From the comment at the link above:
$dbh->query("CALL SomeStoredProcedure($someInParameter1, $someInParameter2, #someOutParameter)");
$dbh->query("SELECT #someOutParameter");
// OR, if you want very much to use PDO.Prepare(),
// insert "SELECT #someOutParameter" in your stored procedure and then use:
$stmt = $dbh->prepare("CALL SomeStoredProcedure(?, ?)");
$stmt ->execute(array($someInParameter1, $someInParameter2));
See also this: https://stackoverflow.com/a/4502524/815386
Got it! Just add a
SELECT #outputparam;
at the end of the stored procedure, where #outputparam is the name used for the param in the stored procedure definition. If you cannot edit the stored procedure, you should do a second query, for SELECT #outputparam, with PHP PDO to get the output param value.
Tip: If you're using the deprecated DBLib to connect to SQL Server and you modified the stored procedure as suggested, you'll also need to tweak your syntax to get the output param value in the calling PHP script:
$out = 0;
$sth = $db->prepare("DECLARE #myout INT; EXECUTE mysp :firstparam, :secondparam, #myout OUTPUT;"); // the DECLARE trick is needed with DBLib
$sth->bindParam(':firstparam', $firstparam, PDO::PARAM_INT);
$sth->execute();
$sth->bindColumn(1, $out, PDO::PARAM_INT);
$sth->fetch(PDO::FETCH_BOUND);
var_dump($out); // works
You need to specify that your parameter is IN/OUT style like PHP web site example :
http://php.net/manual/en/pdo.prepared-statements.php example #5
<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";

Warning: mssql_execute(): supplied argument is not a valid MS SQL-Statement resource

I try to run one of the stored proc with php. But somehow this is always display the following error message on the screen:
"Warning: mssql_execute(): supplied argument is not a valid MS SQL-Statement resource..."
Please find below for my code for calling the stored proc in php:
$conn = mssql_connect("sql-02", "rsGreen", "abc123");
$db = mssql_select_db("Green");
$Query = "exec rpt_control #list = '".$_REQUEST['list']."',
#suburb = '".$_REQUEST['suburb']."',
#state = '".$_REQUEST['state']."',
#on_off = ".$_REQUEST['switch'];
mssql_execute($Query );
Do anyone know how is going wrong with my code?
Note: When I'm manually run the stored proc, this is working fine and no error display
mssql_execute() executes a prepared statement, not a string containing a SQL statement (which is the function of mssql_query(). You will need to prepare a statement, bind parameters into it, and execute it:
// Prepare it with mssql_init()
$qry = mssql_init("rpt_control", $conn);
if ($qry) {
// We assume these fields are all VARCHAR types...
// If not, see the type constants listed on the mssql_bind() docs...
mssql_bind($qry, '#list', $_REQUEST['list'], SQLVARCHAR);
mssql_bind($qry, '#suburb', $_REQUEST['suburb'], SQLVARCHAR);
mssql_bind($qry, '#state', $_REQUEST['state'], SQLVARCHAR);
mssql_bind($qry, '#switch', $_REQUEST['switch'], SQLVARCHAR);
// Then execute it
mssql_execute($qry);
// And free it
mssql_free_statement($qry);
}
mssql_execute() docs
mssql_bind() docs
Although it would be possible to execute your stored procedure by building a SQL string and sending it to mssql_query(), doing so is not recommended when a prepared statement can be used.
I believe you should be using the sqlsrv functions instead of mssql, but you should refer to the php documentation before asking a question here as it can probably help you get to the root of your problem. mssql_execute() requires a resource, not a string query. You either need to create a stored procedure to call mssql_init() with, or in your case you can probably use mssql_query().

Categories