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";
}
Related
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.
My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.
My connection & sql queries have already been tested and they work. I am just trying to print one column of data into my browser for output so I can test the rest of the database. I am just trying to print one row and when I run the code, nothing shows up in the browser as output. The database column name is "type" and there is a "1" in there for the user I am logging in with. The login works but I am trying to read the integer in the database in order to direct it to a specific profile. I can't get anything to printout from my table into the browser.
$role = "SELECT type FROM fp.user WHERE usname ='$username' AND pswd = '$password'";
$access = mysqli_query($link, $role);
$row = mysqli_fetch_row($access);
echo $row['type'];
There may be a problem with your query. You should check to see if $access is first false (Which would indicate a query failure), and echo out the error associated with the query.
$role = "SELECT type FROM fp.user WHERE usname ='$username' AND pswd = '$password'";
$access = mysqli_query($link, $role);
if ( !$access )
{
echo 'There was a problem running this query: ', mysqli_error($link);
exit;
}
$row = mysqli_fetch_row($access);
Also, according to the docs:
Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.
Check to make sure the user/password combo in the database is correct. Another issue could be that no user exists for that $username/$password combo.
Here's what I'm doing.
I'm checking if there's a "version" value in the URL with $get_version.
Get the latest version from the database and set as a default variable.
If the URL variable is good, check the database to see if it exists then set the appropriate variables.
If doesn't exist, use default value from above.
It always goes to the "Bad query section". Either my query is wrong or my if statement doesn't work.
Here's my code. Also, is there a cleaner way of doing it?
// Check if there's a version in URL. If not, set to empty.
$get_version = isset($_GET['version']) ? $_GET['version'] : '';
// Set defaults if nothing in URL
$query = "SELECT * FROM sn_hockey_versions ORDER BY version_id DESC LIMIT 1";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
$newest_version_id = $row['version_id'];
$newest_sections = $row['sections'];
}
if (!empty($get_version) && preg_match('/^[0-9.]*$/', $get_version)) {
$query = "SELECT version_id, sections FROM sn_hockey_versions WHERE version = '".$get_version."'";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
if ($row = mysqli_fetch_array($result)) {
$set_version = $row['version_id'];
$v_sections = $row['sections'];
$test = "IT WORKS!!!!";
}
else {
$set_version = $newest_version_id;
$v_sections = $newest_sections;
$test = "Bad query";
}
}
else {
$set_version = $newest_version_id;
$v_sections = $newest_sections;
$test = "Set default";
}
Your conditional if statement is checking to see whether $rows is set to mysql_fetch_array($result), not whether it returned any results. If the query returns results, the conditional statement returns true, $row is set to the resulting array, and your if block will be evaluated. Otherwise, $row is set to null, making the condition false, and the else block evaluates.
Since your else statement is evaluating, this leads me to believe that there is an issue with the query, which can be tested by printing out the results of the array. While there are numerous ways to check if a query returns any results, to prevent confusion in your code, checking the value of mysql_num_rows would be a better solution before fetching the results:
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result)
For more information about mysqli_num_rows check out http://php.net/manual/en/mysqli-result.num-rows.php
Also see: Whats the proper way to check if mysql_query() returned any results?
The other recommendation I have for making the code more efficient is: Only query the database for the default version when necessary. Too many unnecessary queries can lead to database performance issues. One way to accomplish this, is to place the default version query into a function and call it only in the "bad query" "set default" blocks. I hope this helps.
To check if it was successful outside of the code, copy the query and run it in phpmyadmin or through ssh to see if it returns results. If it returns results then put in some stop checks in your code to see what you are getting. like so
echo '<pre>jwow',print_r($result,1),'</pre>';
die('here');
Just place that under which ever result you would like to check. I like to name the query results by different names. like $defaults_results and $version_results . if it is getting to "Bad Query" you will have found your error after trying that. If it returns no results in phpmyadmin then read the errors it gives.
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.