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
Related
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.
Just started learning PHP, Angular and mySQL and am trying to retrieve just one field value from one single row. The same code below works for a query that returns multiples rows:
$qry = "SELECT ID FROM SharePoint001 ORDER BY DownloadedTimeStamp DESC LIMIT 1"; //returns a5f415a7-3d4f-11e5-b52f-b82a72d52c35
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array("ID" => $rows['ID']);
}
print_r(json_encode($data[0]));
I highly recommend switching to the mysqli extension. It's a much better way of doing things and you will probably find it much easier.
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}
The MySQL extension is:
Officially deprecated (as of PHP 5.5. Will be removed in PHP 7.)
Lacks an object-oriented interface
Much slower than mysqli
Not under active development
Does not support:
Non-blocking, asynchronous queries
Transactions
Stored procedures
Multiple Statements
Prepared statements or parameterized queries
The "new" password authentication method (on by default in MySQL 5.6; required in 5.7+)
Since it is deprecated, using it makes your code less future proof. See the comparison of SQL extensions.
You have not executed the query, so you'll never get results.
First you have to prepare query and place it into a variable lets say $qry.
Then execute that query by using mysql_query() function and capture result into a variable lets say $result
Now you can iterate that $result with loop to fetch rows and cells (what you call fields).
Below is code I have corrected:
$qry = "SELECT ID FROM SharePoint001 ORDER BY DownloadedTimeStamp DESC LIMIT 1";
$result = mysql_query($qry); // You are missing this line
$data = array();
while($rows = mysql_fetch_array($result)) // You have to pass result into mysql_fetch_array not query string
{
$data[] = array("ID" => $rows['ID']);
}
print_r(json_encode($data[0]));
Other people have asked this question, but mine is a little more specific.
I have this query:
$sql = "UPDATE table SET option=? WHERE number=?";
$q = $conn->prepare($sql);
$q->execute(array($option, $number));
$q->setFetchMode(PDO::FETCH_BOTH);
echo $q->rowCount();
If the WHERE number already exists and the SET option is same, $q->rowCount() equals 0
If the WHERE number doesnt exist and the row does not update, $q->rowCount() equals 0
How can I distinguish between these non-updates?
On recent PHP versions, it's controlled by the PDO::MYSQL_ATTR_FOUND_ROWS attribute.
When set to true, according to the doc, the effect is:
Return the number of found (matched) rows, not the number of changed rows.
Will be better check before if exists? I use a common function for this in my miniclass for manage PDO, but i dont know if is the best solution because make one query more...
function checkExistsInDatabase($id, $table, $where = null){
// Connect
$Database = Database::connect();
// Query
$sql = "SELECT id
FROM $table
WHERE id = :id $where
LIMIT 1";
$params = array(
':id' => array(
'value' => $id,
'type' => 'int'
)
);
$q = $Database->query($sql, $params);
// Ha encontrado algo?
$resultados = $Database->fetchArray($q);
if(count($resultados) === 1){
return true;
}else{
return false;
}
}
You can try using REPLACE which work's like insert but if the row already exists its first deleted and then inserted. This has overwork from mysql side
Add this:
$db = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
to the first "try {" part of your databasefunctions.php file
I am using the sqlsrv ms drivers for php, which work fine (tested with normal queries). I have also tested it with running a stored procedure to update a table data, which also works.
Now I want to use it to run a stored procedure, and I want to retrieve the response. How can this be done?
$server = "...the server address...";
$options = array("UID"=>"...the username...","PWD"=>"...the password...",
"Database" => "...the database..."
);
$conn = sqlsrv_connect($server, $options);
if ($conn === false) {die("<pre>".print_r(sqlsrv_errors(), true));}
$tsql_callSP = "{call ...the stored proc...( ?, ?)}";
$params = array(
array("...first value in...", SQLSRV_PARAM_IN),
array("...second value in...", SQLSRV_PARAM_IN)
);
$stmt3 = sqlsrv_query( $conn, $tsql_callSP, $params);
if( $stmt3 === false )
{
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true));
}
print_r( $stmt3); //attempting to print the return but all i get is Resource id #3
echo "test echo";
sqlsrv_free_stmt( $stmt3);
sqlsrv_close( $conn);
I know that I can use an output parameter, but I will always receive multiple values from the stored proc.
Supposing that the stored procedure is returning the contents of one table with a single SELECT statement, using its output should be as simple as using the result of sqlsrv_query as you would any other selection query result (i.e. using sqlsrv_fetch_object/array on the result)!
So the stored proc could look something like this:
CREATE STORED PROCEDURE test
AS
-- do some other stuff here
-- ...
SELECT * FROM test
GO
And in your php:
// establish db connection, initialize
// ...
$sql = "{call test}"
$result = sqlsrv_query($conn, $sql);
while (sqlsrv_fetch_object($result))
{
// do something with the data
// ...
}
You need to call sqlsrv_fetch() and sqlsrv_get_field() to get data from the returned statement.
From the example code in the manual for sqlsrv_get_field:
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
echo "Error in statement preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Make the first row of the result set available for reading. */
if( sqlsrv_fetch( $stmt ) === false )
{
echo "Error in retrieving row.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Note: Fields must be accessed in order.
Get the first field of the row. Note that no return type is
specified. Data will be returned as a string, the default for
a field of type nvarchar.*/
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
Beyond that, I am not sure when you say you will receive multiple values whether you mean there will be multiple fields in one row (in which case you will want to make more calls to sqlsrv_get_field()), more than one row (in which case you will have to use a while loop with the call to sqlsrv_fetch() in the loop), or more than one result set (in which case you'll want a while loop using sqlsrv_next_result()).
Sample code:
$infoArray = array();
require_once("connectAndSelect.php");
// Connects to mysql and selects the appropriate database
$sql = "SOME SQL";
if($results = mysql_query($sql))
{
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
$infoArray[] = $result;
}
}
else
{
// Handle error
}
echo("<pre>");
print_r($infoArray);
echo("</pre>");
In this sample code, I simply want to get the result of my query in $infoArray. Simple task, simple measures... not.
I would have enjoyed something like this:
$sql = "SOME SQL";
$infoArray = mysql_results($sql);
But no, as you can see, I have two extra variables and a while loop which I don't care for too much. They don't actually DO anything: I'll never use them again. Furthermore, I never know how to call them. Here I use $results and $result, which kind of represents what they are, but can also be quite confusing since they look so much alike. So here are my questions:
Is there any simpler method that I
don't know about for this kind of
task?
And if not, what names do you
give those one-use variables? Is
there any standard?
The while loop is really only necessary if you are expecting multiple rows to be returned. If you are just getting one row you can simply use mysql_fetch_array().
$query = "SOME SQL";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
For single line returns is the standard I use. Sure it is a little clunky to do this in PHP, but at least you have the process broken down into debug-able steps.
Use PDO:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
$sql = "SELECT * FROM myTable";
$result = $dbh->query($sql)
//Do what you want with an actual dataset
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Unless you are legacied into it by an existing codebase. DONT use the mysql extension. Use PDO or Mysqli. PDO being preferred out of the two.
Your example can be come a set of very consise statements with PDO:
// create a connection this could be done in your connection include
$db = new PDO('mysql:host=localhost;dbname=your_db_name', $user, $password);
// for the first or only result
$infoArray = $db->query('SOME SQL')->fetch(PDO::FETCH_ASSOC);
// if you have multiple results and want to get them all at once in an array
$infoArray = $db->query('SOME SQL')->fetchAll(PDO::FETCH_ASSOC);
// if you have multiple results and want to use buffering like you would with mysql_result
$stmt = $db->query('SOME SQL');
foreach($stmt as $result){
// use your result here
}
However you should only use the above when there are now variables in the query. If there are variables they need to be escaped... the easiest way to handle this is with a prepared statement:
$stmt = $db->prepare('SELECT * FROM some_table WHERE id = :id');
$stmt->execute(array(':id' => $id));
// get the first result
$infoArray = $stmt->fetch(PDO::FETCH_ASSOC);
// loop through the data as a buffered result set
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
// do stuff with $row data
}