sqlsrv_fetch_array returning NULL - php

I have an issue where using sqlsrv_fetch_array is returning NULL. I am trying to do a simple query on a view in MS SQL that I have verified in SQL Server Management Studio provides results.
I am running PHP 7.4.4 on Windows Server 2016 x64, with version 5.8 of the PHP SQL drivers and 17.5.2.1 of the ODBC driver.
Similar queries are being run on 4 other views within this database and all work fine. Below is the code I'm testing:
<?php
include("../mscon.php");
$msConnInfo = array( "Database"=>"XYZ", "UID"=>"username", "PWD"=>"password");
$msConn = sqlsrv_connect( $msServerName, $msConnInfo);
if($msConn)
{
//echo "Connection established.\n";
}
else
{
//echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
$query = "SELECT * FROM Public_Web";
$result = sqlsrv_query($msConn, $query, array(), array( "Scrollable" => 'static' )) or die( print_r( sqlsrv_errors(), true));
if ($result === false) {
die(print_r(sqlsrv_errors(), true));
}
else
echo "We good fam, no errors<br/>\n";
var_dump($result);
if(sqlsrv_has_rows($result))
{
echo "<br/>Rows exist<br/>\n";
$numRows = sqlsrv_num_rows($result);
echo "There are $numRows rows<br/>\n";
while ($row = sqlsrv_fetch_array($result));
{
var_dump($row);
}
}
else
{
echo "no results were found<br/>\n";
}
sqlsrv_free_stmt( $result);
sqlsrv_close($msConn);
?>
The above code outputs lets me know that there are no errors and that 1493 rows exist in the view. But when I do a var_dump on $row it outputs NULL. All of the fields in the view I'm trying to access are varchar and there are only 7 fields total.
I have tried just grabbing one field in my query instead of all fields, no change in results. It seems like I have tried all possible troubleshooting methods.
Anything you can think of would be greatly appreciated. Thanks.

Problem solved. We ended up deleting the view in SQL and recreating it. No idea why it wasn't working properly.

Related

Update reads successful in console, but the database is unaffected

Trying to update a record using PHP and PDO statements.
The query fires with no errors, and the console reads the update was successful, but there is no change in the table.
So confused as to why this is happening:
<?php
include("../include/sessions.php");
if(isset($_POST['editcriteria']))
{
$value = $_POST['editcriteria'];
$editUID = $value['editUID'];
$editAddDelete = $value['editAddDelete'];
$editeffectiveDate = $value['editeffectiveDate'];
try
{
$update = $conn->prepare("UPDATE primary_vehicle_data SET `add_delete` = :eadddelete,
`effective_date` = :eeffectivedate WHERE `uid` = :euid");
$update->execute([
'eadddelete' => $editAddDelete,
'eeffectivedate' => $editeffectiveDate,
'euid' => $editUID
]);
if($update)
{
echo "Success: Record Updated";
}
else
{
echo "Error: The Vehcile was not updated.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
}
?>
I simplified the above code as much as possible. There were several more parameters, but when I removed the parameters and left it with the 3 parameters above, I still get "Success: Record Updated". But the table is literally unaffected.
Why is this happening and how do I fix it?
* UPDATE *
I already confirmed the connection to the database is good. I'm lost.
$update is a PDOStatement object, so when you test
if ($update)
it will always succeed as a PDOStatement object is equivalent to true.
You should be:
checking the result of $update->execute e.g.
if ($update->execute([ /* params */])) {
checking the value in $update->rowCount, which will tell you if any rows were affected by the query.

PHP + SQL Login system. Returning the wrong value [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 2 years ago.
Hello Everyone newbie here,
I'm trying to figure out why my code is returning "Login Successful" no matter what when my $loginresult is not = 1. This is my first time trying to implement prepared statements with my login system to avoid SQL injection and was curious if the issue lies in how I wrote that.
I can definitely say that when I am making my successful login my value is 1 and unsuccessful is 5.
Whenever it is 5 it is still returning the same echo that 1 should be returning.
Thank you for your time and patience everyone.
<?php session_start(); ?>
<!DOCTYPE html>
<head>
<title>Login</title>
</head>
<body>
<?php
include('config.php');
$conn = sqlsrv_connect($serverName, $conn_array);
$myparams['username'] = $_POST['username'];
$myparams['password'] = $_POST['password'];
// All checks done already (including password check). Begin building prepare statement.
$sql = "SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_WARNINGS ON
SET ANSI_PADDING ON
exec LoginScript #in_accountname=?,#in_password=?
";
//Array for prep
$procedure_params = array(
array(&$myparams['username'], SQLSRV_PARAM_IN),
array(&$myparams['password'], SQLSRV_PARAM_IN)
);
/* Prepare the statement. */
if( $stmt = sqlsrv_prepare( $conn, $sql, $procedure_params))
{
// echo "Statement was successfully prepared.\n";
}
else
{
echo "Statement could not be prepared.\n";
// ( print_r( sqlsrv_errors(), true)); ACTIVATE ONLY FOR DEBUGGING TO PREVENT HELPING SQL INJECTORS
}
/* Execute the statement. */
if( sqlsrv_execute( $stmt))
{
// echo " Statement executed.\n";
}
else
{
echo " Unable to execute prepared statement!\n";
// ( print_r( sqlsrv_errors(), true));
}
//checkuser
$result = sqlsrv_prepare( $conn, $sql, $procedure_params);
$info=sqlsrv_fetch_array($stmt);
$LoginResult = $info;
//Login Success
if (!$LoginResult=1)
{
echo "Login DEAD.";
echo "Login Result: ".$info[0]."\n";
}else{
echo "Login Successful.";
echo "Login Result: ".$info[0]."\n";
}
/* Free the statement and connection resources. */
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>```
if (!$LoginResult=1) is not what you want, you need
if ($LoginResult != 1) is not valid
See: Equality Operators
What you've done with your original code is assign the value 1 to the $loginResult variable and checked if it is not truthy

MySQLi returns an object but won't return results in foreach loop

I have a basic MySQLi query that is returning a MySQLi object and looping through it in a foreach(); to display a dump of data from my db. When I test it locally running PHP 5.5.9 everything is fine but when I put it on my remote production server running PHP 5.3.3 it will return the object in a var_dump but it will not loop through the results and display them.
Here is the code:
if ($mysqli->connect_errno) {
echo "There was an error";
} else {
if ($result = $mysqli->query("SELECT * FROM acronyms")) {
}
else {
echo "query error";
}
foreach($result as $x=>$y) {
echo $y["definition"];
}
}
?>
It appears that mysqli is installed on my production server but just won't loop in an identical file that have in my testing server.
I have also rewritten the query in regular MySQL and have been able to get the data out of the database.
MySQLi->query returns a MySQLi_result class on successfully retrieving a resultset.
Iterator support to MySQLi_result was only added in PHP 5.4, if your version of PHP is earlier than that you will need to traverse these results in the traditional way using fetch_assoc:
while($y = $result->fetch_assoc()) {
echo $y["definition"];
}
You need to actually do something with the results like use fetch_assoc() to interate through the results.
$mysqli = new mysqli("localhost", "name", "pw", "db");
if ($mysqli->connect_errno) {
echo "There was an error";
}
else {
if ($result = $mysqli->query("SELECT * FROM acronyms")) {
}
else {
echo "query error";
}
while ($row = $result->fetch_assoc()) {
echo $row["definition"];
}
}
Note the while ($row = $result->fetch_assoc()) { which is a fairly standard method used to roll through MySQLi results like this.

Retrieve SQL statement from MySQL and process in PHP

I have successfully saved a number of SQL UPDATE statements to MySQL and now I want to retrieve them and have PHP process them. The code is below.
When I echo $query I get the correct SQL statements from the DB, but then when I try to process them, I get an error Warning: mysqli_query() [function.mysqli-query]: Empty query
It makes no sense to me and is driving me nuts! Do I have to do something else to $query so PHP can process it?
$num_rows = mysqli_num_rows($resultSQL);
if ($num_rows > 0)
{
while ($row = mysqli_fetch_array($resultSQL))
{
$strSQLupd[] = $row['uSQL'];
}
foreach ($strSQLupd as $query) {
$resultSQLupd = mysqli_query($link,
$query
);
if (!$resultSQLupd)
{
$error = 'Error fetching data: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
}
}
Are you setting the value of $link somewhere and is it required for what you're doing in this application? Also, remember that var_dump($varname); is always a helpful debugging tool.
foreach ($strSQLupd as $query) {
// put a var_dump below
var_dump($query);
$resultSQLupd = mysqli_query($query
);
if (!$resultSQLupd)
{
$error = 'Error fetching data: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
}
Give this a shot and look at the query string dumped to the screen. It may be null which is what's producing your error.

Trouble with returning data consistently after performing SQL stored procedure in PHP

all,
i have been lurking on stackoverflow for a few years now, always able to find the help needed to resolve the issue at hand. however, this time, i needed to create my first question as i was unable to find questions that hit on the same issue i am encountering.
i have been stumped for over a week and am getting into hot water at work because i already blew my estimated date. i put myself at your mercy in the hopes that you may help me with my coding headache.
i am able to return data from executing a stored procedure through PHP on a SQL 2008 server on a VM (running windows 2008 r2) where i pass in one parameter.
that parameter has a total of eleven (11) choices. whenever i pass in one (1) of those choices, expected data is returned.
however, whenever i use any of the other choices, no data is returned (and with my current code, no errors are returned either).
there are 11 choices of $application_selected to pass into the stored procedure and only one (1) of those choices returns data. none of the others return data or errors.
here is my entire code:
<!DOCTYPE html>
<html>
<head>
<title>data</title>
</head>
<body>
<?php
////////////////////////////////////////////////////////////////////////////
//connection information
$servername = "192.168.1.104";
$username = "sa";
$password = "*";
$database = "*";
$connection_info = array( "Database"=>$database, "UID"=>$username, "PWD"=>$password);
$conn = sqlsrv_connect( $servername, $connection_info);
if($conn===FALSE) die( print_r( sqlsrv_errors(), true));
else echo "<font color=\"blue\">DB Connected.</font><br>";
/////////////////////////////////////////////////////////////////////////////
$application_selected = "param1";
$sql_cmd = "EXECUTE GetApprover '$application_selected'";
$execute_this = sqlsrv_prepare($conn, $sql_cmd);
$application_proc = sqlsrv_execute($execute_this);
if($application_proc===FALSE) die( print_r( sqlsrv_errors(), true)); //execute failed; die and display errors
else echo "<font color=\"blue\">DB data retrieved.</font><br><br>";
$row_apps = "";
$count = 0;
echo "<font color=\"blue\">Attempting data output via loop</font><br><br>";
/////////////////////////////////////////////////////////////////////////////
// output data
//echo var_dump($execute_this)."<br><br>";
echo "<font color=\"blue\">Application selected = </font>\"".$application_selected."<font color=\"blue\">\" - data pulled ▼</font><br><br>";
while(($row_apps = sqlsrv_fetch_array($execute_this)) && (sqlsrv_fetch_array($execute_this) <> FALSE)) { //while var has data
if (!isset($row_apps)) die( print_r( sqlsrv_errors(), true));
$count += 1;
echo $row_apps['ApplicationName']." - ".$row_apps['ApproverCode']." - ".$row_apps['ApproverDesc']." - ".$row_apps['FullName']." - ".$row_apps['Email']." - ".$row_apps['UserId']."<br>";
}
/////////////////////////////////////////////////////////////////////////////////
echo "<br><font color=\"blue\">▲ Data displayed.";
echo "<br><br><font color=\"blue\">There were [<font color=\"red\"><b>$count</b></font>] rows returned.<br><br><br>";
echo "<br>\$servername = ";
echo var_dump($servername)."<br>";
echo "<br>\$username = ";
echo var_dump($username)."<br>";
echo "<br>\$password = ";
echo var_dump($password)."<br>";
echo "<br>\$database = ";
echo var_dump($database)."<br>";
echo "<br>\$connection_info = ";
echo var_dump($connection_info)."<br>";
echo "<br>\$conn = ";
echo var_dump($conn)."<br>";
echo "<br>\$application_selected = ";
echo var_dump($application_selected)."<br>";
echo "<br>\$sql_cmd = ";
echo var_dump($sql_cmd)."<br>";
echo "<br>\$execute_this = ";
echo var_dump($execute_this)."<br>";
echo "<br>\$application_proc = ";
echo var_dump($application_proc)."<br>";
echo "<br>\$row_apps = ";
echo var_dump($row_apps)."<br>";
echo "<br>\$count = ";
echo var_dump($count)."<br>";
echo "<br><br><br>";
sqlsrv_close($conn);
echo "<br>DB Connection closed.</font><br><br><br>";
?>
</body>
</html>
it seems my preliminary suspicions (although i had no tangible proof of such) of some sort of db issue was the culprit after pushing my dba (also my director) with some test results from added debug code [like var_dump()/print_r()]. his reply to the issue that caused it all was as follows:
"i don't know what happened but i copied the table content from my dev environment to your dev environment and now things work."
i'm sorry to trouble you all with my issue. i am grateful that Marc B and Raad answered my plea for help so quickly and i really hope this question helps someone in the future.

Categories