PHP Mysql query multiple items - php

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.

Related

Show only one time a repeat record and all of the other different elements adding to it in PHP

I have a table called Orders with 2 attributes: id_order and id_product.
In this table, I save the list of the products bought adding this to a single id of order, something like this
id_order - id_product
1 - 1
1 - 2
1 - 5
1 - 6
2 - 4
2 - 8
2 - 14
3 - 1
I want to show this record in a table, BUT only showing one(1) time the id of order.
<?php
include "con.php";
$sql = "SELECT DISTINCT a.id_order , b.id_product FROM orders a JOIN orders b ON a.id_order=b.id_order";
$sentence1 = $con->prepare($sql);
$sentence1->execute();
$sentence1->bind_result($id, $product);
?>
<html>
<body>
<table border="3">
<tr>
<td>ID of order</td>
<td>ID of products from this order</td>
</tr>
<?php
while ($sentence1->fetch()) {
echo "<tr>";
echo "<td>" . $id . "</td>";
echo "<td>" . $product . "</td>";
echo "</tr>";
}
$sentence1->close();
?>
The problem is this SQL show repeatable times the number of id_order I want something like this:
id_order - id_product
1 - 1
- 2
- 5
- 6
____________
2 - 4
- 8
- 14
____________
3 - 1
The result I want is:
Another design:
While iterating over your result set in PHP, you can keep track of whether you encounter a new id value. If so, then display it in a table cell, otherwise do not display it.
$id_prev = NULL;
while ($sentencie->fetch()) {
echo "<tr>";
if ($id != $id_prev) {
echo "<td>" . $id . "</td>";
$id_prev = $id;
}
else {
echo "<td></td>"; // you could try adding spaces here for padding
}
echo "<td>" . $product . "</td>";
echo "</tr>";
}
As for the separator line, this is probably something which should be handled in your CSS/HTML layer.
Update:
It looks like your new requirement is to have the id table cells span multiple product rows. One option would be to use the rowspan attribute of the table cell. The trick here is that we need to iterate across an entire id before we know how many products there are.
$id_prev = NULL;
$products = array();
function displayRow($id, $products) {
for ($x = 0; $x < count($products); $x++) {
echo "<tr>";
if ($x == 0) {
echo "<td rowspan=\"" . count($products) . "\">" . $id . "</td>";
}
echo "<td>" . $products[$x] . "</td>";
echo "</tr>";
}
}
while ($sentencie->fetch()) {
if ($id != $id_prev) {
displayRow($id, $products);
$products = array();
$id_prev = $id;
}
array_push($products, $product);
}
// DON'T forget to call displayRow() one last time, to cover the final id
// appearing in your result set
displayRow($id_prev, $products);
Here sql command .
$sql = "SELECT DISTINCT id_order, GROUP_CONCAT(DISTINCT id_product ORDER BY id_product) AS child_id_list FROM orders group by id_order ORDER BY id_order";
$sentence1 = $con->prepare($sql);
$sentence1->execute();
$sentence1->bind_result($id, $product);

PHP, While loop not showing results

i am new to PHP and mysql, I am trying to build a table. However, I have a very interesting bug that i can't fix.
code:
//Initializing mysql queries
//-----------------------SELECTING GOALS------------
$sql= "SELECT * FROM goals";
$records = mysql_query($sql);
//-----------------------SELECTING SERVICES---------
$sql2= "SELECT * FROM services";
$records2 = mysql_query($sql2);
//----------------SELECTING THE JUNCTION----------
$sql3 = "SELECT services.sid AS sid, services.name, objectives.oid
FROM services, objectives, servo
WHERE servo.s_id = services.id AND servo.obj_id = objectives.id";
$records3 = mysql_query($sql3);
$sql4 = "SELECT oid, gid, statement, GROUP_CONCAT(DISTINCT gid) AS GOID
FROM goals, objectives, obgoals
WHERE obgoals.go_id = goals.id AND obgoals.ob_id = objectives.id
GROUP BY oid";
$records4 = mysql_query($sql4);
<?php
while ($product = mysql_fetch_assoc($records2)) {
echo "<tr>";
$sid = $product['sid'];
$service = $product['name'];
echo "<td><a href='objectives.php?sid=" . $sid . "&service=" . $service . "'>" . $product['sid'] . "</a> </td>";
echo "<td>".$product['name']."</td>";
echo "<td>";
while ($g4services = mysql_fetch_assoc($records)) {
echo $g4services['gid'];
}
echo"</td>" ;
}
?>
Basically, my table has 30 rows and 3 columns, the last column is supposed to print out values from a database, this part is done by this piece of code
while ($g4services = mysql_fetch_assoc($records)) {
echo $g4services['gid'];
}
However, instead of printing the results for each row, it only prints the results for the first row, basically the first while loop runs and creates the the table with the 30 rows, but the second while loop only prints values on first row only. Essentially this is happening:
|SID|Name Of Service| Objectives|
-------------------------------
|S1| Service 1 | make the best cars|
|s2| Service 2 | |
|s3| Service 3 | |
|s4| Service 5 | |
|s5| Service 5 | |
.....
.....
....
|s30| Service30 | |
for some reason, my objectives column is not populated by the while loop, it only works for the first row. If someone can help me work the while loop to print the values for every row, it will be huge help. I will greatly appreciate it. Thanks.
The problem is that you're reading all the results of $records during the first iteration of the outer while loop. On future iterations, there are no more rows left, so the inner while loop completes immediately.
You can read those results once into a variable outside the loop, and then show that variable during the loop:
$all_g4services = '';
while ($g4services = mysql_fetch_assoc($records)) {
$all_g4services .= $g4services['gid'];
}
while ($product = mysql_fetch_assoc($records2)) {
echo "<tr>";
$sid = $product['sid'];
$service = $product['name'];
echo "<td><a href='objectives.php?sid=" . $sid . "&service=" . $service . "'>" . $product['sid'] . "</a> </td>";
echo "<td>".$product['name']."</td>";
echo "<td>$all_g4services;</td>" ;
}
Your second while loop is not required. It is runnning for each row. Remove it. Then for each row you have to find the entry that matches and echo only that.
echo $g4services['gid']
I dont know how to correct it for you as I dont know the relationship between the two.

Fetch 2 querys at once

I have 2 tables, in 1 table there are lists of all the episodes from a movie and in the other table there are the streams from the episode. Every episode got his own id so the streams are linked via the id from the episode.
But now I have a problem: I want to make a episode-list and at the same time I want to insert a link to the stream. So that means that I have to fetch 2 tables at the same time but I don't know how. This is my code
<?php
include 'connection.php';
$a = (int)$_GET['a'];
if ($result = $con->prepare("SELECT id, ep_nr, ep_title FROM anime_episode WHERE ani_id = $a"))
{
$result->execute();
$result->bind_result($eid, $nr, $title);
while ($result2 = $con->prepare("SELECT * FROM anime_stream WHERE ep_id = $eid"))
{
$result2->execute();
$result2->bind_result($eid, $etitle, $lang, $sname, $link, $uploadedby);
echo '<div id="list-box">';
echo '<table cellspacing="0">';
while ($result->fetch() && $result2->fetch())
{
echo '<tr>';
echo '<td width="50">' . $nr . '</td>' . '<td>' . $title . '</td>' . '<td>' . $link. '</td>';
echo '</tr>';
}
echo '</div>';
echo '</table>';
}
}
$con->close();
?>
As Strawberry suggests, I believe your looking to join the two table based on the foreign key and select the content of both tables, somethig like...
select
epi.*,
str.*
from
anime-episode epi
inner join
anime-stream str on epi.ani-id = str.epi-id
where
epi.ani-id = $id
This assumes that your episodes will always have at least one stream as an inner join will only return a row (with the column of both tables) when a record is found in each of the tables of the join. A Left Outer join can be used which will still return movies even if no streams exist for a given episode.
Can't find underline on my tablet!
A query something like this should do the trick.
SELECT ae.id, ae.ep_nr, ae.ep_title, as.* FROM anime_episode ae
LEFT JOIN anime_stream as ON as.ep_id = ae.id
WHERE ae.ani_id = [$arg]

php-sql groups data with the same category

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.

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