How to display data from SQL Server - php

I can get the connection but the data does not show. Some error occurs at this line:
if($result ->num_rows > 0)
The table names for this database is "ndtatt".
This table has 4 columns. And that just one example the value stored in this database.
varchar CARDNO = value 009145
varchar STAFF = value V0822
varchar NAME = value Marry
Varchar ATTDATE = value 2020/01/04
.
<?php
$serverName = "LAPTOP-61BF65AR";
$connectionInfo = array("Database"=>"LocalDatabase");
$conn = sqlsrv_connect ($serverName, $connectionInfo);
if ($conn) {
echo " Connection established.<br/>";
}else{
echo "Connection Failed.<br />";
die(print_r (sqlsrv_errors() , true));
}
$attDate = $_GET['attDate'];
$cardNo = $_GET['cardNo'];
$sql = "SELECT * FROM ndtatt WHERE ATTDATE = '$attDate' AND CARDNO = '$cardNo'";
$result = sqlsrv_query ($conn, $sql);
if($result ->num_rows> 0)
{while($row = $result->fetch_assoc())
{?>
<tr>
<td><?php echo $row['CARDNO']; ?></td>
<td><?php echo $row['STAFF']; ?></td>
<td><?php echo $row['NAME']; ?></td>
<td><?php echo $row['ATTDATE']; ?></td>
</tr>
<?php
}}
else {echo "0 results";}
$conn->close();
?>
Below this is the html file :
<form method="GET" action="get3.php">
<h3 class="absolute" > Attendance Date :
<input type="date" name="attDate"> </h3>
</br></br></br>
<h3 class="absolute2" > Card Number :
<input type="text" name="cardNo" placeholder="Card Number"> </h3>
</br></br></br></br></br>
<center> <input type="submit" name="search" value="Search" class="button" /> </center>
</form>
The first source codes was originally for php(xampp) database with html, but I have made some changes in it, because I want to change the database(php) into sql server.
Do I need to change the entire source codes or just make some changes like I have done in the source codes given?
Does XAMPP have anything to do with SQL Server? I mean, to use the SQL server, do I need to open XAMPP when to run the codes?

XAMPP is an Apache distribution containing MariaDB, PHP and Perl, so the only thing that you need to connect to SQL Server, is to install the PHP Driver for SQL Server (you are using sqlsrv_ functions in your code).
But you have some issues with your code:
You need to use only sqlsrv_ functions. The calls to $result->num_rows, $result->fetch_assoc() and $conn->close() will raise an error.
You need to use "ReturnDatesAsStrings" => true as a connection option to fetch the date/time values as strings (the default value is false and the values of date/time columns are returnded as PHP DateTime objects).
The date values in your table are stored as text, so you need to transform the value of the input elements of type "date" to match the format in the table (yyyy-mm-dd). As a side note, if possible, do not store date values as text. Use the appropriate data types - date or datetime2 in this case.
Always try to use parameters in your statements to prevent SQL injection issues. As is mentioned in the documentation, the sqlsrv_query() function does both statement preparation and statement execution, and can be used to execute parameterized queries.
Example, based on the code in the question:
<?php
// Connection
$serverName = "LAPTOP-61BF65AR";
$connectionInfo = array(
"ReturnDatesAsStrings" => true,
"Database" => "LocalDatabase"
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn) {
echo " Connection established.<br/>";
} else {
echo "Connection Failed.<br />";
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
// Query
$attDate = DateTime::createFromFormat('Y-m-d', $_GET['attDate'])->format('Y/m/d');
$cardNo = $_GET['cardNo'];
$sql = "SELECT * FROM ndtatt WHERE ATTDATE = ? AND CARDNO = ?";
$params = array($attDate, $cardNo);
$result = sqlsrv_query ($conn, $sql, $params);
if ($result === false ) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
// Fetch data
if (sqlsrv_has_rows($result)) {
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['CARDNO']; ?></td>
<td><?php echo $row['STAFF']; ?></td>
<td><?php echo $row['NAME']; ?></td>
<td><?php echo $row['ATTDATE']; ?></td>
</tr>
<?php
}
} else {
echo "0 results";
}
// End
sqlsrv_free_stmt($result);
sqlsrv_close($conn);
?>
Notes:
The code from the question is driver specific, but you may try to rewrite this code using PDO (PHP Data Objects). With PDO, using the new code, you can use any supported database (of course you need to install a database-dependant driver that implements the PDO interface).

The query below will retrieve two table data with join:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

Related

Query with data from user in MSSQL with PHP [duplicate]

This question already has answers here:
sqlsrv_num_rows Not Returning Any Value
(2 answers)
Closed 2 years ago.
(I'm forced to work on microsoft sql server in my internship).
I don't understand why my query doesn't work in PHP (it returns no data), but it works when I put it directly in Microsoft SQL Server Management Studio (it returns the datas).
Here is my code :
<?php
require('conn.php');
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
$sql = "SELECT codepo, codepsa, controle, FORMAT(date, 'dd-MM-yyyy hh:mm:ss') as date FROM dbo.codebarre where datediff(day, date, '$search') = 0";
var_dump($sql);
$result = sqlsrv_query($conn2, $sql);
$queryResult = sqlsrv_num_rows($result);
?>
(...)
<?php
if($queryResult > 0){
while($donnees = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
?>
<tbody>
<tr>
<th style="font-weight: normal;"><?php echo htmlspecialchars($donnees['codepo']); ?></th>
<td><?php echo htmlspecialchars($donnees['codepsa']); ?></td>
<td <?php if ($donnees['controle'] === 'NOK') {
echo 'style="color: red; font-weight: bold"';
} ?>><?php echo htmlspecialchars($donnees['controle']); ?></td>
<td><?php echo $donnees['date'] ?></td>
</tr>
</tbody>
<?php
}
} else {
echo "No data";
}
}
The var_dump($sql) returns me this :
string(138) "SELECT codepo, codepsa, controle, FORMAT(date,
'dd-MM-yyyy hh:mm:ss') as date FROM dbo.codebarre where datediff(day,
date, '20210107') = 0"
As I told you when I paste it in Management studio it works, so I don't understand why it doesn't here.
You have two options:
Execute sqlsrv_query() with the appropriate cursor type, if you want to get the exact number of the returned rows.
Use sqlsrv_has_rows() if you want to check if there are rows returned.
PHP code using sqlsrv_num_rows():
<?php
...
$result = sqlsrv_query($conn2, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$queryResult = sqlsrv_num_rows($result);
if ($queryResult > 0) {
// Fetch data
}
...
?>
PHP code using sqlsrv_has_rows():
<?php
...
$result = sqlsrv_query($conn2, $sql);
$queryResult = sqlsrv_has_rows($result);
if ($queryResult) {
// Fetch data
}
...
?>
As an additional note, always use parameterized statements to prevent possible SQL injection issues. As is mentioned in the documentation, function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
<?php
...
$sql = "
SELECT codepo, codepsa, controle, FORMAT(date, 'dd-MM-yyyy hh:mm:ss') AS date
FROM dbo.codebarre
WHERE datediff(day, date, ?) = 0
";
$params = array($search);
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$result = sqlsrv_query($conn2, $sql, $params, $options);
...
?>

How to connect an HTML interface (to submit SQL statements) to a PHP file and then connect the PHP to my database?

I'm not sure how to connect my HTML interface to a PHP file to then connect to my database. I want to be able to enter SQL statements into my interface and have it retrieve and display data from my database?
Connect from client HTML to server with a PHP handler for GET or POST. In this handler method, implement your logic for database interaction for SQL statements.
MySQL is the most popular database system used with PHP.
I will try to explain this to you by storing data into the DB and getting the data from the DB to view in a table in the front end.Very often you will need to use a MySQL table to store data inside it and then output that data by using a PHP script. To display the table data it is best to use HTML, which upon filling in some data on the page invokes a PHP script which will update the MySQL table.
To populate a new database table with data you will first need an HTML page which will collect that data from the user. The following HTML code that and passes the information to a PHP script:
<form action="insert.php" method="post">
Value1: <input type="text" name = "field1" /><br/>
Value2: <input type="text" name = "field2" /><br/>
Value3: <input type="text" name = "field3" /><br/>
Value4: <input type="text" name = "field4" /><br/>
Value5: <input type="text" name = "field5" /><br/>
<input type="submit" />
</form>
The above HTML code will show the user 5 text fields, in which the user can input data and a Submit button. Upon clicking the Submit button the data submitted by the user will be passed to a script named insert.php.
That script can have a syntax similar to the following:
<?php
$username = "your_username";
$password = "your_pass";
$database = "your_db";
$mysqli = new mysqli("localhost", $username, $password, $database);
// Don't forget to properly escape your values before you send them to DB
// to prevent SQL injection attacks.
$field1 = $mysqli->real_escape_string($_POST['field1']);
$field2 = $mysqli->real_escape_string($_POST['field2']);
$field3 = $mysqli->real_escape_string($_POST['field3']);
$field4 = $mysqli->real_escape_string($_POST['field4']);
$field5 = $mysqli->real_escape_string($_POST['field5']);
$query = "INSERT INTO table_name (col1, col2, col3, col4, col5)
VALUES ('{$field1}','{$field2}','{$field3}','{$field4}','{$field5}')";
$mysqli->query($query);
$mysqli->close();
After the user submits the information, the insert.php script will save it in the database table. Then you may want to output that information, so that the user can see it on the page. The first command you will need to use is the SELECT FROM MySQL statement that has the following syntax:
SELECT * FROM table_name;
This is a basic MySQL query which will tell the script to select all the records from the table_name table. After the query is executed, usually you would want the result from it stored inside a variable. This can be done with the following PHP code:
<?php
$query = $mysqli->query("SELECT * FROM table_name");
The whole content of the table is now included in a PHP array with the name $result. Before you can output this data you should change each piece into a separate variable. There are two stages.
Now, we have to set up the loop. It will take each row of the result and print the data stored there. This way we will display all the records in the table:
$query = "SELECT * FROM table_name";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
}
/* free result set */
$result->free();
}
You can now write a full script to output the data. In this script the data is not formatted when it is printed:
<?php
$username = "username";
$password = "password";
$database = "your_database";
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM table_name";
echo "<b> <center>Database Output</center> </b> <br> <br>";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
echo '<b>'.$field1name.$field2name.'</b><br />';
echo $field5name.'<br />';
echo $field5name.'<br />';
echo $field5name;
}
/*freeresultset*/
$result->free();
}
This outputs a list of all the values stored in the database. This will give you a very basic output which is not useful for a live website. Instead, it would be better if you could format it into a table and display the information in it. To apply formatting you need to use HTML to print the result by including the variables in the correct spaces. The easiest way to do this is by closing the PHP tag and entering HTML normally. When you reach a variable position, include it as follows:
<?php echo $variablename; ?>
in the correct position in your code.
You can also use the PHP loop to repeat the appropriate code and include it as part of a larger table.
The final output will be:
<html>
<body>
<?php
$username = "username";
$password = "password";
$database = "your_database";
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM table_name";
echo '<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td> <font face="Arial">Value1</font> </td>
<td> <font face="Arial">Value2</font> </td>
<td> <font face="Arial">Value3</font> </td>
<td> <font face="Arial">Value4</font> </td>
<td> <font face="Arial">Value5</font> </td>
</tr>';
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
echo '<tr>
<td>'.$field1name.'</td>
<td>'.$field2name.'</td>
<td>'.$field3name.'</td>
<td>'.$field4name.'</td>
<td>'.$field5name.'</td>
</tr>';
}
$result->free();
}
?>
</body>
</html>
This code will print out table content and add an extra row for each record in the database, formatting the data as it is printed.
I hope this will help you to solve your issue.

Why query column return zeros when connect with ODBC connection to MS SQL?

I want get values from the cloud server on which MSSQL is running. I use ODBC connection in php to get data. But numeric field called Balance in cloud return zero values in myside which have non zero values. I have check the the datatype which return from cloud, and it is float.here is my code to fetch data.
<?php
$select_Total_Outstanding = "Select CustCode,CustName,Balance FROM AS_vwCustomer";
$result = odbc_exec($conn1, $select_Total_Outstanding);
?>
<table>
<tr>
<th>CustCode</th>
<th>CustName</th>
<th>Balance</th>
</tr>
<?php
while (odbc_fetch_row($result)) {
echo '<tr>';
$field1 = odbc_result($result,1);
$field2 = odbc_result($result,2);
$field3 = odbc_result($result,3);
echo '<td>'.$field1.'</td>';
echo '<td>'.$field2.'</td>';
echo '<td>'.$field3.'</td>';
echo '</tr>';
}
?>
</table>
AS_vwCustomer is a view created in the cloud server and I have observe the AS_somethingelse has a numeric field which return non zero values on myside successfully.Currently I have no access to the query of the view created and i think there is something wrong with the AS_vwCustomer Balance field.
Is there any other way to get values of that field?

How to fetch data in PHP with MySQLi?

I tried several times but cannot succeed in getting the right syntax—according to PHP 5.5.12 —to fetch single or multiple rows from my database.
session_start();
$con=mysqli_connect("localhost","root","","doortolearn");
if (!$con) {
echo "Could not connect to DBMS";
}
$query="select * from teacher where tremail='$_POST[email]' and trpasssword='$_POST[password]'";
$result=mysqli_query($con,$query);
$flag=FALSE;
while ($row=mysqli_fetch_array($result,MYSQLI_BOTH)) {
$_SESSION['email']=$row['email'];
$flag=TRUE;
}
First, you have no single quotes ' around $_POST[password]:
$query = "SELECT * FROM teacher WHERE tremail='". $_POST['email'] ."' and trpasssword='" . $_POST['password'] . "'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$flag = FALSE;
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$_SESSION['email'] = $row['email'];
$flag = TRUE;
}
But past that, do you even have a MySQL database connection set here? I see $con but is that really working?
Also, check if there are errors by adding or die(mysql_error($con)) to your mysqli_query($con, $query) line.
Also, you have a $_SESSION value, but do you even set session_start at the beginning of your script?
But I also recommend you use mysqli_stmt_bind_param for your values to at least escape them if you are not going to do basic validation:
$query = "SELECT * FROM teacher WHERE tremail=? and trpasssword=?";
mysqli_stmt_bind_param($query, 'ss', $_POST['email'], $_POST['password']);
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$flag = FALSE;
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$_SESSION['email'] = $row['email'];
$flag = TRUE;
}
To successfully fetch data from MySQL using mysqli extension in PHP you need to perform more or less three actions: connect, execute prepared statement, fetch data.
Connection:
The connection is really simple. There should always be only 3 lines of code for opening a connection. You enable error reporting, create new instance of mysqli, and set the correct charset.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db_name');
$mysqli->set_charset('utf8mb4');
Prepared statement
This is the tricky part. You need to prepare SQL statement to be executed. Careful, never concatenate PHP variables into SQL directly. Bind the variables using placeholders. Once the statement is ready you can execute it on the server.
$stmt = $mysqli->prepare('SELECT * FROM teacher WHERE tremail=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
Fetch the data
If your prepared statement should return some results, you need to fetch them and do something with the records. To fetch the result use get_result(). This will give you an object that you can iterate on to fetch each row one by one.
$result = $stmt->get_result();
foreach ($result as $row) {
echo $row['user_id'];
}
If you are only starting learning PHP, please consider learning PDO instead. It is easier to use and offers more functionality. Use mysqli only for legacy projects.
can You try this code
<?php $query=mysqli_query($connection, "SELECT * FROM user");
while($rows=mysqli_fetch_array($query)){ ?>
<tr>
<td><?php echo $rows['name']; ?></td>
<td><?php echo $rows['age']; ?></td>
<td><?php echo $rows['mobile']; ?></td>
<td><?php echo $rows['email']; ?></td>
</tr>
<?php } ?>
$r =$mysqli->query("select * from users");
while ( $row = $r->fetch_assoc() )
{
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['pwd']; ?></td>
</tr>
<?php
}
?>

Echo statement in PHP not executing in a specific manner

I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.

Categories