sqlsrv_execute doesn't return anything - php

I'm using the SQL Server drivers for PHP to access a SQL Server database and I have a problem to update some data using sqlsrv_prpare and sqlsrv_execute functions.
I'm running two queries:
In the first query I'm retrieving some binary data (In SQL Server Management Studio, this query takes about 15 minutes to getting completed);
Then, for each row returned by the first query execution I'm trying to Update some data on the database.
Here's how my code looks like:
$query1 = "SELECT tgt.id, src.file, src.field1 from [Table1] tgt inner join [Table2] src on tgt.id = src.id order by tgt.id";
$query2 = "UPDATE [Table1] SET field1 = ? WHERE id = ?";
$getFiles = sqlsrv_query($con, $query1); //$con is the connection with the database, received by parameter
while($row = sqlsrv_fetch_array($getFiles, SQLSRV_FETCH_BOTH)) {
/* Some code here */
$file = $row[1];
$value = $row[2];
try {
if(!is_null($file)) {
$stmt = sqlsrv_prepare($con, $query2, array(&$value, &$row[0]));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_execute( $stmt );
}
} catch (Exception $e) {
error_log("\nError: " . $e->getMessage());
}
} //end while
sqlsrv_free_stmt($getFiles);
sqlsrv_close($con);
The problem is that the code inside the loop works fine to the first row, but on the second the update query isn't executed. The sqlsrv_prepare returns the value 1, but the sqlsrv_execute doesn't returns anything.
I'm thinking that the problem could be related to the first query execution time, but I don't know how to check this, considering that no error log is generated, the script just keeps executing forever.
EDIT: Actually, the example was simplified. The values that will be updated on tgt table are calculated using some data that are in src table and other application data. That's the reason why I use the loop, for each row returned by query1 specific values are calculated and used on query2. I already checked that these values are correctly calculated, this is why I thought it's better to simplify the example.

To solve this problem I have to ran the queries separately:
First I ran the query1, made the computation of the data that I needed to update the tgt table and stored them in an array;
Then, using the data stored in array, I ran the query2.
No other changes were needed.

Related

PHP PDO sqlsrv large result set inconsistency

I am using PDO to execute a query for which I am expecting ~500K results. This is my query:
SELECT Email FROM mytable WHERE flag = 1
When I run the query in Microsoft SQL Server management Studio I consistently get 544838 results. I wanted to write a small script in PHP that would fetch these results for me. My original implementation used fetchAll(), but this was exhausting the memory available to php, so I decided to fetch the results one at a time like so:
$q = <<<QUERY
SELECT Email FROM mytable WHERE flag = 1
QUERY;
$stmt = $conn->prepare($q);
$stmt->execute();
$c = 0;
while ($email = $stmt->fetch()[0]) {
echo $email." $c\n";
$c++;
}
but each time I run the query, I get a different number of results! Typical results are:
445664
445836
445979
The number of results seems to be short 100K +/- 200 ish. Any help would be greatly appreciated.
fetch() method fetches one row at a time from current result set. $stmt->fetch()[0] is the first column of the current row.
Your sql query has no ordering and can have some null or empty values (probably).
Since you are controlling this column value in while loop, if the current row's first value is null, it will exit from the loop.
Therefore, you should control only fetch(), not fetch()[0] or something like that.
Also, inside the while loop, use sqlsrv_get_field() to access the columns by index.
$c = 0;
while ($stmt->fetch()) { // You may want to control errors
$email = sqlsrv_get_field($stmt, 0); // get first column value
// $email can be false on errors
echo $email . " $c\n";
$c++;
}
sqlsrv_fetch

How to retrieve data from SQL Server?

I was wondering why my query is returning null when I know there is data there.
my query is as follows:
if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note FROM Notes WHERE NoteID = 2";
$showNotes = sqlsrv_query($conn, $showNoteInfo);
var_dump($showNotes);
}
I have tested $_POST['noteid'] and that displays an ID no problem, in theory this id will replace where I have the number 2 in my query.
However I know in my table in the Notes table where NoteID = 2 the text should be like this
However var_dump displays "resource(7) of type (SQL Server Statement)"
And I have also tried a different method of displaying it and that returned as the query expected resource and was given NULL, so why is this query not getting any results?
My connection details are in an include at the top of the page and are like this: http://pastebin.com/qz3tScdW
If you need anything else please ask.
Underlying question, why is my Query returning NULL when I know theres data there?
You never actually try to retrieve your data. sqlsrv_query performs the database query, but it doesn't get the data. You need to use sqlsrv_fetch_array (or sqlsrv_fetch_object) for that:
$stmt = sqlsrv_query($conn, $showNoteInfo);
if (sqlsrv_has_rows($stmt)) {
$data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
var_dump($data['Note']);
} else {
echo "No data found";
}

PHP + SQLite duplicate inserts

Every insert I do happens twice.
I thought the page might be getting hit twice so I also added a counter file that would increment on each load. The page is only getting hit once, yet each insert is inserted twice.
<?
$x = intval(file_get_contents("./count.x"));
header("Content-type: text/plain");
$db = new SQLite3("/var/www/images/cache.db");
$statement = $db->prepare('insert into `imgCache` (name,type,data) values("test7","bmp","argh);');
$result = $statement->execute();
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
print_r($row);
}
$x++;
file_put_contents("./count.x",$x);
?>
Prior to running this script there is no entry for "test7" in the database, and the contents of count.x is "0".
When I run this script, the following happens
count.x contains the text "1"
there are TWO entries for test7 in the database now.
PHP executes queries twice: one time to check whether any rows are returned, and a second time to actually return the rows.
An INSERT statement is not a query, and does not return rows.
Remove the fetchArray call.

echo statement not showing result after getting variable from $_post in php mysql

I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.

MySQL query sent successfully, yet database field stays empty

The following 2 queries are the result of an echo in php:
UPDATE glymping_userdata
SET current_location_gps = '51.9171115;4.484812'
WHERE id = 1
and
UPDATE glymping_user_has_appointments
SET status = 'enroute',
start_location_gps = '51.9171115;4.484812'
WHERE userId = 1
AND appointmentId = 47
Both queries work when entered manually in the database and all fields are filled correctly. When I let the php file run the queries, the queries are like shown above, but the "start_location_gps" and the "current_location_gps" are empty.
The values in the queries are strings and the database fields are a varchar(30). Yet the fields in the database are empty.
The location value is received from a post method.
Does anyone knows what I am forgetting or doing wrong?
EDIT:
php example
public function SendQuery($query)
{
$results = $this->mysqli->query($query);
return $results;
}
public function UpdateUserLocation($currentLocationGps)
{
$query = "UPDATE ".DB_PREFIX."userdata
SET current_location_gps = '{$currentLocationGps}'
WHERE id = ".$this->userId;
//echo $query;
$this->db->SendQuery($query);
}
Your current code doesn't check the return value of mysqli_query; the query might fail "silently". It could also be that the query does not affect any records in the database becaue of wrong values in the WHERE clause.
Try it with
if ( !$this->db->SendQuery($query) ) {
// query failed: syntax error, connection lost, access denied,duplicate entries, ...
trigger_error($this->mysqli->error);
}
else {
if ( 0 < $this->mysqli->affected_rows ) {
// WHERE clause doesn't match any record, no values changed, ...
trigger_error('no rows affected');
}
}
Your query might also be prone to sql injections, please check http://php.net/manual/en/security.database.sql-injection.php

Categories