php-sql groups data with the same category - php

How can I print my fetch rows into groups of data?
For example i have these on my database
title category
one number
two number
three number
a letter
b letter
c letter
and I wanted to print it out on a different table.
table1 table2
number letter
one a
two b
three c
here's what I've tried.
$select = "SELECT * FROM `table` ORDER BY `category`";
$result = mysql_query($select);
$current_cat = null;
while ($rows = mysql_fetch_array($result))
{
if ($rows["category"] != $current_cat)
{
$current_cat = $rows["category"];
echo "<p>$current_cat</p>";
}
echo"$rows[title]";
}
the output of these codes is like this
number
one
two
three
letter
a
b
c
but then again, I wanted it to be in separate table.

You could add an if statement to test if the $current_cat is equal to the previous loops $current_cat. Do so by adding a new variable $last_cat, setting it equal to the current iterations $current_cat at the end of the while loop. Here is an example
$select = "SELECT * FROM `table` ORDER BY `category`";
$result = mysql_query($select);
$current_cat = null;
$last_cat = null;
while ($rows = mysql_fetch_array($result)) {
if ($current_cat == null) {
// Create a table with an id name of the first table
echo "<table id='" . $rows["category"] . "'>";
// Write the first row of the table - Category Title
echo "<tr class='categoryTitle'><td>" . $rows["category"] . "</td></tr>";
}
// Set the $current_cat to current loop category value
$current_cat = $rows["category"];
if ($last_cat != null) {
if ($current_cat != $last_cat) {
// Close table from previous $current_cat
echo "</table>";
// Create new table with id name of the category
echo "<table id='" . $rows["category"] . "'>";
// Write the first row of the table - Category Title
echo "<tr class='categoryTitle'><td>" . $rows["category"] . "</td></tr>";
}
}
}
// Write new row in table with the value of the title
echo "<tr><td>" . $rows[title] . "</td></tr>";
// set the $last_cat to the value of $current_cat at the end of the loop
$last_cat = $current_cat;
}
// Close the last table after while loop ends
echo "</table>";
This will allow you to create separate tables based on the category name no matter how many categories you have and allow you to style the tables based on the category name.

Related

Display name instead ID from another table

I'm facing a problem to display a name on a table, only the id is displayed I have tried some inner join queries without luck i got 2 tables
Table 1 = empresas
Here is where all the data lives:
the number 9 in u_tip corresponds to the ID of the data that is in tipoempresas table
Table 2 = tipoempresas
I want to display the name of the type not the ID
I'm using this code to display the data in a html table
$result = mysqli_query($conn,"SELECT * FROM empresas");
$i = 0;
while($row = $result->fetch_assoc())
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
You are already there you just need to use join statement and specify the column you want to display
$result = mysqli_query($conn,"SELECT * FROM empresas AS e INNER JOIN tipoempresas AS t ON t.id = e.u_tip");
$i = 0;
while($row = $result->fetch_assoc())
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value['Nombre'] . "</td>"; //SPECIFY THE COLUMN YOU WANT TO DISPLAY
}
echo "</tr>";

PHP Mysql query multiple items

I have this part of code:
resultrights = $conn->query("SELECT userid, page FROM pagerights WHERE userid = '" . $_SESSION['uid'] . "'");
while ($rowrightss = $resultrights->fetch_assoc()) {
echo $rowrightss['page']."<br>";
}
This works. It just echoes the numbers
1
2
3
5
Perfectly fine.
Now, I want to select a few buttons based on that numbers. They are button numbers, declared else in the DB.
Somewhere later I have this:
<?php
$i = 0;
$result = $conn->query("select pagenumber, pagetitle from pages WHERE pagenumber = '" . $_SESSION['assignedpage'] . "'");
echo "<html>";
echo "<body>";
echo '<table cellpadding="20">';
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['pagenumber'];
$name = $row['pagetitle'];
$i++;
//if this is first value in row, create new row
if ($i % 3 == 1) {
echo "<tr>";
}
echo '<td><button1 id="groteknop" class="btn-state state-start" onclick="Switchf();"><i id="knopje" class="icon icon-start"></i></button1></td>';
//if this is third value in row, end row
if ($i % 3 == 0) {
echo "</tr>";
}
}
//if the counter is not divisible by 3, we have an open row
$spacercells = 3 - ($i % 3);
if ($spacercells < 3) {
for ($j=1; $j<=$spacercells; $j++) {
echo "<td></td>";
}
echo "</tr>";
}
echo "</select>";
$conn->close();
?>
What I am trying to achieve, is instead of the pagenumber = the session value assigned page, I want to select all buttons from the result of the query before. Endresult: I want to display button 1, 2, 3, 5. This numbers are coming from the first query. So when these numbers change, and they do, because they are selected based on userid, I want to display the result of that query.
How can I get that working?
Try with this query
select pagenumber, pagetitle from pages WHERE pagenumber in
(SELECT page FROM pagerights WHERE userid = '" . $_SESSION['uid'] . "')
To me this seems a task for an inner join, which would join pagerights table with the pages table. If I understood your question correctly, then pagerights.page should match page.pagenumber.
SELECT page.pagenumber, page.pagetitle FROM pagerights
INNER JOIN page ON pagerights.page=page.pagenumber
WHERE userid=...
Substitute the user id from session in the place of ... in the query. this way you need to run only a single query.

PHP dropdown to query for another dropdown to query for results

Right! I'm a complete PHP noob but have managed to completely blag/copy/paste/graft together some PHP that queries what I want it to query and return me a dropdown.
Now. I can bastardise this for another dropdown. HOWEVER. This dropdown should be returning results based on an array returned from the first query.
AND. Finally once this dropdown has been selected it should be printing the results in a table below.
I understand that I should be using Javascript to temporarily store the values returned by the dropdowns.
So it goes as such, I have three queries that all work in MySQL:
select id, name, replace(replace(arrange, 'c,', ''), '|', ',')
from cats
limit 10;
This query now returns the "arrange" in an array-friendly format which contains the subcategories which I simply copy and paste, but for this want to return as a string and query.
select id, name, Group_concat(replace(replace(arrange, 'i,', ''), '|', ',')) As Products_in_Category from cats
where id in (ARRAY FROM PREVIOUS QUERY REPLACE);
This now returns a massive array, that you guessed it, I want to define as a string and query to return for the final query.
select p.id,substring(c.name, 1, 60) As Name, c.code, sum(qty) As Sold
from cart c
join prods p on c.item = p.id
and order_status = ('Processed Order')
and p.id in ([ARRAY RETURNED FROM PREVIOUS GROUP_CONCAT)
group by code
order by sold desc
So, the code I have for the PHP is:
<?php
$host = '';
$user = '';
$pass = '';
$db = '';
//Database Connection
mysql_connect($host, $user, $pass)
or die('Could not connect: ' . mysql_error());
mysql_select_db($db)
or die ('Could not select database ' . mysql_error());
// SQL QUERY TO NAME
$sql = "select id, name, replace(replace(arrange, 'c,', ''), '|', ',')
from kcommerce_cats
where arrange like ('c,%')";
$result = mysql_query($sql);
echo "<select name='type'>";
while($row = mysql_fetch_assoc($result)){
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo "</select>";
?>
So how do I now select the replace as a string.
How do I then query that replace as the In for the 2nd dropdown.
And from there, how the devil should I declare the group_concat as a string to be queried for the final in.
Add to that I would love to be able to put all that in an HTML table.
I am asking a lot here but have the principles of what I want in my head, just not the PHP ability!!!
So I haven't managed to work out the dropdown/select side of things, but I have managed to answer the question of how to pass a result from one query and then query against that - also I have managed to print the results in an HTML table.
So, in order for the querying of the categories which will eventually be the basis of the whole page and its' dropdowns:
$query = "select id, name, replace(replace(arrange, 'c,', ''), '|', ',') As Arrange
from cats
where arrange like ('c,%') limit 10";
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
The above is doing the first query in preparation for the storing of the result as a string.
while ($row = mysql_fetch_array($result)) {
$arrange = $row['Arrange'];
}
echo $arrange;
mysql_free_result($result);
Now this is saying lookup the value of arrange from the first query, the echo prints it out so you can confirm the values returned. The important part is the $arrange that is now in the code to store that array.
//Query Subcategories
$query = "select id, name, Group_concat(replace(replace(arrange, 'i,', ''), '|', ',')) As Products from cats
where id in (".$arrange.")";
This is the subcategory query with the important addition of querying against the results from $arrange.
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_array($result)) {
$prodsarray = $row['Products'];
}
echo "<br>";
echo $prodsarray;
I have then repeated the process as above, returning the Group Concat as a string which can then be used as per the first line of the 2nd query above.
$query = "select p.id As ID,substring(c.name, 1, 100) As Name, c.code As Code, sum(qty) As Sold,
p.price As Price, format(p.price*1.2,2) As VAT, p.rrp As RRP, p.cost As Cost
from cart c
join prods p on c.item = p.id
and order_status = ('Processed Order')
and p.id in (".$prodsarray.")
and date_ordered < now()-interval 3 month
group by code
order by sold desc";
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
The next step is to echo the results from this query into a table.
echo "<table class='equalDivide' cellpadding='0'cellspacing='0' width='100%' border = '3'><tr>";
echo "<td width = '5%' align='center'>ID</td>";
echo "<td width = '35%'align='center'>Name</td>";
echo "<td width = '15%' align='center'>Code</td>";
echo "<td width = '7.5%' align='center'>Sold</td>";
echo "<td width = '7.5%' align='center'>Price</td>";
echo "<td width = '7.5%' align='center'>VAT</td>";
echo "<td width = '7.5%' align='center'>RRP</td>";
echo "<td width = '7.5%' align='center'>Cost</td>";
echo "</tr></table><br>";
Above is the hardcoding of the field names.
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_array($result)) {
echo "<table class='equalDivide' cellpadding='0'cellspacing='0' width='100%' border = '1'><tr>";
echo "<td width = '5%'>".$row['ID']."</td>";
echo "<td width = '35%'>".$row['Name']."</td>";
echo "<td width = '15%'>".$row['Code']."</td>";
echo "<td width = '7.5%'>".$row['Sold']."</td>";
echo "<td width = '7.5%'>".$row['Price']."</td>";
echo "<td width = '7.5%'>".$row['VAT']."</td>";
echo "<td width = '7.5%'>".$row['RRP']."</td>";
echo "<td width = '7.5%'>".$row['Cost']."</td>";
echo "</tr></table>";
}
This is the loop that fills the table with the results, notice the ['Sold'] under row is whatI declared the row as in the select query.
Next step is to turn the first two queries into dropdown selects, then I am done! Boom!

PHP: table structure

I'm developing a website that has some audio courses, each course can have multiple lessons. I want to display each course in its own table with its different lessons.
This is my SQL statement:
Table: courses
id, title
Table: lessons
id, cid (course id), title, date, file
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
Can someone help me with the PHP code?
This is the I code I have written:
mysql_select_db($database_config, $config);
mysql_query("set names utf8");
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<p><span class='heading1'>" . $row['course'] . "</span> </p> ";
echo "<p class='datum'>Posted onder <a href='*'>*</a>, latest update on " . strftime("%A %d %B %Y %H:%M", strtotime($row['date']));
}
echo "</p>";
echo "<class id='text'>";
echo "<p>...</p>";
echo "<table border: none cellpadding='1' cellspacing='1'>";
echo "<tr>";
echo "<th>Nr.</th>";
echo "<th width='450'>Lesso</th>";
echo "<th>Date</th>";
echo "<th>Download</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['nr'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . strftime("%d/%m/%Y", strtotime($row['date'])) . "</td>";
echo "<td><a href='audio/" . rawurlencode($row['file']) . "'>MP3</a></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
}
?>
One thing that comes to mind is you're starting with lessons and pulling the course details over with it. That means you're going to have a new row per lesson with a joined course. You may want to sort by course (so they're grouped) then (in PHP) keep a tally of "current course". When the course changes, switch to new heading paragraph, table, etc.
Pseudo code:
$currentCourse = null; // intitialize the course
$query = your select sorted by course;
while ($row in $query)
{
if ($currentCourse != $row['course'])
{
if (!is_null($currentCourse))
{
// there was a course before it, close the current one
}
// begin setting up heading1, table beginning, etc.
$currentCourse = $row['course']; // set this as the active course
}
// dump the current row as a table entry
}
// close the table (same code as in the second if statement)
You close the while loop on line 8 of your code block. Remove that '}' on line 8.
Also the HTML element doesn't exists!
I think I know what's your problem. You need a while loop that loops al the "courses" and in that loop you execute a second query where you select the lessons where the course_id is equal to the current course id you're looping. A little dummy code for you.
<?php
while($row = mysql_fetch_assoc(mysql_query("SELECT * FROM courses"))) {
//display the course
while($row2 = mysql_fetch_assoc(mysql_query("SELECT * FROM lessons WHERE course_id=" . $row['id']))) {
//display the lessons of that course
}
}
?>

Retrieving values from several tables in a MySQL database

I have a MySQL database called "bookfeather" with several tables that contain list books. Under each table, each book has a given number of votes. The PHP code below allows the user to enter in a book title ($entry), and then returns the total number of votes that book has in all tables ($sum).
How could I use PHP to make a 2-column, 25-row table that lists the 25 books in the database with the highest value for $sum (in descending order)?
Thanks in advance,
John
mysql_connect("mysqlv10", "username", "password") or die(mysql_error());
mysql_select_db("bookfeather") or die(mysql_error());
// We preform a bit of filtering
$entry = strip_tags($entry);
$entry = trim ($entry);
$entry = mysql_real_escape_string($entry);
$result = mysql_query("SHOW TABLES FROM bookfeather")
or die(mysql_error());
$table_list = array();
while(list($table)= mysql_fetch_row($result))
{
$sqlA = "SELECT COUNT(*) FROM `$table` WHERE `site` LIKE '$entry'";
$resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
list($isThere) = mysql_fetch_row($resA);
$isThere = intval($isThere);
if ($isThere)
{
$table_list[] = $table;
}
}
//$r=mysql_query("SELECT * , votes_up - votes_down AS effective_vote FROM `$table[0]` ORDER BY effective_vote DESC");
if(mysql_num_rows($resA)>0){
foreach ($table_list as $table) {
$sql = "SELECT votes_up FROM `$table` WHERE `site` LIKE '$entry'";
$sql1 = mysql_query($sql) or die("$sql:".mysql_error());
while ($row = mysql_fetch_assoc($sql1)) {
$votes[$table] = $row['votes_up'];
$sum += $row['votes_up'];
//echo $table . ': "' . $row['votes_up'] . " for $entry from $table\"<br />";
}
}
}
else{
print "<p class=\"topic2\">the book \"$entry\" has not been added to any category</p>\n";
}
//within your loop over the DB rows
//$votes[$table] = $row['votes_up'];
//afterwards
if($sum>0){
print "<table class=\"navbarb\">\n";
print "<tr>";
print "<td class='sitenameb'>".'<a type="amzn" category="books" class="links2b">'.$entry.'</a>'."</td>";
print "</tr>\n";
print "</table>\n";
//echo "<p class=\"topic3\">".''.$entry.''. "</p>\n";
echo "<p class=\"topic4\">". number_format($sum) . ' votes in total.'."</p>\n";
Try something like this. All of this hasn't been tested so please add comments for changes. I'll work with you to get the code right.
// After getting your array of tables formated like
$tableArray = array("`tableA`", "`tableB`", "`tableC`");
// create a table statement
$tableStatement = implode(", ", $tableArray);
// create a join statement
$joinStatement = "";
for ($i = 1; $i < count($tableArray); $i++) {
if ($joinStatement != "")
$joinStatement .= " AND ";
$joinStatement .= $tableArray[0] . ".site = " . $tableArray[$i] . ".site"
}
$firstTable = $tableArray[0];
$sql = "SELECT SUM(votes_up) FROM " . $tableStatement . " WHERE " . $joinStatement . " AND " . $firstTable . ".site LIKE '" . $entry . "' GROUP BY " . $firstTable . ".site ORDER BY SUM(votes_up) DESC";
Edit --------
I now realize that the query above won't work perfectly because votes_up will be ambiguous. Also because you probably want to be doing joins that grab records that are only in one table. I think the concept is the right direction even though the query may not be perfect.
You can do something like
$selectStatement = "SUM(tableA.votes_up) + SUM(tableB.votes_up) as total_votes_up"
I did something like this recently. In your database, you'll have to rename each field to a corresponding book name.php like (TaleofTwoCities.php). Now on your page that will display the vote results, you'll need to include some php files that will drive the database query on each load. I called mine "engine1.php" and "engine2.php." These will do all your sorting for you.
$query1 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 0,1"));
$query2 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 1,1"));
$query3 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 2,1"));
and so on.. then..
$num1 = "$query1[0]";
$num2 = "$query2[0]";
$num3 = "$query3[0]";
That part sorts your listings by the number of votes from highest to lowest, with url, in your case, being the name of the books(remember you want it to end in .php - you'll see why in a second), and counter being the field that logs your votes.
Make your second engine.php file and add something like this:
$vquery1 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book1.php'"));
$vquery2 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book2.php'"));
$vnum1 = "$vquery1[0]";
$vnum2 = "$vquery2[0]";
and so on... Until you get to 25 for both this and engine 1.
Now, in your results page, after you put in the require_once(engine.php) and require_once(engine2.php) at the start of your body, start an HTML table. You only want two columns, so it'll be something like..
<table border=1 cellspacing=0 cellpadding=0>
<tr>
<?php include $num1; ?>
</tr>
<tr>
<?php include $num2; ?>
</tr>
And so on... By naming your field with "book1.php" and including the engines, $num1 will change to a different .php file depending on votes from high to low. Now all you have to do is make small php files for each book like so - no headers or anything because you're inserting it into the middle of html code already:
<td style="width:650px;"><center><img src="images/book1.jpg" alt="" border="none"
/></a></center></td>
<td style="width:150px;">Votes: <?php echo $vnum1;?></td>
And there you have it. A code that will dynamically give you results from high to low depending on the number of votes each book has.

Categories