Query SQL DB Table view and display results in HTML table - php

my purpose is to display in a HTML table the result of a query to a remote ODBC SQL database with PHP.
I've already established the connection with the database, but when i try to execute a query and display it in a table it doesn't show anything.
Is there a difference in the query syntax if the table is a view?
The environment is WAMP installed on Windows, PHP 5.6.19, APACHE 2.4.18
This is the code (I have omitted the variables for the odbc connection):
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<?php
$conn=odbc_connect("Driver={SQL Server};Server=$server;Database=$database;", $user, $password);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( odbc_error(), true));
$sql = "SELECT * FROM ASSET_VIEW";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>numero</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["N_IMMA"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
?>
</body>
</html>
All I get is the "Connection established" string and that's it.
I would like to show all the results from the table (about 30 columns and 300 rows). I've tried with different tables but I still get the same result. I'm relatively new to PHP and MySql and maybe it's a silly request but I can't get my head around it for the moment.
Thank you

You haven't closed the else bracket for Connection could not be esatblished. That's why the Table part is not getting genearted.
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( odbc_error(), true));
}
// Logic to build the table from query

Related

sqlsrv_fetch_array returning NULL

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.

PHP : 'json_encode' from Database not showing any values

It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got

Connect to mysql db but no data from table is echo to screen

The script below connects to the db (I get the connected successfully echo) but none of the data from the query is shown onscreen.
I assume the data must be somewhere as I do not get the error message.
Question: Where is the error in the script?
<?php
//connectdb();
$con = mysqli_connect("localhost","UN","PW");
if ( $con == "" ) { echo " DB Connection error...\r\n"; exit(); }
echo 'Connected successfully';
$result = mysqli_query($con, "SELECT graduation_year FROM wp_gfsept2013");
while($row = mysql_fetch_array($result))
if ($result === "") {echo "An error occurred.";}
{
echo $row['graduation_year'];
echo "<br>";
}
?>
Appreciate any help that can be sent my way, I'm a real newbie at this stuff.
Roger
Try adding an opening brace after while($row = mysql_fetch_array($result)) and a closing brace before the end of the script.
Is this not a syntax issue?? Why is there an IF clause after a WHILE clause but before the opening bracket for the WHILE loop block?
Additionally, you are trying to use mysql_fetch_array() instead of mysqli_fetch_array().
<?php
//connectdb();
$con = mysqli_connect("localhost","UN","PW");
if ( $con == "" ) { echo " DB Connection error...\r\n"; exit(); }
echo 'Connected successfully';
$result = mysqli_query($con, "SELECT graduation_year FROM wp_gfsept2013");
if ($result !== FALSE && mysqli_num_rows($result) > 0) { // Proper way to test for results
while($row = mysqli_fetch_assoc($result))
{
echo $row['graduation_year'];
echo "<br/>";
}
}
else {
die("Query Returned 0 rows...");
}
?>
Documentation: mysqli_result::$num_rows

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.

PHP and SQL 2008 - Truncate table not working

Why won't this table get Truncated? No error is returned. If I run the truncate SQL in SQL Server Management Studio, it truncates normally.
$truncate = "USE energyDB truncate table temp_energydata";
// Initiate connection to energyDB MS SQL server
$connection = sqlsrv_connect($serverName, $connectionInfo);
if( $connection ) {
echo "Connection established.";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
// Start the query on the Database server
$statement = sqlsrv_query($connection,$truncate);
if( $statement ) {
echo "Truncate Query completed.";
}else{
echo "Query not completed.<br />";
die( print_r( sqlsrv_errors(), true));
#user1745767
$truncate = "USE energyDB truncate table [temp_energydata]";
try like this it tooks hours for met too.

Categories