mysql stored procedures using php - php

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.

Related

sqlsrv_query returns false without any error (sqlsrv_errors())

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.

Call MySql Stored Procedure from PHP (PDO)

I am trying to execute a MySQL Stored Procedure using PDO connection, i tried almost everything but not able to execute it.
The SP will only insert and update. Following is the codes I tried till now.
$config = require('protected/config/main.php');
try
{
$db_adat = new PDO($config['components']['db']['connectionString'], $config['components'] ['db']['username'], $config['components']['db']['password']);
$result= $db_adat->prepare('CALL pdv()');
$a = $result->execute();
$a->fetchAll(PDO::FETCH_ASSOC);
I tried with only fetch(), with only fetchAll(), fetchObject(), with fetch(PDO::FETCH_ASSOC), with fetchAll(\PDO::FETCH_ASSOC), but I always get following error
Fatal error: Call to a member function fetchAll() on a non-object in D:\ADAT_System\www\test\protected\controllers\ExportPDVController.php on line 35
I also tried using query() instead of execute(), but that doesn't work either.
I also tried adding a (select * ) statement in SP and tried with all above "fetch" options, but got same error.
The SP takes 7 minutes to complete, but all gave error immediately, so I am guessing it never ran the SP.
I tried as following too
$result= $this->$db_adat->prepare("CALL pdv()");
$result->execute();
but the I got following error:
Object of class PDO could not be converted to string
I am not passing any parameters in SP, just a simple call. Please let me know if any more information is required.
This part of your code is wrong
$result= $db_adat->prepare('CALL pdv()');
$a = $result->execute();
$a->fetchAll(PDO::FETCH_ASSOC);
Because execute() returns a boolean upon success or failure.
You cannot use that to fetch.here is the proper way with appropriate variable names:
$stmt= $db_adat->prepare('CALL pdv()');
$success = $stmt->execute();
if($success){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}else{
echo 'failed to run sp';
}
<?php
if(isset($_POST) && !empty($_POST)){
$SearchPO = (($_POST)['SearchPO']);
}
$stmt = $pdo->prepare("CALL spPO(?)");
$stmt->bindParam(1, $SearchPO, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT|PDO::ATTR_EMULATE_PREPARES, 4000);
$stmt->execute();
do {
$result = $stmt->fetchAll();
} while ($stmt->nextRowset() && $stmt->columnCount());
?>
You must use the nextRowset() function because the next record is 'empty' without it. Source

Can I call Two procedure in php?

I am using procedure in php. There are two procedure. First procedure is calling but second procedure is not working. When I comment the first procedure then second is working.
I don't know the that two procedure are called at a time or not. please tell me the way. I am new for procedure. Please help me.
if(isset($_REQUEST['customer'])){
$customer_name = $_POST['customer_name'];
$lang = 'en';
$qry = mysql_query("call customer (NULL,'$customer_name','$lang')")
or mysql_error();//first procedure
$data = mysql_num_rows($qry);
if($data > 0){
$msg ="Customer already exists.";
}
else{
mysql_query("call insertCustomer(NULL,'$customer_name','','','',1,'','','','',#ret,#err_code)")
or mysql_error();//second procedure
$rs = mysql_query('SELECT #p_ret,#p_err_code')or mysql_error();
$data = mysql_fetch_array($rs);
echo $data['#p_err_code'];
echo $data['#p_ret'];
}
}
First of all you should not be using mysql but mysqli or PDO - mysql is deprecated and support for this will be withdrawn.
Secondly your question is not specific: the second procedure might not be called at all because if ($data > 0) returns true and in this case that would be ok.
Try to improve your code for debugging purposes - your calls to mysql_error() are pointless as the function returns error as a string or empty string if no error but you don't echo it out or assign it to any variables. Also would be good to save the result of mysql_query (mysqli_query rather) to a variable and then test if it worked or not.

Why is $rs->RowCount not returning a value?

I'm using a basic SQL query with ADO and PHP but the row count always returns -1. What am I missing?
Here is my code:
include 'constants.php';
// Create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
// Open the connection to the database
$conn->open(DB_CONN_STR);
$query = "select * from table_name";
$rs = $conn->execute($query);
if (!$rs) {
return;
}
else {
return $rs->RecordCount();
}
I know this table has values...what am I missing?
The manual says why.
http://phplens.com/lens/adodb/docs-adodb.htm#recordcount
seems you have set
$ADODB_COUNTRECS = false
I had a similar problem using Adodb with PHP, with a PDO mssql driver.
I executed a SQL query with GetOne or LimitQuery in a try / catch block
the query resulted in an error
i caught the exception and went on to execute a valid query with Execute
the resulting calls to RecordCount would wrongly return -1 (but i could iterate on the rows).
I found out that some Adodb functions set that $ADODB_COUNTRECS flag to false before executing their query. In case of an error the flag was not set back to true, and that is why RecordCount returned -1.
I set the global variable to true in my exception constructor and that solved the problem.

PEAR MDB2 executeStoredProc and returning a result set. Possible? Worth it?

I've been trying to make this work for the last couple of hours. I have a simple stored proc called get_log_entries:
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_log_entries`(p_min_id INT)
BEGIN
SET p_min_id = IFNULL(p_min_id, -1);
SELECT * FROM db_log WHERE item_id > p_min_id;
END
It's dead simple and it returns results in two columns: item_id (int) and log_description (varchar).
I am trying to execute this using MDB2 object, but so far no luck. Here's the code that is trying to do it:
$conn = MDB2::factory('mysql://myUser:myPassword#localhost/my_db');
if (PEAR::isError($conn)) {
die ("Cannot connet to DB(10): " . $conn->getMessage());
}
// loading the Function module
$conn->loadModule('Function');
$params = array('null');
$result = $conn->executeStoredProc('get_log_entries', $params);
if (PEAR::isError($result)) {
$msg = $result->getMessage() . "<br /><br />" . $result->getUserInfo();
die ($msg);
}
At this point this nice error shows up with the message:
"_doQuery: [Error message: Could not
execute statement] [Last executed
query: CALL get_log_entries()] [Native
code: 1312] [Native message: PROCEDURE
wh_search.get_log_entries can't return
a result set in the given context]"
Now I have a couple of questions:
1. Is it even possible to execute SPs using MDB2 and return result sets?
2. Or is it better to write a wrapper class for "native" PHP-MySQL functions myself?
Thanks!
Nevermind, wrapping mysqli for calling SP. Also lots of fun...

Categories