I am trying to run a sqlsrv_connect SELECT query, and I am having issues getting any information back. No matter what query I run, sqlsrv_num_rows always returns a null value. I have verified that my queries are correct in SQL Server Management studio.
Some sample code:
$connection_info = array("UID"=>"uid", "PWD"=>"pwd", "Database"=>"db");
$c = sqlsrv_connect("tcp:hostname", $connection_info);
if (!$c) {
die(0);
}
$sql = "QUERY";
$result = sqlsrv_query( $c, $sql );
$row_count = sqlsrv_num_rows( $result );
echo $sql . $row_count;
Is there anything I am doing wrong? What am I missing?
The solution that worked for me was to put array("Scrollable" => 'static') as a configuration option for the select function.
Related
I am trying to update a row in my database via AJAX. $stmt_aufschlag returns true, but no updates in the database are made.
Executing the query directly in SQL Management Studio works fine.
Once I define a second variable with sqlsrv_query($conn, $sql_aufschlag) it works and the rows are updating. This is weird because I have several functions where the update query works fine with a single sqlsrv_query and I have another case where I have so assign sqlsrv_query twice.
Am I missing some arguements?
Here's my PHP code:
$serverName = "server2020";
$connectionInfo = array("Database"=>"Auftragsmanagement", 'ReturnDatesAsStrings'=> true, "CharacterSet" => "UTF-8");
$conn = sqlsrv_connect($serverName, $connectionInfo);
function save_aufschlag($conn){
$artikel = $_POST['artikel'];
$preisgruppe = $_POST['preisgruppe'];
$aufschlag = str_replace(',', '.', str_replace('.', '', $_POST['aufschlag']));
$sql_aufschlag = "UPDATE dbo.Artikel SET Kalkulation_AufschlagPG$preisgruppe = $aufschlag WHERE id = '$artikel'";
$stmt_aufschlag = sqlsrv_query($conn, $sql_aufschlag);
$test = sqlsrv_query($conn, $sql_aufschlag);
if($stmt_aufschlag){
echo json_encode(array("statusCode"=>200, "sql"=>$sql_aufschlag));
}
else if($stmt_aufschlag === false){
echo json_encode(array("statusCode"=>201, "error"=>print_r( sqlsrv_errors(), true), "sql"=>$sql_aufschlag));
}
}
Thanks to #Salman A and #Zhorov!
SET NOUCOUNT ON; at the beginning of the SQL Query is the solution.
a new webserver has been stood up for me. It is Ubuntu 20.04 and has PHP 7.4.3 on it. I am working with MS SQL Server 2012. I can send my SQL query to the DB server and see it in SQL Server Profiler. I can copy it from the profiler and it runs fine in SQL Management Studio but, I am having a problem when I try to echo the results to my page. When I use sqlsrv_num_rows I get -1. Could I get a hand please?
<?php
if(isset($_POST['getPassBtn'])){
#DATABASE LOGIN
include './php/inc/dbLogin/mydb.php';
#FORM POST VARIABLES
$badge = $_POST['empId'];
//$badge = (int)$badge;
#check badge entry for paramiters
if($badge == '' || $badge < 10000 || $badge > 30000){
echo '<br/> ERROR : Invalid Badge Number <br/>';
die();
}
$sql = "USE mydb SET NOCOUNT ON SELECT badgeNumber, userPassword FROM dbo.users WHERE badgeNumber = '$badge' ORDER BY badgeNumber ASC --getTestData.php";
//$sql = "USE toolsMeskwaki SELECT * FROM bingoProgressive.users ORDER BY badgeNumber ASC --getTestData.php";
$params = array();
$options = array( 'Scrollable' => 'buffered');
$stmt = sqlsrv_query( $conn, $sql, $params, $options);
#check if query returns false
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}else{
echo '<br/> Query sent to SQL Server <br/>';
}
/*
$row_count = sqlsrv_num_rows( $stmt );
if ($row_count === false){
echo "Error in retrieveing row count.";
}else{
echo $row_count;
}
*/
#Fetching Data by array
while($row = sqlsrv_fetch_array($stmt)){
echo 'badgeNumber '.$row['badgeNumber'];
echo 'userPassword '.$row['userPassword'];
}
#release query
sqlsrv_free_stmt($stmt);
#CLOSE DATA BASE CONNECTION
sqlsrv_close($conn);
echo "<br/> SQL Server Connection closed.<br />";
}else{
echo '<br/> click GET btn to connect SQL Server <br/>';
}
?>
You're submitting three different statements:
USE mydb
SET NOCOUNT ON
SELECT badgeNumber, userPassword FROM dbo.users WHERE badgeNumber = '$badge' ORDER BY badgeNumber ASC
It works in SQL Management Studio for two reasons:
Auto-magic statement detection, although deprecated for several years (you're now expected to use ; as delimiter), is still supported.
The query tool is specifically designed to run several statements at once.
We know that sqlsrv_query() supports it because it isn't returning false. But, given that you're running three statements, you need you use sqlsrv_next_result() twice to move to the third result set.
On a side note:
You can use sqlsrv_connect() to provide the initial database. You only need to switch DBs if you use several of them and you don't want to add the name as mydb.dbo.users.
SQLSRV supports prepared statements (see sqlsrv_prepare() and sqlsrv_execute()).
Please shame me. What's not right here? I was hoping for something like ->fetch_all(Opt), a one liner, to place all the results in an array but couldn't make it work. This is what I wound up doing:
$s = "select id, username from users";
$conn = db_connect();
$sth = $conn->prepare($s);
$sth->execute();
$sth->bind_result($id, $un);
$ida = array();
while ($sth->fetch()) {
$ida[] = $id;
}
I tried
$r = $sth->fetch_all() (tried assigning and not assigning a return value) both using and not using ->bind_result()
but both failed. What am I doing wrong?
First off, make sure that you have mysqlnd on your environment.
Then, to use ->fetch_all(), you'll need to use ->get_result() method first.
Here's the sequence:
$s = "select id, username from users";
$conn = db_connect();
$sth = $conn->prepare($s);
$sth->execute();
$data = $sth->get_result(); // get result first
$result = $data->fetch_all(MYSQLI_ASSOC); // then fetch all
print_r($result);
I'm trying to use PHP/ODBC to connect to an access file. The problem is that I can read from the database but I can't write to it using the below:
$conn = odbc_connect('SKW-DB','','');
if (!$conn)
{
exit ("ODBC Connection Failed ". $conn);
}
$stmt = "INSERT INTO PRODUCT (ProductCode, ProductName) VALUES ('TestCode', 'TestEntry')";
$result = odbc_exec ($conn,$stmt);
echo "Result1: ";
echo $result;
$result returns nothing. Again, I am able to read from the database, connectivity isn't an issue. I just can't write to it.
That's because you're simply ASSUMING the query can never fail. It did fail, and returned a boolean false. echo false literally prints out nothing.
Try this instead:
$result = odbc_exec($conn, $stmt);
if ($result === false ) {
die(odbc_errormsg($conn));
}
And what you get back from odbc_exec() cannot be echoed out anyways. On success, it returns a statement handle, which is NOT something you can simply print out.
Sounds like you need a little more debugging code.
First, try var_dumping the $result instead of echoing it.
var_dump($result);
There's certain PHP variable types that echo can't/won't display.
Next -- chances are your query's causing an error of some sort, so try using the odbc error reporting functions after making your query
$result = odbc_exec ($conn,$stmt);
echo "Result1: ";
var_dump( $result );
if($result)
{
var_dump( odbc_error($conn) );
var_dump( odbc_errormsg($conn) );
}
I'm attempting to execute a query of a SQL Server database, looking at a many to many relationship. I link the table I want the rows from with the relationship table, and plug in the unique id, in this case the $guid.
The query is functional, sometimes. It will work, and then I switch out solely the $guid for another one, and it fails, even though I'm staring at the table and it has values associated with that new $guid.
<?php
$guid = '{893C7BF8-E8C5-41D5-9C61-A72CF62DDBA8}';
// Connect to Database
$server = "###($#";
$connectionSettings = array("Database"=>"db", "UID"=>"user", "PWD"=>"pword");
$connection = sqlsrv_connect($server, $connectionSettings);
if (!$connection){
die("Failed Connection");
}
// Prepare and Execute Query
$sql = "SELECT *
FROM STREAMS.ATTACHMENTS a INNER JOIN STREAMS.RELATTACHMENTS ra
ON a.ROWGUID = ra.ATTACHMENT_GUID
WHERE ra.FEATURE_GUID = '" . $guid . "'";
$results = sqlsrv_query($connection, $sql);
$rowCount = sqlsrv_num_rows( $results );
if ($rowCount === false)
echo "failure";
else
echo $rowCount;
while($row = sqlsrv_fetch_array($results)){
echo "loop";
}
?>
Even stranger, the output to this code is the following:
failurelooploop
So that implies that the sqlsrv_num_rows command counted no rows in the result... but it also implies that the same results set has 2 rows, since the while loop went around twice.
Can anybody explain this funky behavior?
Thanks.
I will bet that you have some sort of error: sqlsrv_num_rows will return FALSE if something goes wrong. You can get the error output through:
// probably don't want this in production.
print_r( sqlsrv_errors());
I'll guess the cause has to do with your guid column, but I can't be sure. :-)
Oh, and unless you need the number of rows, don't use it. Use do... while instead:
$row = sqlsrv_fetch_array($results);
if($row)
{
do{
echo "loop";
} while( $row = sqlsrv_fetch_array( $results ) );
}
else
{
// No results found
// you can output print_r( sqlsrv_errors() ); here
}
This error shows for cursor type SQLSRV_CURSOR_FORWARD & SQLSRV_CURSOR_DYNAMIC . my personal preference is not to use it. if you still want to use it pass extra parameter to query function like :
$stmt = sqlsrv_query( $connection, $sql, array(), array( "Scrollable" => 'keyset' ));
// $stmt = sqlsrv_query( $connection, $sql, array(), array( "Scrollable" => 'dynamic' ));
// $stmt = sqlsrv_query( $connection, $sql, array(), array( "Scrollable" => 'static' ));
check more : https://msdn.microsoft.com/en-us/library/hh487160.aspx
-- http://php.net/manual/en/function.sqlsrv-query.php