I'm using the sqlsrv to fetch data from a sql server database. This database is in a diferent server of PHP (outside local network).
I using a query with lots of UNION. If I run the query on Management Studio it takes around 4-5 seconds to fetch all the data... But if I use the PHP and sqlsrv it takes around 57 seconds!
This is the code I'm using:
$connectionInfo = array("Database"=>$db, "UID"=>$u, "PWD"=>$p, "CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($serverName, $connectionInfo);
$errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
$tsql = $query;
$stmt = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => 'static' ));
$json = array();
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
} while ( sqlsrv_next_result($stmt) );
echo json_encode($json);
Any idea of what I'm doing wrong?
Try this code:
$this->stmt = sqlsrv_query($this->conn, $sql, null, array( "Scrollable" => SQLSRV_CURSOR_FORWARD ));
SQLSRV_CURSOR_STATIC Lets you access rows in any order but will not reflect changes in the database. static is the abbreviated form of SQLSRV_CURSOR_STATIC.
Please take a look at: https://learn.microsoft.com/en-us/sql/connect/php/cursor-types-sqlsrv-driver
Related
Laravel version:7.6,
SQL Server version: 2019,
I was going to get stored procedure as following:
$result = \DB::select(\DB::raw("exec myStoredProcedure:type"),[
':type' => "A",
]);
dd($result); // return value is only text
$result returned only one text.
Actually $result should have returned array. array[0] is one text sentence, array[1] is table array.
When I run this in SSMS, it returned exactly what I wanted. array[0] and array[1].
Could you please help me?
I also tried like this to solve this issue.
$result = \DB::select('exec myStoredProcedure(?)', ["A"]); // error
$result = \DB::select('exec myStoredProcedure("A")); // error
Above two results showed error.
I tried with core php as following:
$serverName = "localhost";
$connectionInfo = array("Database"=>"myDB", "UID"=>"sa", "PWD"=>"myPsw");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$query = "SET NOCOUNT ON; exec myStoredProcedure#type= A";
$stmt = sqlsrv_query($conn, $query);
$next_result = sqlsrv_next_result($stmt);
$array = [];
if( $next_result ) {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
$array[]=$row;
}
} elseif( is_null($next_result)) {
echo "No more results.<br />";
} else {
die(print_r(sqlsrv_errors(), true));
}
dd($array); // this returned only array[1] which is table array.
PHP 7.2.21
Database is on MS SQL, and the database connection is working
I have found and read sqlsrv_num_rows Not Returning Any Value. I have updated the $options based on the solution, but my code still does not return any results.
If I run the query in SQL, I get 8 records, so I know the data is there.
$sql = "SELECT * FROM Question WHERE Category = 'HD';";
$params = array();
$options = array( "Scrollable" => 'keyset' );
$stmt = sqlsrv_query( $conn, $sql, $params, $options );
if( $stmt === false ) { reportSQLError($sql, $params); }
$maxHDQ = sqlsrv_num_rows($stmt);
The code itself is ok and should work. What are the values for $stmt and $maxHDQ?
It is suddenly working
I just removed 'HD' from the query and added it to $params and this seems to have resolved everything.
I am not sure why it is working this way as the final query sent to SQL comes out the same either way I run it, however it does work.
$sql = "SELECT * FROM Question WHERE Category = ?;";
$params = array('HD');
$options = array( 'Scrollable' => 'buffered' );
$stmt = sqlsrv_query( $conn, $sql, $params, $options );
if( $stmt === false ) { reportSQLError($sql, $params); }
$maxHDQ = sqlsrv_num_rows($stmt);
I have one table that contains Company's Logo.... whenever I read small image like 4096 bytes It works perfectly, but i am not able to read over the 10000 bytes in php.
it's read only 4096 bytes from database
Update:
Column Lenth in Sql :
My Code in Model
function GetLogoById($Id)
{
$this->load->database();
mssql_query("SET TEXTSIZE 2147483647");
// or use CI's active record
$this->db->query("SET TEXTSIZE 2147483647");
$query = $this->db->query( "EXEC GetLogoById '$Id'" );
$result = array();
foreach ($query->result() as $row)
{
$result[] = array("Logo"=> $row->Logo);
}
return $result;
}
My Controller Code :
public function GetLogoById()
{
parse_str($_SERVER['QUERY_STRING'],$_GET);
$Id = $_GET['Id'];
$this->load->model('MyModel');
$result = $this->MyModel->GetLogoById($Id);
header('Content-type: image/png');
echo $result[0]['Logo'];
}
I am Getting Only 4096 bytes like :(string:4096) ����
I am getting this error on browser :
I think this is a problem with using MSSQL where data stored in a text type column is truncated for no apparent reason after 4096 characters.
Increase the maximum size of a text column to be returned from SQL Server. You can do this with the following SQL query:
SET TEXTSIZE 2147483647
You can run this with the following PHP, run it right after you make the connection:
mssql_query("SET TEXTSIZE 2147483647");
// or use CI's active record
$this->db->query("SET TEXTSIZE 2147483647");
And another way way to work around the issue is to change the "textlimit" and "textsize" settings within php.ini, like the following:
mssql.textlimit = 2147483647
mssql.textsize = 2147483647
Refer to this SO answer Why TEXT column returns only 4096 bytes? which refers to SQL Server, PHP and Truncating Text.
Update: Upon further review, reading this PHP bug, you may want to try using PDO_ODBC to connect to MSSQL Server instead:
//$dsn = 'mssql:host=MYBOX;dbname=testdb';
$dsn = 'odbc:DRIVER={SQL Server};SERVER=MYBOX;DATABASE=testdb;';
Also try setting the TEXTSIZE to megabytes:
$sql = "SET TEXTSIZE 3145728"; // 3 Megabytes
mssql_query($sql, $db) or die(mssql_get_last_message());
Got solution with sqlsrv driver ;)
function GetLogoById($Id)
{
$serverName = "XXXXX";
$uid = "XXXXXX";
$pwd = "XXXXXX";
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>"XXXXXX");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$tsql = "select Logo from TableName where Id = '$Id'";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Retrieve each row as an associative array and display the results.*/
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
return $row;
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
}
First. don't use the DBMS to store images. trust me.
Second, don't use the DMBS to store the images.....
Now, if you are getting an $id from the model, why have looping code to return an array? kind of defeats the purpose of an id?
I assume that the logo data is stored in the form of a BLOB ?
If this is the case the model could be something like:
$query = $this->db->get_where('tablename',array('id' => $id));
if ($query->num_rows() == 1)
{
return $query->first_row()->logo
}
else
{
return FALSE;
}
then the controller code could be something like:
public function GetLogoById($id)
{
$this->load->model('MyModel');
if($logo = $this->MyModel->GetLogoById($id))
{
$this->output->set_content_type('image/png');
$this->output->set_output($logo);
}
}
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
I have established a connection with my SQL Database through Windows Authentication in my php file. However I'm not sure how the syntax will look if I wanted to display a simple SQL query such as (Select * from Media) on the php page that shows an entire table. I tried a few methods but it displayed a fatal error.
Here is my code for the php:
<?php
$serverName = "172.20.90.170,5050"; //serverName\instanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"TestDB");
$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));
}
$version = mssql_query('SELECT * FROM MEDIA');
$row = mssql_fetch_array($version);
echo $row[0];
?>
Fatal Error:
Fatal error: Call to undefined function mssql_query()
This establishes a succesful connection but what would I need to change in my code for this query to run error free and display the required output?
It appears you are mixing two different API's (sqlsrv_ and mssql_).
If you're using sqlsrv_, then a simple statement could look like:
$connectionInfo = array( "Database" => "database", "UID" => "username", "PWD" => "password" );
$conn = sqlsrv_connect( "Server", $connectionInfo );
$stmt = "SELECT [column] FROM [table] WHERE [id] = ?";
$params = array( $id );
$query = sqlsrv_query( $conn, $stmt, $params );
if( $query === false ) {
print( print_r( sqlsrv_errors() ) );
}
while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC )) {
echo $row['column'];
}
sqlsrv_close( $conn );
Resources
MSDN Documentation
PHP Documentation (contains both Windows & SQL Server authentication examples)
From what I understand, you're new to the PHP world, BUT, I advise you to use the PDO class. You will have more facility to do what you want.
Here's a sample using your data.
If you study, you can understand.
try
{
$connection = new PDO("sqlsrv:Server=172.20.90.170;Database=TestDB", "YOUR_USERNAME", "YOUR_PASSWORD");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_SYSTEM);
}catch (Exception $e)
{
echo $e->getMessage();
die('Connection could not be established.<br />');
}
try
{
$sql = 'SELECT * FROM MEDIA';
$query = $connection->prepare($sql);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}catch (Exception $e)
{
die('Cant fetch rows.');
}
foreach ($result as $r)
{
print_r($r); // do what you want here
}
As others says in the comments, you have two options:
1. Use sqlsrv_query
2. Install MSSQL support to PHP.
Sincerely, I prefer use mssql_* stack of functions. If you use ubuntu, you can install MSSQL support simply:
aptitude install php5-sybase