paginate through records with php and mssql server - php

i just moved to asp and php and i'm able to connect to mssql database and retrieve records. what i'm currenlty finding it hard to do is how to do pagination through the records showing 10 records at a time.
<table width="40%" border="1" align="center" cellpadding="5" cellspacing="5">
<tr>
<td>Item-</td>
<td>Quantity</td>
<td>Price</td>
</tr>
<?php
while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
?>
<tr>
<td> <?php echo $row['item'] ?></td>
<td><?php echo $row['quantity'] ?></td>
<td><?php echo $row['rprice'] ?></td>
</tr>
<?php
}
?>
<tr>
<td><div align="left">Previous</div></td>
<td> </td>
<td><div align="right">Next</div></td>
</tr>
</table>
PHP SCRIPT
<?php require_once('Connections/db.php'); ?>
<?php
$sql = "SELECT * FROM item_table order by item desc";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $stmt );
if ($row_count === false)
echo "Error in retrieveing row count.";
else
echo $row_count;
?>

You can use OFFSET to get specific results:
$startingRow = 5;
$rowsPerPage = 10;
SELECT * FROM item_table order by item desc
OFFSET $startingRow ROWS FETCH NEXT $rowsPerPage ROWS ONLY
You will get results from 5th to 15th

If you want to do the paging in SQL Server, you can use the ROW_NUMBER function to order your rows & specify a starting point in the WHERE clause, and number of records in the TOP clause.
See the examples below. I prefer the CTE syntax.
--inline syntax
select top(10) * from (select row_number() over(order by item) as rid, * from item_table) as d where rid>10;
--cte syntax
with _numberedData as
(
select
row_number() over(order by item) as rid,
*
from item_table
)
select top(10)
*
from _numberedData
where rid>10;

Related

Displaying SQL Query in HTML table (php)

Trying to get counts from 2 different tables into a simple HTML table.
This is my code:
$sql = "SELECT COUNT(*) FROM tasks";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
if ($result->num_rows > 0) { ?>
<table style="width:100%">
<tr>
<th>Total</th>
</tr>
<?php while($row = $result->fetch_assoc()) { ?>
<tr>
<td><?=$rowcount;?></td>
</tr>
<?php } ?>
</table>
<?php } else { echo "0 results"; } ?>
When I run the code, it shows the amount of rows in the table, but it also creates the amount of rows with the number in it (i.e. 281 rows).
Table
281
281
281
281 etc.
My idea was to copy and paste the above to show a second table set of results (if it was correct), but is there a better way of doing this? I've been looking at how I would display SELECT (select COUNT(*) from tasks) , (select count(*) from quotes) into the following format (HTML):
Table
Count
Tasks
281
Quotes
42000
First of all your query does produces only one row for a table, not 281.
The second - I omit usage of prepared SQL statements with placeholders, which should always be used in a real project whenever applyable.
$rows = [];
foreach(['Tasks', 'Quotes'] as $table ){
$result = $conn->query("SELECT '$table' as 'table', count(*) as 'count' FROM $table");
if( $result )
$rows[] = $result->fetch_assoc();
}
if( empty( $rows ) )
print "0 results";
else {?>
<table style="width:100%">
<tr><th>Table</th><th>Count</th></tr>
<?=implode(
"\n",
array_map(function($row){
return "<tr><td>${row['table']}</td><td>${row['count']}</td></tr>";
}, $rows)
)?>
</table>
<?php }
I've been looking at how I would display SELECT (select COUNT() from
tasks) , (select count() from quotes) into the following format
(HTML)
You can just run the queries query, and use the result of the first to create the first row of the table, then the result of the second to create the second row. Since COUNT queries always return exactly 1 row when there's no GROUP BY, it's quite simple to do really:
$sql1 = "SELECT COUNT(*) FROM tasks";
$result1 = $conn->query($sql1);
if ($row = $result1->fetch_array()) $taskCount = $row[0];
else $taskCount = "error";
$sql2 = "SELECT COUNT(*) FROM quotes";
$result2 = $conn->query($sql2);
if ($row = $result2->fetch_array()) $quoteCount = $row[0];
else $quoteCount = "error";
?>
<table style="width:100%">
<tr>
<th>Table</th>
<th>Count</th>
</tr>
<tr>
<td>Tasks</td>
<td><?php echo $taskCount; ?></td>
</tr>
<tr>
<td>Quotes</td>
<td><?php echo $quoteCount; ?></td>
</tr>
</table>
Another way, if you want the HTML structure to be less repetitive / dependent on the tables queries, is to UNION the SELECTs into a single query:
$sql = "SELECT 'Tasks' AS 'table', COUNT(*) as 'count' FROM tasks";
$sql .= " UNION ";
$sql .= "SELECT 'Quotes' AS 'table', COUNT(*) as 'count' FROM quotes";
$result = $conn->query($sql);
?>
<table style="width:100%">
<tr>
<th>Table</th>
<th>Count</th>
</tr>
<?php
while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo $row["table"]; ?></td>
<td><?php echo $row["count"]; ?></td>
</tr>
<?php
}
?>
</table>

How to display two or more array on same table

Hey guys I have one mysql table tick where i have some info like user id now to display that data I need to retrieve from user table name of the user based on that id
?php
$mysql5 = mysqli_query($dbc, "SELECT * FROM tick where status='1' ORDER BY dt DESC LIMIT 6 ");
if($indtbl = mysqli_fetch_array($mysql5))
{
$title = $indtbl['tickettitle'];
$company = $indtbl['companyname'];
$companyid =$indtbl['compid'];
$trackid = $indtbl['trackid'];
$assignto = $indtbl['assignto'];
$priority = $indtbl['priority'];
}
?>
and user table query is based on first one
<?php
$findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
if($rest = mysqli_fetch_array($findresults2323))
{
$userimg = $rest['img'];
$fname1 = $rest['fname'];
$lname1 = $rest['lname'];
}
?>
now the problem is when i am fetching the array
<thead>
<tr>
<th class="text-left">Title</th>
<th>Company</th>
<th>Ticket ID</th>
<th>Assign To</th>
<th>Priority</th>
</tr>
</thead>
<?php
while($rowten = mysqli_fetch_array($mysql5)) {
$retrive11 = mysqli_fetch_array($findresults23);
?>
<tr>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["tickettitle"]; ?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["companyname"];?> <?php echo $rowten["compid"];?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["trackid"]; ?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["priority"]; ?></td>
</tr>
<?php
}
?>
i am getting the error
Notice: Trying to access array offset on value of type null on line 459
line 459 is
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?></td>
what I am doing wrong
In order to use 2 queries, you need to run the second query inside of the loop so it retrieves the specific user record for the given result from the tick query.
while($rowten = mysqli_fetch_array($mysql5)) {
$assignto = $rowten['assignto'];
$findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
$retrive11 = mysqli_fetch_array($findresults23);
However, this is very inefficient as it requires a query on the user table for every result in the tick query. The proper way of doing this is to use a single query with a join.
SELECT tick.*, users.fname FROM tick LEFT JOIN users ON (tick.assignto=users.id) where tick.status='1' ORDER BY tick.dt DESC LIMIT 6
The result of this query will have all the data from both your queries in one result.

How to run two statements in mysqli_query

I need to run two statements to return the data I need. The below code will return all needed except the count column which can be retrieved from a different table.
How can I run these two statements in the same code to retrieve the count as well?
Here is the code I have:
<?php
$query = "SELECT * from $CLIENTS_DATABASE order by id DESC";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $row["name"]; ?> </td>
<td><?php echo $row["url"]; ?> </td>
<td><?php echo $row["secret"]; ?> </td>
<td><?php echo $row["count"]; ?> </td>
</tr>
<?php
}
mysqli_free_result($result);
}
?>
The other statement that the count data I need is this:
$query = "SELECT COUNT(*) as count from visits where id_client='$result[id]'"
Thanks for your time and any help you can provide.
Join the two queries.
$query = "SELECT order.*, IFNULL(c.count, 0) AS count
FROM $CLIENTS_DATABASE AS order
LEFT JOIN (SELECT id_client, COUNT(*) AS count
FROM visits
GROUP BY id_client) AS c
ON c.id_client = order.id
ORDER BY order.id DESC";

using foreach and while together in PHP to generate table

I've done something similar to this table below quite a few times, where I use a while statement to populate the <td> section of a table, but I've never done it before where part of the <td> is populated with a foreach statement, and it's confusing me.
In this example, I create a table, then I populate the first column with a list of suppliers, based on the number of tables inside of my database. (each supplier has its own table).
$supplierList = array();
$showTable = "SHOW TABLES from dbOne";
$getSuppliers = mysqli_query($con, $showTable);
while ($row = mysqli_fetch_row($getSuppliers)) {
$supplierList[] = $row;
}
$supplierList = array_reduce($supplierList, 'array_merge', array());
Now I have my array that contains the list of all my suppliers, and I use that to generate the <td>s in my table.
<table>
<thead>
<th style="text-align: center;">Supplier</th>
<th style="text-align: center;">Earliest line</th>
<th style="text-align: center;">Latest line</th>
<th style="text-align: center;"># of total lines</th>
</thead>
<?php
foreach ($supplierList as $subList) {
$supplierName = $subList;
$earlyExp = "SELECT date FROM $subList ORDER BY date DESC LIMIT 1" ;
$earlyExpQuery = mysqli_query($con, $earlyExp);
$lateExp = "SELECT date FROM $subList ORDER BY date ASC LIMIT 1" ;
$lateExpQuery = mysqli_query($con, $lateExp);
$countLines = "SELECT * from $subList";
$countLinesQuery = mysqli_query($con, $countLines);
$countLinesCount = mysqli_num_rows($countLinesQuery);
while ($row = mysqli_fetch_array($earlyExpQuery)) {
$earlyExpDate = $row['date'];
?>
<tbody>
<td><img src = "/img/suppliers/<?= $supplierName ?>.png"></td>
<td style="text-align: center;"><?= $earlyExpDate ?></td>
<td style="text-align: center;"><?= $lateExpDate ?></td>
<td style="text-align: center;"><?= $countLinesCount ?></td>
</tbody>
<?php
}
}
?>
</table>
The table itself builds correctly, and displays each supplier in a unique row. I cannot figure out though how to populate the other parts of the row with the information based off the unique supplier in the foreach statement.
Okay, I sorted this out. In case it helps anyone else, here's how I did it:
This code goes in the same spot as my post above - so in between the header and the body of the table. I did not need to use any <tr>.
<?php
foreach ($supplierList as $subList) {
$supplierName = $subList;
$earlyExp = "SELECT * FROM $subList where dateOne != '' UNION SELECT * from $subList where dateTwo != '' ORDER BY dateTwo, dateOne ASC LIMIT 1" ;
$earlyExpQuery = mysqli_query($con, $earlyExp);
$lateExp = "SELECT * FROM $subList where dateOne != '' UNION SELECT * from $subList where dateTwo != '' ORDER BY dateTwo, dateOne DESC LIMIT 1" ;
$lateExpQuery = mysqli_query($con, $lateExp);
$countLines = "SELECT * from $subList";
$countLinesQuery = mysqli_query($con, $countLines);
$countLinesCount = mysqli_num_rows($countLinesQuery);
while ($row = mysqli_fetch_array($earlyExpQuery)) {
$earlyExpDate = $row['dateTwo'] ? $row['dateTwo'] : $row['dateOne'];
}
while ($row = mysqli_fetch_array($lateExpQuery)) {
$lateExpDate = $row['dateTwo'] ? $row['dateTwo'] : $row['dateOne'];
?>
They key is that I had to close off each individual while statement except the last one - closing that after I closed the </tbody> tag but before the </table>, like so:
</tbody>
<?php
}
}
?>
</table>

select query and while loop doesn't return all rows correctly

can you explain me why when i try this query it returns to me only half of rows?
For example, if $records is made by 4 values it only get row 1 and 3 from DB.
What's wrong?
$query=mysql_query("SELECT * FROM ".DB_PREF."books WHERE book_id IN ('".$records."')");
while($fetch=mysql_fetch_assoc($query))
{
global $book_id, $book_title, $book_description, $book_author_id, $book_author_name, $book_author_surname;
$book_id=$fetch['book_id'];
$book_title=$fetch['book_title'];
$book_description=$fetch['book_description'];
$book_author_id=$fetch['book_author_id'];
$query=mysql_query("SELECT * FROM ".DB_PREF."profiles WHERE user_id='".$book_author_id."'");
$fetch=mysql_fetch_assoc($query);
$book_author_name=$fetch['user_name'];
$book_author_surname=$fetch['user_surname'];
getModule('htmlmodule...');
}
Are you overwriting your $fetch variable in the loop? Maybe try:
$fetch2=mysql_fetch_assoc($query);
Or, even better, use a join in your SQL:
$query=mysql_query("SELECT * FROM ".DB_PREF."books LEFT JOIN ".DB_PREF."profiles ON book_author_id = user_id WHERE book_id IN ('".$records."')");
Then just get everything you want out of that single query.
MY DO WHILE
mysql_select_db($database_lolx, $lolx);
$query_Recordset1 = "SELECT * FROM person";
$Recordset1 = mysql_query($query_Recordset1, $lolx) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
<table border="1">
<tr>
<td>id</td>
<td>emal</td>
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['id']; ?></td>
<td><?php echo $row_Recordset1['emal']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>

Categories