how to execute sql server stored procedure on php? - php

i want to know why i cannot call any stored procedure on php file
it always return false
but when i call it on sql server directly, it shows my data
here is my php:
include ($_SERVER['DOCUMENT_ROOT'] . '/simda/classes/koneksi.php');
global $conn;
$kon = new koneksi();
$conn = $kon->bukaKoneksi();
$params = array();
$query = "EXEC dbo.RptSPJ_Pengeluaran '2013','1','1','1','0','1','1'";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$rs_test = sqlsrv_query($conn, $query, $params, $options);
if ($rs_test != NULL) {
$num_rows = sqlsrv_num_rows($rs_test);
echo $num_rows;
}
else {
echo 'wrong';
}
if i echo the query and execute it on sql server, it shows my data
is there anything wrong?
please help me
thank you

Related

SQLSRV call a stored procedure in SQL server

I'm totally new at this, Just do 'cause of boss request. So i have some issue wanna ask.
This is result when i call SP in SQL
Below is code to calling a SP in php
$ma_dvcs = 'OL';
$ngay = '01/2/2015';
$ma_kho = 'BPOL01';
$ma_nhvt = '';
$ma_vt = '24110012A2140850';
$kieu = '1';
$query = "{call Tondaulist (#p_Ma_Dvcs_List = ?,#p_Ngay = ?,#p_Ma_Kho = ?,#p_Ma_Nh_Vt = ?,#p_Ma_Vt = ?,#p_Kieu = ?)}";
$params = array(
array(&$ma_dvcs, SQLSRV_PARAM_IN),
array(&$ngay, SQLSRV_PARAM_IN),
array(&$ma_kho, SQLSRV_PARAM_IN),
array(&$ma_nhvt, SQLSRV_PARAM_IN),
array(&$ma_vt, SQLSRV_PARAM_IN),
array(&$kieu, SQLSRV_PARAM_IN)
);
$smtp = sqlsrv_prepare($conn, $query, $params);
if( $smtp === false )
{
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true));
}
$rows = sqlsrv_execute($smtp);
var_dump($rows);die;
$arr[] = sqlsrv_fetch_array($rows,SQLSRV_FETCH_ASSOC);
SQLSRV exec var_dump return true but i cant fetch anything and it keep giving error:
The active result for the query contains no fields
Or
sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given
So i wanna know is SP working the same like function in php or not? If yes, can it return an array or can just return boolean and how to get that array?
Thank in advance
Try changing your query to this
$query = "EXEC Tondaulist #p_Ma_Dvcs_List = ?,#p_Ngay = ?,#p_Ma_Kho = ?,#p_Ma_Nh_Vt = ?,#p_Ma_Vt = ?,#p_Kieu = ?";
This won't return an "array" SQL doesn't support arrays, but it will return a result set
You also need to change the call sqlsrv_execute to sqlsrv_query
There's an example of looping through a SQL result set here PHP MSSQL - How To Loop through Returning Rows?
Hope that helps
You need to change code as i mention below.
use stmp as argument to method sqlsrv_fetch_array .
if(sqlsrv_execute($smtp)){
print "success";
while($row = sqlsrv_fetch_array($smtp)){
print_r($row);
print "<br />";
}
}else{
print_r( sqlsrv_errors());
}
if you still not able to do it let me know what problem you are facing with this code.

Get Return Value from SQL Stored Procedure using PHP

So I have a php script that uses a stored procedure to interact with my SQL database. The stored procedure works just fine, the problem is I don't know how to get my php to echo the Return Value from the stored procedure. The stored procedure is basically activating an account using an activation key and sets the username and password.
It basically says "if the activation key provided does not have a username yet, set it to the one provided and RETURN 1, if it already has a username RETURN 2, and if the activation key does not exist RETURN 3". It works perfectly in SQL and even give the correct Return Value. Now how can I get my php to echo that? I have tried the following:
$link = sqlsrv_connect($myServer, array('Database' => $myDB, 'UID' => $myUser, 'PWD' => $myPass));
if($link === FALSE) {
die('Could not connect: ' . sqlsrv_errors(SQLSRV_ERR_ALL));
}
$key = $_REQUEST['key'];
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$query = "EXEC Activate_Account";
$query .=" #key = ";
$query .= $key;
$query .=", #user = ";
$query .= $username;
$query .=", #pass = ";
$query .= $password;
$result = sqlsrv_query($link, $query);
while($row = sqlsrv_fetch_array($result))
{
echo $row[0];
}
sqlsrv_close($link);
and
while($row = sqlsrv_fetch_array($result))
{
echo $row['Return Value'];
}
Neither of them echo anything.
To return a value with a stored procedure:
For example:
SQL :
CREATE DEFINER=`user`#`localhost` PROCEDURE `ProcedureName`(IN `Input_Value` INT, OUT `Out_val` INT)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
// Your SQL Code
SET Out_val= Your Value;
SELECT Out_val;
END
PHP Code:
$insert = "CALL ProcedureName(:Input_Value,
#Out_val)";
$bdd = new PDO('mysql:host=localhost;dbname=db-name', 'user', 'password');
$stmt = $bdd->prepare($insert);
$stmt->bindParam(':Input_Value', $an_input_value, PDO::PARAM_STR);
$stmt->execute();
$tabResultat = $stmt->fetch();
$Out_val = $tabResultat['Out_val'];
var_dump($Out_val);
The following example enables you to retrieve the RETURN value from a stored procedure and allows you to retrieve the OUTPUT values.
SQL:
CREATE PROCEDURE [ProcedureName]
#input_parameter as int,
#output_parameter as int out
AS
BEGIN
-- Your SQL code
SELECT #output_parameter = #input_parameter;
RETURN 2
END
PHP:
// Connect.
$link = sqlsrv_connect($myServer, array('Database' => $myDB, 'UID' => $myUser, 'PWD' => $myPass));
$returnValue = 0;
$inputParameter = 10;
$outputParameter = 0;
$parameters = [
[&$returnValue, SQLSRV_PARAM_OUT],
[$inputParameter, SQLSRV_PARAM_IN],
[&$outputParameter, SQLSRV_PARAM_OUT],
];
$sql = "EXEC ? = ProcedureName ? ?";
$stmt = sqlsrv_query($link, $sql, $parameters);
if ($stmt === false)
{
// Throw/Handle Error.
}
// $returnValue and $outputParameter should be updated here because they were passed by Reference.
// Retrieve query rows if any.
$rows = [];
while (($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ?? false) !== false) {
$rows[] = $row;
}
Some more reading about this topic can be found on the following links: How to retrieve input and output parameters using the sqlsrv driver and Sqlsrv query

PHP MySQLi select function not execute

I'm trying to call my function, but she's wrong.
I believe it is in connection variable.
Connection:
$conn = mysqli_connect('','','', '');
if(mysqli_connect_errno()) {
header("Location: error.php");
exit();
}
Function:
function t_car($id) {
global $conn;
$s_t_car = "SELECT *
FROM t_car
WHERE session='$id'";
$s_t_car_return = mysqli_query($conn, $s_t_car) or die("Erro SQL.".mysqli_error());
return $s_t_car_return;
}
Call Function:
$s_t_car_return = t_car($conn, $_SESSION['session_client']);
if(mysqli_num_rows($s_t_car_return )!=0) {
while($r_t_car = mysqli_fetch_array($s_t_car_return )) {
}
}
Error:
Catchable fatal error: Object of class mysqli could not be converted to string
At first you need to enter your settings from your MySQL server (mysql db).
$connection = mysqli_connect("HOSTNAME","USERNAME", "PASSWORD","DATABASE");
You can then use an if statement to check if the connection to the server has been made, if so, continue execution of following code, otherwise die();
If you want to fetch the data see below here:
$res = $connection->query("SELECT finger FROM hand WHERE index = 3");
while($row = $res->fetch_array())
{
print_r($row);
}
mysqli_query() returns a result. You have to fetch the result to do something with it.
$res = mysqli_query($conn, $s_t_car) or die("...");
$s_t_car_return = mysqli_fetch_row($res);

Using PHP to query a MDB file, and return JSON

I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make my code do the same thing, but just for the Access database.
Here is the MSSQL code
$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));
$sql = "SELECT *
FROM db.dbo.table";
$data = sqlsrv_query ($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
sqlsrv_free_stmt ($data);
sqlsrv_close ($conn);
Here is what I tried for the MDB file
$dbName = "/filename.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$sql = "SELECT *
FROM cemetery";
$data = $db->query($sql); // I'm getting an error here
$result = array();
// Not sure what do do for this part...
do {
while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
I kind of followed this to try to connect to the database: http://phpmaster.com/using-an-access-database-with-php/
Currently this is giving me a 500 Internal Server Error. I'm expecting a string such as this to be saved in the variable $json
[
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
etc...
}
]
Can someone help me port the MSSQL code I have above so I can use it with an MDB database? Thanks for the help!
EDIT: I'm commenting out the lines one by one, and it throws me the 500 error at the line $data = $db->query($sql);. I looked in the error log, and I'm getting the error Call to a member function query() on a non-object. I already have the line extension=php_pdo_odbc.dll uncommented in my php.ini file. Anyone know what the problem could be?
You only need 1 loop,
fetchAll is your iterable friend:
while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
odbc_connect doesn't return an object, it returns a resource. see (http://php.net/manual/en/function.odbc-connect.php) so you would need to do something like this.
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$oexec = obdc_exec($db,$sql);
$result[] = odbc_fetch_array($oexec);
and then you can iterate over results..
see also:
http://www.php.net/manual/en/function.odbc-fetch-array.php
http://www.php.net/manual/en/function.odbc-exec.php
I finally figured it out.
<?php
// Location of database. For some reason I could only get it to work in
// the same location as the site. It's probably an easy fix though
$dbName = "dbName.mdb";
$tName = "table";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
FROM $dbName.$tName";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
$data = array();
$i = 0;
// Grabs all the rows, saves it in $data
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
?>
I use this code to get results from an ODBC query into a JSON array:
$response = null;
$conn = null;
try {
$odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
$sql_query = "SELECT * FROM table;";
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
//this will show all results:
//echo odbc_result_all($result);
//this will fetch row by row and allows to change column name, format, etc:
while( $row = odbc_fetch_array($result) ) {
$json['cod_sistema'] = $row['cod_sistema'];
$json['sistema'] = $row['sistema'];
$json['cod_subsistema'] = $row['cod_subsistema'];
$json['sub_sistema'] = $row['sub_sistema'];
$json['cod_funcion'] = $row['cod_funcion'];
$json['funcion'] = $row['funcion'];
$json['func_desc_abrev'] = $row['desc_abreviada'];
$json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
$response[] = array('funcionalidad' => $json);
}
odbc_free_result($result); //<- Release used resources
} catch (Exception $e) {
$response = array('resultado' => 'err', 'detalle' => $e->getMessage());
echo 'ERROR: ', $e->getMessage(), "\n";
}
odbc_close($conn);
return $response;
And finnally encoding the response in JSON format:
echo json_encode($response);

Executing stored procedure with IN and OUT parameters in PHP

I want to execute a stored procedure into my PHP code, this stored procedure has an IN and an OUT parameter. The stored procedure is this:
USE [phl_pmx]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[PMX_SP_RecreateSynonymsOfSourceDb]
#sourceDb = phl
SELECT 'Return Value' = #return_value
GO
And I already wrote the following code, but it keeps giving errors that he can't execute it, or he just won't show a thing.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include_once 'DBC.php';
$link = mssql_connect('server', 'sa', 'password');
if (isset($_POST['StoredProcedure']))
{
mssql_select_db($id,$link);
$a = new TableOutput();
$a->getTables ("PMX_SP_RecreateSynonymsOfSourceDb","phl");
mssql_close($link);
}
elseif (isset($_POST['Value']))
{
$query =mssql_query("UPDATE [phl].[dbo].[PMX_EXDB] set ExtraDb='phl_pmx'");
mssql_close($link);
}
?>
This is the function for it.
<?php
class TableOutput {
function getTables($procname, $parameter) {
$stmt = null;
$data = null;
$vars = null;
$num = null;
$con = mssql_connect('server', 'sa', 'password');
if
(!$con) {
die('Could not connect: ' . mssql_error());
}
mssql_select_db("phl",$con);
$this->setStmt(mssql_init($procname, $con));
mssql_bind($this->getStmt(), '#sourceDb', $parameter, SQLINT2, false, false);
if ($rtn != 0) {
echo ("Errors happened when executing the stored procedure");
}
$exec = mssql_execute($this->getStmt());
$data = array();
$i = 0;
while ($row = mssql_fetch_assoc($exec)) {
$data[++$i] = $row;
}
unset($con);
unset($stmt);
return $data;
}
function setStmt($a_stmt) {
$this->stmt = $a_stmt;
}
function getStmt() {
return $this->stmt;
}
}
?>`
Does anyone know how to correct the code, because it keeps showing me the following error:
Warning: mssql_execute(): stored procedure execution failed in /var/www/mssql/management/DBC.php on line 24 Warning: mssql_fetch_assoc() expects parameter 1 to be resource, boolean given in /var/www/mssql/management/DBC.php on line 27
I don't know MSSQL stored procedures, so I can't analyse your stored procedure. If your proc is returning multiple resultsets you need to use mssql_next_result:
do {
while ($row = mssql_fetch_row($exec)) {
$data[++$i] = $row;
}
} while (mssql_next_result($exec));
Maybe this helps.

Categories