I'm learning PHP and having it talk to our SQL Server 2008R2 DB. I am trying to run a query that has 2 date parameters that need to pass in. I know I could code the date params in to the SQL but I would like to see what I am doing wrong with the placeholder method below:
$serverName = "server";
$connectionInfo = array( "Database"=>"db", "UID"=>"user", "PWD"=>"pwd");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$startDate = strtotime("2015-04-30");
$endDate = strtotime("2015-05-01");
$sql = "SELECT * FROM history
WHERE (ts >= ? and ts < ?)
ORDER BY ts";
$params = array($startDate, $endDate);
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt == false) {
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<p>" . $row['vesselname'] . "</p>";
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
This returns the error "Arithmetic overflow error converting expression to data type datetime". ts is a datetime field.
Never mind. I figured out that I don't need the strtotime and to just pass date strings.
Related
I'm trying to execute a stored procedure in a Microsoft SQL database through PHP 7.4, including the passing of variables. I'm able to successfully execute it through SSMS with the following command.
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[UDX_Page]
#message1 = N'GROUP,user,.Notification Group,Is this thing on? [WebMSG]',
#message2 = NULL
SELECT 'Return Value' = #return_value
GO
It seems that it is expecting message1 as a varchar(200) and message2 as text, though the latter can be NULL. I've tried to call it through a couple different iterations of the following PHP code. I get no errors, but it doesn't seem to execute, so I must be doing something wrong.
<?php
$conn = sqlsrv_connect( $serverName, $connectionInfo); //connection info redacted
echo "<b>DATABASE: </b>";
if( $conn ) {
echo "Connection established. (" . $serverName . ")<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$message1 = 'GROUP,user,.Notification Group,Testing -DW [WebMSG]';
$message2 = NULL;
$sql = "EXEC [dbo].[UDX_Page] #message1 = N'" . $message1 . "', #message2 = NULL";
$stmt = sqlsrv_query($conn, $sql);
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
?>
And also with the following:
<?php
$conn = sqlsrv_connect( $serverName, $connectionInfo); //connection info redacted
echo "<b>DATABASE: </b>";
if( $conn ) {
echo "Connection established. (" . $serverName . ")<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$message1 = 'GROUP,user,.Notification Group,Testing -DW [WebMSG]';
$message2 = NULL;
$sql = "{CALL [dbo].[UDX_Page] (?,?)}";
$stmt = sqlsrv_query($conn, $sql, array(&$message1, &$message2));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
?>
Similarly, when I try it in Python, I'm having similar issues where nothing seems to happen. It recognizes that I need two variables to be passed and complaints if I don't (even if one is None). But it doesn't seem to actually do anything. Any I missing some final execution command?
#/bin/python3
import pyodbc
cursor = cnxn.cursor() #Connection info redacted
SQL_STATEMENT = '{call UDX_Page(?,?)}'
message1 = 'GROUP,user,.Notification Group,Test #7 -DW [WebMSG]'
message2 = None
values = (message1, message2)
cursor.execute(SQL_STATEMENT, (values))
Any ideas?
I need to fetch active records from my table. A record is active means it is not expired and the expiration time is 2 minutes after record is generated. I am using sql server database.
Here is the structure for my table
And my code is as follows
$serverName = "xxx.xx.x.xxx";
$connectionInfo = array( "Database"=>"xxxxxx", "UID"=>"xxxxx", "PWD"=>"xxxxxx");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if($conn)
echo 'success';
else
echo "failed";
$currentTime = date('Y-m-d H:i:s');
$query = "SELECT * FROM ApiTockenMaster WHERE Tocken = ? AND DateGenerated <= ? AND Status = ?";
$params = array("xxxxxxx", "2018-09-03 18:06:17.7600000", "Generated");
$result = sqlsrv_query( $conn, $query, $params);
$row = sqlsrv_fetch_array($result);
echo '<pre>'; print_r($row);
echo count($row);
I need the condition for DateGenerated as
currenttime <= DateGenerated + 2 minutes
How can I implement this condition in my query
Another possible approach is to let the SQL Server do the check using CURRENT_TIMESTAMP and DATEADD():
<?php
# Connection
$serverName = "xxx.xx.x.xxx";
$connectionInfo = array(
"Database"=>"xxxxxx",
"UID"=>"xxxxx",
"PWD"=>"xxxxxx"
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn) {
echo "Connection established.<br />";
} else {
echo "Connection could not be established.<br />";
die(print_r(sqlsrv_errors(), true));
}
# Statement
$query = "
SELECT *
FROM ApiTockenMaster
WHERE
(Tocken = ?) AND
(CURRENT_TIMESTAMP <= DATEADD(mi, 2, DateGenerated)) AND
(Status = ?)
";
$params = array(
"xxxxxxx",
"Generated"
);
$result = sqlsrv_query($conn, $query, $params);
if ($result === false){
die(print_r(sqlsrv_errors(), true));
}
# Result
$row = sqlsrv_fetch_array($result);
echo '<pre>';
print_r($row);
echo count($row);
?>
You can use DATEADD:
currenttime <= DATEADD(MINUTE, 2, DateGenerated);
Try this one, i haven't tested but it would be like this.
$currenttime= date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s")." +2 minutes"));
$params = array("xxxxxxx", $currenttime, "Generated");
Although this question has already been answered multiple times here, here, and here, none of these solutions could solve the issue for me.
I am trying to use PHP to fetch data from an MSSQL database. Although any query that I attempt to perform yields the same error message:
The active result for the query contains no fields.
Below is the code that I use to execute the query.
<?
include 'private.php'; // contains the servername, database, userID and password
$connectionInfo = array( "Database"=>$database, "UID"=>$userID, "PWD"=>$password);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
$query = 'USE data; SELECT * FROM Users;';
$stmt = sqlsrv_query( $conn, $query );
if(sqlsrv_has_rows($stmt))
{
echo 'success';
}
$row = sqlsrv_fetch_array( $stmt);
if ($row === false)
{
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['Name'].", ".$row['Value']."<br />";
}
sqlsrv_free_stmt( $stmt);
}
else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
Surprisingly, executing the same query in Microsoft SQL Server Management Studio works without any errors and executing queries that do not return information work fine aswell.
Note that I have already tried using SET NOCOUNT ON;, which is recommended in some answers regarding the same topic.
How can I resolve this error?
Please note that i tried all existing solutions and still haven't got output.
I have a php page that calls a Stored Procedure in SQL Server using sqlsrv functions. I have tried existing solutions but unable to solve my problem. When i execute this same SP in SQL Management Studio, it gives output of 31 rows. However, here in my code i am unable to get any row of data. Could someone advise on how to?
Here is my code:
$serverName = "(local)"; //serverName\instanceName
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$connectionInfo = array( "Database"=>"TESTDB");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
$AcCode = '18100017';
$StartDate = '2016/12/01';
$EndDate = '2016/12/31';
$CutAmt = -50000;
$IntRate1 = 2;
$IntRate2 = 3;
$sql = "EXEC dbo.uspGetBankInterest #AC_NO= ?, #AsOfDate= ?, #EndDate= ? ,#CutAmt= ?, #IntRate1= ?, #IntRate2= ?";
$stmt = sqlsrv_prepare($conn, $sql, array(&$AcCode,&$StartDate,&$EndDate,&$CutAmt,&$IntRate1,&$IntRate2));
$result=sqlsrv_execute($stmt);
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
if($result){
echo "SP Executed!";
}
$ctr=0;
$row_count = sqlsrv_num_rows( $stmt );
echo ' '.$row_count.'<br>';
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
print_r($stmt);
echo($row['STAT_DATE'].' '.$row['STAT_AMT'].' '.$row['INT_AMT']."<br>");
$ctr++;
}
echo 'The total number of records are:'.$ctr;
die();
}
else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
The output i get is:
SP Executed!
The total number of records are:0
When i executed, there was an output of 31 records and the data was displayed correctly. There is no problem in my SP. However, when i am trying it in php, no data is brought. How can i solve this problem?
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