We would like to query our database and sample records based on a particular user's department.
Given the app design, the only way I know to do this is to filter the query by using dept's session variable.
The code below is not working.
Data gets returned if I comment out the session variable.
Nothing is getting retrieved with the session variable as filter.
Any ideas what I am doing wrong?
Is the session variable route the wrong approach?
Thanks in advance for help.
//Start your session
session_start();
// Connect to SQL Server database
include("../sqlConnect.php");
// Construct query
$loginName = $_GET['loginName'];
//Ok, let's grab user's dept from query
$sql = "SELECT ISNULL(dept,'NA') AS 'dept' FROM emp where ([userName]) = lower('$userName')"
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false )
{
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$results = array();
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) {
array_push($results,$row);
$dept = $row['dept'];
}
//Store department in the session
$_SESSION['dept'] = $dept;
//Now extract records based on dept
$tsql ="SELECT
r.REQUESTID,
convert(char(10),r.[currDate],101),
r.[startedDBY],
e.[dept],
e.[WORKPHONE],
e.[EMAIL],
r.[DESCRIPTION],
r.[DETAILS],
r.[PROBLOCATION],
c.[COMMENTS]'
FROM EMPLOYEE e,REQUEST r,CUSTOMERCALL c
WHERE LOGINNAME='$loginName'
AND c.REQUESTID=r.requestid
AND e.dept = '" . $_SESSION['dept'] . "'
";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$results = array();
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) {
array_push($results,$row);
}
echo json_encode($results);
// Free connection resources
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
Related
I am new to MSSQL Server and there's a stored proc created by some developer and all I need to is run the proc from my PHP code.
But I am getting below error
The formal parameter "#contract_id" was not declared as an OUTPUT parameter, but the actual parameter passed in requested output.
Below is my code
$params['contract_id'] = '00990007';
$params['major_version'] = '1';
$procedure_params = array(
array(&$params['contract_id'], SQLSRV_PARAM_OUT),
array(&$params['major_version'], SQLSRV_PARAM_OUT)
);
$sql = "EXEC [MTP].[Process_07a_create_a_contract_version_wrapper] #contract_id = ?, #major_version = ?";
$stmt = sqlsrv_prepare($conn, $sql, $procedure_params);
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
if(sqlsrv_execute($stmt)){
while($res = sqlsrv_next_result($stmt)){
// make sure all result sets are stepped through, since the output params may not be set until this happens
}
// Output params are now set,
}else{
die( print_r( sqlsrv_errors(), true));
}
Can anyone guide me on this please?
First, check the type and the order of parameters, using sys.parameters. Then set params using the results:
<?php
...
$sql =
"SELECT [name], [is_output]
FROM sys.parameters
WHERE object_id = object_id('[MTP].[Process_07a_create_a_contract_version_wrapper]')
ORDER BY parameter_id";
$res = sqlsrv_query($conn, $sql);
if ($res === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC)) {
echo 'Name: '.$row['name'].', ';
echo 'Output: '.($row['is_output'] == 1 ? 'Yes' : 'No');
echo '</br>';
}
...
?>
Error message "The formal parameter "#contract_id" was not declared as an OUTPUT parameter, but the actual parameter passed in requested output" can be raised when the #contract_id parameter is not output parameter. So you can try with this (using your code):
<?php
...
$sql = "{call [MTP].[Process_07a_create_a_contract_version_wrapper](?, ?)}";
$procedure_params = array(
array($params['contract_id'], SQLSRV_PARAM_IN),
array(&$params['major_version'], SQLSRV_PARAM_INOUT)
);
$stmt = sqlsrv_query($conn, $sql, $procedure_params);
if( $stmt === false ) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
// Output parameters are available after consuming all resultsets.
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
}
...
?>
I am using PHP 5.6 and SQL Server 2012 with a nonthreadsafe driver. I have an incredibly easy question I already know, but for some reason i am completely brain dead.
I have a basic SQL query that will can either return 1 row of data, or multiple.
There is only three fields with data. but I would like to be able to read off the data (this is going into a vXML ivr using Voice Server 4.0, but that is irrelevant to my question).
Here is my code:
<?php
$serverName = "localhost";
$connectionOptions = array("Database"=>"mydb");
/* Connect using Windows Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if( $conn ) {
echo "Connection established.";
}else{
echo "Connection could not be established.";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM my_table WHERE SSN = 111111111";
//////I have no idea if I need this or not input appreciated
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
?>
All I would like to do is be able to retreive the information as rows, like
echo $row['field'];
echo $row['field2'];
echo $row['field3'];
ect.
would someone be able to point me in the right direction? I can only find mysqli examples, and those do not seem to work. Thanks!
I assume what you're looking for is sqlsrv_fetch_array
sqlsrv_fetch_array — Returns a row as an array
An Example:
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['field'].", ".$row['field2']."<br />";
}
PHP Manual: sqlsrv_fetch_array
I am working on a php code where I insert into two tables and want to grab the id from the first table I inserted into, right now I am getting this error: Call to undefined function sqlsrv_field(). I am trying to grab the routine_id from the table routines.
Code:
date_default_timezone_set('Europe/Oslo');
$date = strftime ('%Y-%m-%d');
$time = strftime('%H:%M:%S');
$value = $_GET['Temp'];
$conn = sqlsrv_connect('BILAL' , $conn_array);
$sql = "Insert into routines (date, time, value, emp_id) values ('$date', '$time', '$value', (SELECT id FROM emps WHERE user_name='Arduino'))";
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$query = sqlsrv_query( $conn, $sql);
if( $query === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_next_result($query);
sqlsrv_fetch($query);
$id = sqlsrv_field($query,0);
$sql2 = "Insert into measure_routines (routine_id, measure_id, pool_id) values ('$id', (Select id from measurements where title='A_Auto_Temperatur'), 1 )";
$stmt = sqlsrv_query( $conn, $sql2);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
There is no function called sqlsrv_field(). Instead, use sqlsrv_get_field():
...
sqlsrv_next_result($query);
bool fetchStatus = sqlsrv_fetch($query);
if(fetchStatus === false) {
die( print_r( sqlsrv_errors(), true));
}
if(fetchStatus === null) {
// Some work when there are no results in the result set
} else {
$id = sqlsrv_get_field($query, 0);
}
...
This should solve your problem basically. However your code is vulnerable to SQL injection. Instead of giving values directly into the sql query, consider using prepared statements.
There are many articles about that, here is one I found in quick search:
What's the Right Way to Prevent SQL Injection in PHP Scripts?
Try this:
function lastId($queryID) {
sqlsrv_next_result($queryID);
sqlsrv_fetch($queryID);
return sqlsrv_get_field($queryID, 0);
}
$lastInsertedId = lastId($stmt);
I'm having a really annoying problem with a simple query.
So:
INSERT INTO [SapuV2].[dbo].[ALERGIA] ([DESCRIPCION]) OUTPUT INSERTED.PK_ALERGIA VALUES ('test')
PK_ALERGIA is a primary identity key, and i need the new id created.
PHP code:
$sql = "INSERT INTO ALERGIA (DESCRIPCION) OUTPUT INSERTED.PK_ALERGIA VALUES(?)";
$id = 0;
$params = array(
array(&$nombre, SQLSRV_PARAM_IN),
array(&$id, SQLSRV_PARAM_OUT, SQLSRV_PHPTYPE_INT)
);
$stmt = sqlsrv_prepare($this->Conn, $sql, $params);
if( sqlsrv_execute($stmt) === false){
die( print_r( sqlsrv_errors(), true) );
}else{
var_dump($id);
}
I'm able to save records on my BD, but $id is always 0 ...
Thanks ;)
Please try this:
INSERT INTO ALERGIA (DESCRIPCION)select #var=scope_identity()
I finally did it, but i'm not proud ...
Using same SQL Query, but change the sqlsrv_execute to a sqlsrv_fetch_array
$sql = "INSERT INTO ALERGIA ([DESCRIPCION]) OUTPUT INSERTED.PK_ALERGIA VALUES (?)";
$params = array(
array(&$nombre, SQLSRV_PARAM_IN)
);
$rows = sqlsrv_query($this->Conn, $sql, $params);
if($rows === false){
die(var_dump(sqlsrv_errors()));
}else{
while($row = sqlsrv_fetch_array($rows, SQLSRV_FETCH_ASSOC)){
var_dump($row);
}
}
i took below SP HIt using sqlsrv and PHP. Snippet does not worked for me. For the below code i am getting " SQL SRV QUERY NOT RAN ". please provide your advise, how to achieve php + sqlsrv + SP.
$query = "{CALL call_user_name}";
if ( ($res = sqlsrv_query( CONNSTR, $query)) )
{
do
{
if ( sqlsrv_num_fields($res) ) // one way to check if results returned.
{
while( ($row = sqlsrv_fetch_array( $res, $type)) )
{
$data[] = $row;
}
}else{echo "sqlsrv_num_fields not working";}
} while ( sqlsrv_next_result($res) ) ;
sqlsrv_free_stmt($res); // not essential, but good form if your script does lots of other stuff.
}else{
echo "SQL SRV QUERY NOT RAN ";die( print_r( sqlsrv_errors(), true));
}
There are some possible causes for your error, my suggestion: change this line
echo "SQL SRV QUERY NOT RAN"
to
die( print_r( sqlsrv_errors(), true));
Then you can see what is causing the error.
Sample PHP SQL Srv stored Procedure call (With parameters). Hope this will help you to get an idea. (Used to call this php file through Ajax request and Return data after calling the SP)
smeSelectDrp is the SP Name
$sql = "EXEC smeSelectDrp";
$stmt = sqlsrv_prepare($conn, $sql);
if (!sqlsrv_execute($stmt)) {
echo "Error Retrieving Data";
die;
}
else
{
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
$value[] = $row;
}
echo json_encode($value);
}