Separate subject headings in list - php

<?php require_once('Connections/pdoConnect.php'); ?>
<?php
// Issue the query
$pdo_recordset1 = $conn->query("SELECT id, title, author, subject FROM audio");
$pdo_recordset1->setFetchMode(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Audio List</title>
</head>
<body>
<?php
// Now iterate over every row and display it
$n = 0;
while($r = $pdo_recordset1->fetch(PDO::FETCH_ASSOC))
{
?>
<a href="PDO_detail.php?item=<?php echo $r['id']?>">
<?php echo ($r['subject'])?><?php echo ($r['title'])?><?php echo ($r['author'])?></a><br />
<?php
++$n;
}
if(0 == $n)
{
echo "Sorry there are no items to display";
}
?>
</body>
</html>
This produces a list of all entries in the database. However I want to separate out the "subject" data as a heading above each title within that subject group. Eg:
SUBJECT 1
Title 1
Title 2
Title 3
SUBJECT 2
Title 1
Title 2
etc
How should I modify the above code to achieve this? I'm guessing it will need a nested loop, but not sure how to put this together.

You can add the subjects into an array in one loop and then in for each subject in that array you can go through the whole list and echo the title and author if the subject matches.
$subjects = array();
array_push($subjects, $r['subject']);
usage requested so something like this though if someone could edit it to be correct and more efficient...
<?php
$subjects = array();$n=0;
while($r = $pdo_recordset1->fetch(PDO::FETCH_ASSOC))
{array_push($subjects, $r['subject']);}
while($s = $subject->$subjects)
{
while($r = $pdo_recordset1->fetch(PDO::FETCH_ASSOC))
{
if($r['subject']==$s)
{
?><a href="PDO_detail.php?item=<?php echo $r['id']?>">
<?php echo ($r['subject']); echo ($r['title']); echo ($r['author'])?>
</a><br /><?php
}
++$n;
}
if(0 == $n){echo "Sorry there are no items to display";}
}
?>

Related

display content containing html tags from database using php

Table name : Post, column name : content
say, below data along with the html tag and style is stored in content column
<h1 style="color:red">test</h1>
I'm using below php code to display it
<?php
$sql = "SELECT content FROM post where id = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<?php echo htmlspecialchars($row['content'], ENT_QUOTES); ?>
<?php
}
}
else {
echo "0 rasdesults";
}
$conn->close();
?>
expectation : test in red color but
output : only "test"
Please replace you echo syntaxt
<?php echo htmlspecialchars($row['content'], ENT_QUOTES); ?>
with below line
<?php echo htmlspecialchars_decode($row['content']);?>
Hope this will help you!
Thanks & regards.
Shishil Patel

How to make a unordered list using fetch_assoc from database and arrays

Trying to create a list by selecting booking references from the database, sorting them into an array and then having each array value passed into each item on the list. e.g. first booking reference on the first item, second reference on the second item etc...
Here is the code.
<html>
<head>
<title>Manage booking</title>
<link rel="stylesheet" type="text/css" href="style1.css">
</head>
<body>
<h3>Oadby Granville Tennis Club Manage Booking</h3>
<br><br><br>
<?php
include "dbconnect.php";
session_start();
$login_ID = $_SESSION['id'];
$query = "SELECT Booking_ID
FROM `booking`
WHERE Login_ID = '$login_ID';";
$bookingArray = array();
$result = $mysqli -> query($query);
while ($row = $result->fetch_assoc()){
printf ("%s<br>", $reference = $row["Booking_ID"]);
array_push($bookingArray, $reference . "<br>");
}
print_r ($bookingArray);
?>
<table border="1" style="width:50%">
<caption>Please select a booking to edit:</caption>
<tr>
<td>
<ul style="list-style-type:circle">
<?php
$arrayNo = 1;
while ($row = $result->fetch_assoc()){
printf ("<li><a href='UpdateBooking.php'>Booking ID:%s</a>" . $bookingArray[$arrayNo] . "</li><br>");
$arrayNo = $arrayNo + 1;
}
?>
<li>Booking ID</li>
</ul>
</td>
</tr>
</body>
</html>
Your first while ($row = $result->fetch_assoc()) {..} transfers everything into $bookingArray until the result set is exhausted. With your second while ($row = $result->fetch_assoc()) {..} you don't get anything more. Additionally, your use of printf is weired.
Try this instead your second loop:
foreach($bookingArray as $Booking)
{
echo "<li><a href='UpdateBooking.php'>Booking ID:$Booking</a></li><br>";
}
However, UpdateBooking.php wont know which booking should be changed. So you should consider to append the BookingId to the URL.
Edit 2016-03-02:
To append the BookingId to the URL you should try:
foreach($bookingArray as $Booking)
{
echo "<li><a href='UpdateBooking.php?BookingId=" . urlencode($Booking) . "'>Booking ID:$Booking</a></li><br>";
}

PHP Loop, Add a comma after every loop except the last

I've got a query that loops through some product names and puts them down on the page. As part of the loop, it adds a comma to the end, so it looks like this:
Products: Shirts, Pants, Ties, Jackets,
Notice that I'm getting a comma after the last product. Also, they are all links, so I can't use some strreplace fx or similar:
Here's my code:
<?php
$product_query = mysql_query("select * from products_table);
$row_product_query = mysql_fetch_assoc($product_query);
$totalRows_product_query = mysql_num_rows($product_query);
?>
<strong>Products: </strong>
<?php if ($totalRows_product_query > 0) { ?>
<?php do { ?>
<span><?php echo $row_product_query['products_name']; ?></span>
<strong>, </strong>
<?php } while ($row_product_query = mysql_fetch_assoc($product_query)); ?>
<?php } ?><br />
What do I need to do to make that last comma not appear?
Thanks in advance as always.
using the php implode function
<?php
$str = "";
$product_query = mysql_query("select * from products_table");
$row_product_query = mysql_fetch_assoc($product_query);
$totalRows_product_query = mysql_num_rows($product_query);
$cnt = 0;
?>
<strong>Products: </strong>
<?php if ($totalRows_product_query > 0) { ?>
<?php do {
$arr[$cnt] = '<span>'.$row_product_query['products_name'].'</span>';
$cnt++;
<?php } while ($row_product_query = mysql_fetch_assoc($product_query)); ?>
<?php }
echo implode("<strong>,</strong>",$arr);
?><br />
Fix how they are being stored/entered into the database?
otherwise,
<?php echo str_replace(",", "", $row_product_query['products_name']); ?>
should work
As #tucker said, you could use the implode function. Implode Function. You would use it with an array like so
$a_string = implode(",",$the_result_array);
This would give you your desired results.

display php search results in html table

im running this php script and not quite getting the result i want. at the moment its giving me this output
scuba tank
mike
0.00
450.00
5.00
2012-06-04 18:50:22
scuba tank
liam
80.00
350.00
2.50
2012-06-04 19:00:09
Displaying 3 results
scuba tank
josh
410.00
0.00
5.00
2012-06-04 19:00:09
its pretty much what i want except the line displaying 3 results should be displayed at the end instead of before the last entry. what do i need to do to my script to fix this?
<?php
$host = "localhost";
$user = "root";
$pass = null;
// ========================================
$dbhost = #mysql_connect($host, $user, $pass) or die("Unable to connect to server");
#mysql_select_db("divebay") or die("Unable to select database");
$var = "scuba";
$query = trim($var);
if(!isset($query)){
echo "Your search was invalid";
exit;
} //line 18
$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);
if($numrows == 0){
echo "Sorry, your search did not return any results";
}
$i = 0;
while($i < $numrows){
$row = mysql_fetch_array($result);
$ID = $row['ID'];
$name = $row['name'];
$owner = $row['owner'];
$holder = $row['holder'];
$start = $row['sprice'];
$current = $row['cprice'];
$instant = $row['iprice'];
$inc = $row['incprice'];
$image = $row['img'];
$time = $row['stime'];
$length = $row['duration'];
echo "
<?xml version = '1.0' encoding = 'utf-8'?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>searchdbresults</title>
</head>
<body>
<table style='width = 800px;'>
<tr style ='height = 200px;'>
<td style ='width = 200px;'></td>
<td style ='width = 300px;'>
<div style ='180px'> $name </div>
<div> $owner </div>
</td>
<td style='width =200px'>
<div style='height = 100px'> $current </div>
<div style='height = 50px'> $instant </div>
<div> $inc </div>
</td>
<td> $time </td>
</tr>
";
$i++;
}
echo "
<tr> Displaying $numrows results</tr>
</table>
</body>
</html>
";
?>
I can't comment, but there is several problems in your code.
1st the style must double quote
<div style="width:100%;">
for example.
2nd : there must be a td inside a tr for this line : Displaying $numrows results
and last one i see is : you have this :
<?xml version = '1.0' encoding = 'utf-8'?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>searchdbresults</title>
</head>
<body>
inside your while loop, so its several times in your page, and it must not
You also have the table opening in your while loop, but not the closing. So it's opened several times, but opened only once.
edit : you also need to add protection into your sql query
Your script is generating "messy" HTML. From what I see your so generated HTML page will have (in the current example) 3 DOCTYPE definitions, 3 head's as well as 3 opening table tags and only one closing /table. And also you don't need to echo every single html entity, you can use plain html in php files
Try something like that:
<?xml version = '1.0' encoding = 'utf-8'?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>searchdbresults</title>
</head>
<body>
<?php
$host = "localhost";
$user = "root";
$pass = null;
// ========================================
$dbhost = #mysql_connect($host, $user, $pass) or die("Unable to connect to server");
#mysql_select_db("divebay") or die("Unable to select database");
$var = "scuba";
$query = trim($var);
if(!isset($query)){
echo "Your search was invalid";
exit;
} //line 18
$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);
if($numrows == 0){
echo "Sorry, your search did not return any results";
}
else{
?>
<table style='width = 800px;'>
<?php
$i = 0;
while($i < $numrows){
$row = mysql_fetch_array($result);
$ID = $row['ID'];
$name = $row['name'];
$owner = $row['owner'];
$holder = $row['holder'];
$start = $row['sprice'];
$current = $row['cprice'];
$instant = $row['iprice'];
$inc = $row['incprice'];
$image = $row['img'];
$time = $row['stime'];
$length = $row['duration'];
?>
<tr style ="height: 200px;">
<td style ="width: 200px;"></td>
<td style ="width: 300px;">
<div style ="width: 180px"><?php echo $name; ?></div>
<div><?php echo $owner; ?></div>
</td>
<td style="width: 200px;">
<div style="height: 100px;"><?php echo $current; ?></div>
<div style="height: 50px;"><?php echo $instant; ?></div>
<div><?php echo $inc; ?></div>
</td>
<td><?php echo $time; ?></td>
</tr>
<?php
i++;
} //end of while
} //end of else
?>
<tr>
<td colspan="4">Displaying <?php echo $numrows; ?> results</td>
</tr>
</table>
</html>
And also consider preventing SQL Injection too: http://bobby-tables.com/
I think you would be much better off if you separated your php and html into separate files. You seem to be losing track of your opening " and closing ". If you want your
<tr> Displaying $numrows results</tr>
at the bottom of your page, then take it out of the table.
I'd suggest simplifying your table a little bit, maybe taking the 'Displaying $numrows results' out of the table entirely.
The line '<tr> Displaying $numrows results</tr>' is not valid HTML. <tr> means 'Define a new table row', but it needs a <td> inside it to wrap the content. Because most rows of your table contain several TD elements, whilst this row only contains one piece of information, you would need to tell that table cell to span multiple columns.
A good way of debugging this sort of thing is to feed the generated HTML to http://validator.w3.org/, or replace the $variables with sample data and feed the template code to a validator. This is usually a little frustrating at first (as it will force you to be exact about the HTML version you want to use, etc) but it is a good way of tracing problems. If you feed the following HTML snippet into the W3 validator, it will give you some useful feedback:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>A</title></head>
<body>
<table><tr><td>aaa</td><td>bbb</td></tr>
<tr><td>cccc</td><td>dddd</td></tr>
<tr>Test</tr>
</table>
</body>
</html>
The validator tells you that: Line 7, Column 5: character data is not allowed here
<tr>Test</tr>
In other words, the TR element should not directly contain text.
It also says that: Line 7, Column 13: end tag for "tr" which is not finished
<tr>Test</tr>
"Most likely, you nested tags and closed them in the wrong order... Another possibility is that you used an element which requires a child element that you did not include. Hence the parent element is "not finished", not complete. For instance, in HTML the <head> element must contain a <title> child element, lists require appropriate list items (<ul> and <ol> require <li> ...), and so on."
Once you have the static HTML looking, and validating, the way you want, you can then add the PHP loops back in, but this time you can compare the script output to your working HTML example.

Grouped/Stratified Reports using PHP and MySQL

I am trying to generate a grouped/stratified report using PHP and MySQL.
tbl_items has the following fields: (1) UserName and (2) ItemName
A single user can have multiple items listed.
I want to generate an output where the data is stratified by each user. For example:
*UserName #1
-ItemName 1
-ItemName 2
*UserName #2
-ItemName 3
*UserName #3
-ItemName 4
-ItemName 5
I keep playing with the code, trying to put a loop inside a loop...but can't figure out how to do it! This is what I have so far:
<?
$sql="SELECT * FROM $tbl_items";
$result=mysql_query($sql);
?>
<html>
<body>
<? php while($rows=mysql_fetch_array($result)){ ?>
Item: <? echo $rows['ItemName']; ?> (<? echo $rows['UserName']; ?>)
<?php } mysql_close(); ?>
</body>
</html>
Please help!
while($row=mysql_fetch_array($result))
{
$itemsByUser[$row['UserName']][] = $row;
}
foreach($itemsByUser as $user => $items)
{
echo $user . "<br>";
foreach($items as $array)
{
echo "-" . $array['ItemName'];
}
}
This first creates an array that is order by Username. This means each user has an element in the array that contains an array of the items that have been assigned to the user.
Then, we go over each user and print out all of the items.

Categories