MSSQL and PHP echos repeating rows for same information - php

I am sorry about the title as I am not sure whether my problem is in the PHP or the MSSQL query. I am pretty sure it is php.
I am repairing a PHP page that accesses two different MSSQL tables. the page worked fine until we had a system-wide change that created new department ID's and hence some new department names.
I have this almost completely fixed now except one minor thing. When you click List all departments, it Lists all the departments and each link has the correct individuals under them.
The problem is it lists a link for EACH individual in that department name for example if there are 10 people in the Business department we have ten links to Business and all have the same information under them.
I want to make it so there is only 1 link for each department. the two tables are directory (columns involved are Displayname and Department) and departments (columns involved are name and id)
Can someone please tell me where I need to change this so it only prints one link to each department? Is the problem with my SQL query or the PHP?
here is the code
function listDepts() {
$query = "SELECT directory.Lastname, directory.Firstname, directory.email,
directory.phone, directory.Office, directory.Department, departments.id,
departments.name FROM directory FULL JOIN departments ON
directory.Department=departments.id ORDER BY name";
$result = mssql_query($query);
echo "<h3>Please select a department:</h3>\n";
echo "<ul>\n";
for ($i=0; $i<mssql_num_rows($result); ) {
$info = mssql_fetch_assoc($result);
echo "<li>$info[name]</li>\n";
}
echo "</ul>\n\n";
}
Other query
function displayResults($query) {
$result = mssql_query($query);
if (mssql_num_rows($result) > 0) {
for ($i=0; $i<mssql_num_rows($result); $i++) {
$info = mssql_fetch_assoc($result);
if ($info[dept_name] != $last_dept) {
if ($i > 0) {
echo "</table>\n\n";
}
echo "<h3>$info[dept_name]</h3>\n\n";
echo "<table id=\"directory_table\">\n";
echo "<tr>\n";
echo "<th>Name</th>\n";
echo "<th>E-mail</th>\n";
echo "<th>Phone</th>\n";
echo "<th>Office</th>\n";
echo "<th>Title</th>\n";
echo "</tr>\n";
}
if (!$info[dept_name] && $i==0) {
echo "<table id=\"directory_table\">\n";
echo "<tr>\n";
echo "<th>Name</th>\n";
echo "<th>E-mail</th>\n";
echo "<th>Phone</th>\n";
echo "<th>Office</th>\n";
echo "<th>Title</th>\n";
echo "</tr>\n";
}
if ($i % 2 == 0) {
echo "<tr class=\"even\">\n";
} else {
echo "<tr class=\"odd\">\n";
}
echo "<td>";
echo ($info[Firstname]) ? "$info[Firstname]" . " " . "$info[Lastname]" : " ";
echo "</td>\n";
echo "<td>";
echo ($info[email]) ? "$info[email]" : " ";
echo "</td>\n";
echo "<td>";
echo ($info[phone]) ? "$info[phone]" : " ";
echo "</td>\n";
echo "<td>";
echo ($info[office]) ? "$info[office]" : " ";
echo "</td>\n";
echo "<td>";
echo ($info[title]) ? "$info[title]" : " ";
echo "</td>\n";
$last_dept = $info[dept_name];
}
echo "</table>\n\n";
} else {
echo "<p>No results found.</p>\n\n";
}
}

If you're only using these two fields:
echo "<li>$info[name]</li>\n";
Why not just make your select query:
SELECT DISTINCT
name
FROM
departments
ORDER BY
name
You're not using anything from the directory table, so you don't need to take anything from it.
If you've got multiple departments, try:
echo "<li>$info[name]</li>\n";
And then updating your department code to search for employees in the department with that name.
Department code:
$theSQL = "SELECT * FROM directory WHERE department IN (SELECT id FROM departments WHERE name='$department') ORDER BY Lastname");

In your for loop at the end of each iteration $i needs to be evaluated.
It should be like
for ($i=0; $i<mssql_num_rows($result); $i++)
Another way (generally) of looping is
$query = mssql_query('your_query');
while ($row = mssql_fetch_assoc($query)){
echo "<li>$row['name']</li>\n";
}

Related

Multiple Tables of same Database on the same site

I want to display 9 different tables from my sql database in 9 different html created tables on the website.
In detail: I have 9 tables ("dt_bookmarks_01", "dt_bookmarks_02" etc.) with 4 columns "id" (which is primary and auto increment), icon (for favicon), link (url) and text (for the display text).
I've created 9 different html tables with bootstrap and want to output the content of each table in a different bootstrap table of my site.
My problem is that i have no idea how to get different "foreaches" or counter for each different table.
To automaticaly add new rows to the bootstrap table I use the count and foreach function. problem here is: I dont know how to seperate them from each other. If i have 4 entries in sql table 1 it multiplies the one and only entrie of sql table 2 to match the current count of 4.
I am very new to sql and php so I guess I just miss some fundamental functions or something.
document header:
php
$sql = "
SELECT *
FROM dt_bookmarks_01, dt_bookmarks_02";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
and for the html table I use:
php
<tbody>
<!--begin: SQL Selection -->
<?PHP
$count = 0;
foreach($rows as $item){
if (!empty($item['icon'])) {
$icon = '<img src="assets/media/bm-icons/'. $item['icon'] . '">';
}else{
$icon = '<img src="assets/media/bm-icons/default.png">';
}
$count++;
echo "<tr>";
/*echo "<td>" . $count . "</td>";*/
echo "<td> " . $icon . "</td>";
echo "<td> <a href=\"" . $item['link'] . "\"'>" . $item['text'] . "</a> </td>";
echo "<td></i> ";
echo "</i></td>";
echo "</tr>";
}
?>
<!--end: SQL Selection -->
</tbody>
I do not have a database on hand to give you an answer with complete code, but here is the idea:
<?php
for ($i = 1; $i <= 9; $i++)
{
$query = "SELECT index1,index2 FROM dt_bookmarks_0$i";
echo "<h1>This is the content of table $i</h1>";
# RUN THE QUERY HERE !!!
echo "<table>";
# EXTRACT THE RESULTS
foreach $rows as $item
{
echo "<tr><td>$item[index1]</td><td>$item[index2]</td></tr>"
}
echo "</table>";
echo "<br><br>";
}
?>
Loop on your tables.
In each table loop, you output the HTML code to display it's content.
Avoid SELECT *, specify your indexes (research "sql why avoid SELECT *")
So you loop twice. One time to go through the tables, the other to loop on the results.
so here is the new working code.
header:
<?PHP
require_once('/htdocs/_nt/mysql/data.php');
$sql = "
SELECT *
FROM dt_bookmarks";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
?>
and for the table output:
<?PHP
$count = 0;
foreach($rows as $item){
if ($item['category'] == talk) {
$count++;
echo "<tr>";
echo "<td> " . $icontalk . "</td>";
echo "<td> <a href=\"" . $item['url'] . "\"'>" . $item['text'] . "</a> </td>";
echo "</tr>";
}else{
echo "";
}
}
?>

MySql While loop taking too long to query

just wondered if there was a a faster way of running this query? I have over 250K rows in my 'results' table. The code searches the table for all of the different types of race a trainer has run. It the looks at how many races that trainer has ran in the type of race. Then it looks at hoe many races he/she has won. Hope this is enough information. Thanks for looking.
echo "<div style='text-align:center;'>";
echo "<table id='main_table'>";
echo "<tr ><td align = center colspan = 4>".$trainer."</td></tr>";
$result = mysqli_query($db,"SELECT
DISTINCT RaceType AS racetype
FROM results
WHERE trainer = '$trainer' ORDER BY RaceType ASC"); //placing_numerical,
while($row = mysqli_fetch_array( $result ))
{
echo "<tr>";
echo "<td>";
echo $row['racetype'];
echo "</td>";
echo "<td>";
$result_horse = mysqli_query($db,"
SELECT
COUNT(id) AS result_run
FROM results
WHERE trainer = '$trainer' AND RaceType = '".$row['racetype']."'
");
$row_horse = mysqli_fetch_array( $result_horse );
echo $row_horse['result_run'];
$a = $row_horse['result_run'];
echo "</td>";
echo "<td>";
$result_horse1 = mysqli_query($db,"
SELECT
COUNT(id) AS result_win
FROM results
WHERE trainer = '$trainer' AND RaceType = '".$row['racetype']."' AND placing_numerical = '1'
");
$row_horse1 = mysqli_fetch_array( $result_horse1 );
echo $row_horse1['result_win'];
$b = $row_horse1['result_win'];
echo "</td>";
echo "<td>";
$percent = ($b / $a ) * 100;
$percent = sprintf('%0.0f', $percent);
echo $percent."%";
echo "</td>";
echo "</tr>";
}
echo "</table>";
Here are two suggestions you can check :-
For row_horse and row_horse1 , use "mysqli_fetch_assoc" instead of "mysqli_fetch_array" .
Try to write a single query taking all the three queries and it will save you more time what you are expecting .

Displaying 2 records in a column using php

So I have a code
<?php
$showorder = "SELECT order_number FROM orders WHERE customer_number=522";
$orderesult = mysqli_query($con, $showorder);
$ord = mysqli_fetch_array($orderesult);
?>
in my database customer number 522 has 2 order numbers, when i tried to show the result, it only shows 1.
Here's my other code
echo "<table>";
echo "<th>Order Number</th><th>Order date</th>";
echo "<tr><td>";
echo $ord["order_number"];
echo "</td><td>";
echo $ord["order_date"];
echo "</td></tr>";
You just need to use while() here for getting all records, something like:
while($ord = mysqli_fetch_array($orderesult)){
//echo all value here
}
Also note that, if you want to print $ord["order_date"] than you must need to select column also in your query.
Otherwise, $ord will only contain order_number value.
Your SQL is missing the extra column.
Current SQL:
SELECT order_number FROM orders WHERE customer_number=522
Change to:
SELECT order_number, order_date FROM orders WHERE customer_number=522
Put mysqli_fetch_array($orderesult); in a while loop.
while($ord = mysqli_fetch_array($orderesult)) {
echo $ord["order_number"];
# code
}
Replace your code with the below code and then try again
<?php
$showorder = "SELECT order_number, order_date FROM orders WHERE customer_number=522";
$orderesult = mysqli_query($con, $showorder);
echo "<table>";
echo "<tr>";
echo "<th>Order Number</th><th>Order date</th>";
echo "</tr>";
while($ord = mysqli_fetch_array($orderesult)) {
echo "<tr>";
echo "<td>$ord['order_number']</td>";
echo "<td>$ord['order_date']</td>";
echo "</tr>";
}
echo "</table>";
?>
echo "<table>";
echo "<th>Order Number</th>";
while($ord = mysqli_fetch_array($orderesult)) {
echo "<tr><td>";
echo $ord["order_number"];
echo "</td></tr>";
}
you must use loop to show all result , and you can use echo one time .
while($ord = mysqli_fetch_array($orderesult)) {
echo "<table>
<th>Order Number</th><th>Order date</th>
<tr><td>".
$ord["order_number"]."
</td></tr>";
}

Splitting Long php generated HTML table?

I use a MySql query to select data from my DB and then print it in the form of a HTML Table. It works perfectly, fine but sometimes the table consists of hundreds of rows and the webpage looks incredibly akward. Is there a way to split the table side by side into 2 or 3 halves.
Present Output
Desired output
PHP
<?php
....
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
What would be the best way to achieve it?
Help would be appreciated.
You can use PHP to determine in your loop if the loop index is divisible by a certain number using something like this:
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
$rowCount = 1;
$numRows = count($results);
$maxRows = 12;
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
if($rowCount % $maxRows == 0 && $rowCount != $numRows) {
echo "</table><table class='dates' border='1'>";
}
$rowCount ++;
}
echo "</table>";
That's the basics of doing this. Basically in your loop you're testing each index to see if it's divisible by $maxRows, and if so then you're going to close your table and open a new one. You'll have to add the styling to place the tables side by side.
If you wanted to expand upon this concept you can set $maxRows to be an evaluation of $numRows. For instance if you wanted to split the items as close as possible to half in order to show just two tables, you could do... $numRows = count($results); $maxRows = round($numRows / 2);
Inspired by Robert Wade's answer:
<?php
....
echo "<h3>Classes attended :</h3>";
$i=0;
$maxRows=10;
foreach ($results as $dates) {
$a=$i/$maxRows == 0 ? "<table class='dates' border='1'>":"";
$b=$i/$maxRows == 0 ? "</table>":"";
echo $a;
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
echo $b;
$i++;
}
?>
At last, add some css style to the tables.
You can also use array_chunk() for splitting your results. Or instead of displaing a lot of tables next to each other you can make pagination and get only some range in your query. For example:
SELECT * FROM `clients` LIMIT 5, 10
Selects 10 rows beggining from row 5. Now, when you change your page, just change limit values.

PHP - Searching for records in a database whilst simultaneously ordering them and paginating them

Right, day 8 learning php and I feel that I have tried to do things in the wrong order.... I was fine up until yesterday. I have set myselft the task of creating a fake online book shop (seems popuar with all learn php books). First I created my products and listed them all on a page from the database.. easy, then I used a dropdown box to order the results... hard but did it eventually. Then tried to paginate, easy, then tried to join my ordering code and pagination code: most painful few hours of my life but complete. The I utilised a search bar.. easier then thought, an now I am trying to mix this search bar with my pagination and ordering code and my hair is falling out by the handful! I really wish I had attempted to learn all three at once but would have been a bit of a handful/headful.
So my problem is... It paginates... yay, it orders... yay however when I first see the results from a search... It paginates ok (shows me how many pages there are which is always the correct value) however when I click to view the 2nd page it the stops showing me the results of the search, instead takes me to page 2 of ALL products in the database. The same also happens if I try and order the list, it changes to an ordered list of all the products and tells me the search criteria is empty!
Sorry for such a long winded question, I just cant work out where I have slipped up!
Thank you soo much for anybody who can help!
Heres the code:
booksearch.php:
(have taken out all the irrelevent code!)
<?php $query1 = "SELECT *
FROM booktable";
// execute the query
$results1 = mysql_query($query1)
or die(mysql_error());
// count the number of rows that are selected from the table
$field = mysql_num_fields( $results1 );
// echo $field;
for ( $i = 0; $i < $field; $i++ )
{
$names[$i] = mysql_field_name( $results1, $i );
}
?>
<form name="searchbook" action="productssearch.php" method="get">
<br />
Got For It:<input type="text" id="searchbar" name="searchterm" value="Enter anything and we will search on title, author, publisher and ISBN"></input>
<br /><br />
<input type="submit" name="Search" value=" - Search - "></input>
</form>
productssearch.php:
require "dbconn.php";
$term = $_GET['searchterm'];
$records_per_page = 10;
//If user set the sort order, save to session var - else set default
if(#$_POST['order'])
{
$_SESSION['order'] = trim($_POST['order']);
}
elseif(!isset($_SESSION['order']))
{
$_SESSION['order'] = 'bookname';
}
//Determine the total records and pages
$query = mysql_query ("SELECT COUNT(bookname)
FROM booktable
WHERE bookname LIKE '%".$term."%'
OR bookisbn LIKE '%".$term."%'
OR bookpub LIKE '%".$term."%'
OR bookauthor LIKE '%".$term."%'");
$total_records = mysql_result($query, 0);
$total_pages = ceil($total_records / $records_per_page);
//Set the page to load
$page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1;
if($page<1 || $page>$total_pages)
{
$page = 1;
}
//Create limit var for query
$limit_start = ($page-1) * $records_per_page;
//Create and run query for records on current page
$query = mysql_query ("SELECT bookname, bookauthor, bookpub, bookisbn
FROM booktable
WHERE bookname LIKE '%".$term."%'
OR bookisbn LIKE '%".$term."%'
OR bookpub LIKE '%".$term."%'
OR bookauthor LIKE '%".$term."%'
ORDER BY ".mysql_real_escape_string($_SESSION['order'])." ASC
LIMIT $limit_start, $records_per_page");
//Prepare output
//**************************************************************
$numrow = mysql_num_rows($query);
//Create pagination links
$navLinks = '';
//Prev page
if($page > 1)
{
$prevPage = $page - 1;
$navLinks .= "<a href='productssearch.php?page=$prevPage'>Prev</a> ";
}
else
{
$navLinks .= "Prev ";
}
//Individual pages
for($p=1; $p<=$total_pages; $p++)
{
$pageNo = ($p == $page) ? "<b>{$p}</b>" : $p;
$navLinks .= "<a class='pagin' href='productssearch.php?page=$p'>$pageNo</a> ";
}
//next page
if($page < $total_pages)
{
$nextPage = $page + 1;
$navLinks .= "<a href='productssearch.php?page=$nextPage'>Next</a>";
}
else
{
$navLinks .= "Next";
}
?>
(IRRELEVANT STUFF FROM MIDDLE REMOVED)
<div id="mid">
<?php
echo "<table>";
echo "<tr>";
echo "<td>";
echo "</td>";
echo "<td class='toprow'>";
echo "Book Title";
echo "</td>";
echo "<td class='toprow'>";
echo "Book Author";
echo "</td>";
echo "<td class='toprow'>";
echo "Book Publisher";
echo "</td>";
echo "<td class='toprow'>";
echo "Book ISBN";
echo "</td>";
echo "<td>";
echo "</th>";
echo "</tr>";
while ($row = mysql_fetch_assoc($query))
{
$bookname = $row['bookname'];
$bookauthor = $row['bookauthor'];
$bookpub = $row['bookpub'];
$bookisbn = $row['bookisbn'];
// send the values to the browser as a row in a html table
echo "<tr>";
echo "<tr>";
echo "<td>";
echo "<a href='addtolist.php?bookname=".$bookname."&bookauthor=".$bookauthor."&bookpub=".$bookpub."&bookisbn=".$bookisbn."'>Add to basket</a>";
echo "</td>";
echo "<td>";
echo $bookname;
echo "</td>";
echo "<td>";
echo $bookauthor;
echo "</td>";
echo "<td>";
echo $bookpub;
echo "</td>";
echo "<td>";
echo $bookisbn;
echo "</td>";
echo "</tr>";
}
?>
</table>
<?php
echo "<br />";
echo $navLinks; ?>
Please note I am a real beginner so I am not learning how to make secure or safe code.,.. I havnt even encrypted user and admin passwords yet... just trying to learn the mechanics of the script!
Thank you all again for taking the time to read my "windy" question!
It's becuase you are not carrying your:
$term = $_GET['searchterm'];
to the next page.
So when you search a blank string you are getting returned back the results for everything.
Your pagination links should contain the search term used in your POST.
To all who are reading this: I'm keeping it SIMPLE, as Phil has commented he's a beginner. We all know there are considerations that are NOT being taken into account in this answer!
Phil, the answer lies in the construction of your navlinks code.
When you click one of the navlinks, it passes the limits for your pagination, but does NOT pass the search term.
You would need to modify your navlinks to be along the lines of:
$navLinks .= "<a href='productssearch.php?page=$prevPage&searchterm=$term'>Prev</a> ";
and
$navLinks .= "<a class='pagin' href='productssearch.php?page=$psearchterm=$term'>$pageNo</a> ";
and
$navLinks .= "<a href='productssearch.php?page=$nextPage&searchterm=$term'>Next</a>";
etc.

Categories