PHP MYSQL nested join - php

<?php
require "includes/dbh_l4d2.php";
$sql = "
SELECT *
FROM vpk
JOIN maps
ON vpk.vpk_id = maps.vpk_id";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html><html><head><title>Website Title</title>
<link rel = "stylesheet" type = "text/css" href = "assets/css/tek_style.css" /></head>
<body>
<table>
<tr><th>VPK</th><th>MAP</th></tr>
<?php
$result_num_rows = mysqli_num_rows($result);
if( $result_num_rows> 0) {
//while($row = mysqli_fetch_array($result)) {
while($row = $result->fetch_assoc()) {
echo '<tr><td id="'.$row["alpha_anchor"].'" rowspan="'.$row["map_count"].'" class="first_row">'.
'<h3 id="'.$row["anchor"].'">'.$row["vpk_title"].'</h3>'.$row["vpk_file"].'<br>'.
'<a class="details" href="'.$row[details].'">Details</a> '.
'<i>Download vpk</i>'.
'</td></tr>';
for ($i=0; $i < $row["map_count"]-1; $i++) {
echo '<tr><td>'.$row["map_name"].'></td></tr>';
}
}
}
?>
</table></body></html>
Here is the output from the code
This is what I want it to look like
What needs to be done to make this work correctly??? Thanks in advance for any help.

Your nested loop is getting map_name from the same row, not each row of results.
What you can do is use GROUP_CONCAT() to combine all the map names into a single row of results, then use explode() to split them up when creating the table.
<?php
require "includes/dbh_l4d2.php";
$sql = "SELECT vpk.*, GROUP_CONCAT(maps.map_name) AS map_names
FROM vpk
INNER JOIN maps ON vpk.vpk_id = maps.vpk_id
GROUP BY vpk.vpk_id";
//$sql = "SELECT * FROM vpk, maps JOIN vpk ON vpk.vpk_id = maps.vpk_id";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html><html><head><title>Website Title</title>
<link rel = "stylesheet" type = "text/css" href = "assets/css/tek_style.css" /></head>
<body>
<table>
<tr><th>VPK</th><th>MAP</th></tr>
<?php
$result_num_rows = mysqli_num_rows($result);
if( $result_num_rows> 0) {
//while($row = mysqli_fetch_array($result)) {
while($row = $result->fetch_assoc()) {
$map_names = explode(',', $row['map_names']);
echo '<tr><td id="'.$row["alpha_anchor"].'" rowspan="'.$row["map_count"].'" class="first_row">'.
'<h3 id="'.$row["anchor"].'">'.$row["vpk_title"].'</h3>'.$row["vpk_file"].'<br>'.
'<a class="details" href="'.$row[details].'">Details</a> '.
'<i>Download vpk</i>'.
'</td></tr>';
foreach ($map_names as $map_name) {
echo '<tr><td>'.$map_name.'></td></tr>';
}
}
}
?>
</table></body></html>

Related

Displaying details from list of persons using php mysqli

I am trying to display a list of persons. On clicking the list , more details on the person must be shown.
members.php: -a page to list all members
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Our members are</h1>
<?php
include 'config.php';
session_start();
$sql = "SELECT name from users";
$result = $conn->query($sql);
echo '<table>';
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo '<tr>';
$_SESSION['selection'] = $row['name'];
echo '<td>'.$row['name'].'</td>';
echo '</tr>';
}
}
echo '</table>';
$conn->close();
?>
</body>
view.php -the page to show more details:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
include 'config.php';
session_start();
$pkey = $_SESSION['selection'];
$new = "SELECT * FROM users where name = '$pkey'";
$display = $conn->query($new);
$result = $display->fetch_assoc();
echo 'Name:'.$result['name'];
echo 'Rollno:'.$result['rool_no'];
echo 'Description:'.$result['description'];
$conn->close();
?>
</body>
on using session , always the details of last person in the list is shown.
How to display the corresonding details??
finally you are saving last name in the session variable $_SESSION['selection'] = $row['name']; so you getting the last name .while loop end with last name and you saving it in session.you are not using session as array know that.
my advice is not use session. session is not required here.
while($row = $result->fetch_assoc())
{
echo '<tr>';
$_SESSION['selection'] = $row['name'];
echo '<td>'.$row['name'].'</td>';
echo '</tr>';
}
change these lines in members.php
while($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '</tr>';
}
and change these line in view.php
<body>
<?php
include 'config.php';
session_start();
$pkey = $_REQUEST['name'];//change this line alone
$new = "SELECT * FROM users where name = '$pkey'";
$display = $conn->query($new);
$result = $display->fetch_assoc();
echo 'Name:'.$result['name'];
echo 'Rollno:'.$result['rool_no'];
echo 'Description:'.$result['description'];
$conn->close();
?>

php pagination for my members

You guys are helping me greatly. Please I have created a members page which I want to use pagination but it shows only one member's id in all ids.
Here is an image:
Here is my code:
<html>
<head>
<title>MEMBERS</title>
<link rel="icon" href="guyt.gif" type="image/x-icon">
<link rel="stylesheet" type="text/css" media="all" href="style.css">
</head>
<body>
<?php include 'connect.php'; ?>
<?php include 'functions.php'; ?>
<?php include 'header.php'; ?>
<div id="sidebar">
<br>
<?php include 'lists.php'; ?>
</div>
</body>
</html>
here is the lists.php code which contains the pagination:
<?php
$per_page = 5;
if(!isset($_GET['page'])){
$page = 1;
} else {
$page = $_GET['page'];
}
if($page<=1)
$start = 0;
else
$start = $page * $per_page - $per_page;
$mem_query = mysql_query("SELECT id FROM register");
while($run_mem = mysql_fetch_array($mem_query)){
$id = $run_mem['id'];
$first = getuser($id, 'first');
$last = getuser($id, 'last');
}
$sql = "SELECT * FROM register";
$num_rows = mysql_num_rows(mysql_query($sql));
$num_pages = ceil($num_rows / $per_page);
$sql .= " LIMIT $start, $per_page";
$result = mysql_query($sql);
While($row = mysql_fetch_array($result)){
echo "<div class='header'><table width='98%'><tr><td><div align='left'>$first $last</div></td><td><div align='right'><a href='profile.php?user=$id'>VISIT PROFILE</a></div></td></tr></table></div><br>";
}
$prev = $page - 1;
$next = $page + 1;
echo "<hr>";
if($prev > 0)
echo "<a href='?page=$prev' class='box'>Previous</a></font> ";
if($page < ceil($num_rows/$per_page))
echo " <a href='?page=$next' class='box'>Next</a></font>";
?>
if I change this:
$sql = "SELECT * FROM register";
to this:
$sql = "SELECT * FROM register WHERE id='$id'";
it will display like that same user but just once. please help me
You should output the property of each row you are looping in :
While($row = mysql_fetch_array($result)){
echo "<div class='header'><table width='98%'><tr><td><div align='left'>" . $row['name'] . "</div></td><td><div align='right'><a href='profile.php?user=$id'>VISIT PROFILE</a></div></td></tr></table></div><br>";
}
That's assuming the name is stored in a "name" key. Adapt it to your db structure.

PHP MySQL undefined Index and other errors

having trouble getting a script of mine to run correctly, I have 2 undefined index errors and an invalid argument supplied error that for the life of me I can't figure out why I'm getting. the 2 undefined index errors come from these lines.
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
and
if (!is_null($_GET['page']))
and my invalid argument error is this
Warning: Invalid argument supplied for foreach() in
generated from this
<?php foreach ($books as $book) : ?>
my full code between the two classes is this.. any ideas of what I've done wrong? tearing my hair out over this.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Catalog</title>
</head>
<body bgcolor="white">
<?php
/////////////////////////////////////////////////
//connect to db
/////////////////////////////////////////////////
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
{
$thesort = $_GET['order'];
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY ".$_GET['order'];
}
else
{
$thesort = "courseTitle";
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY $thesort";
}
//if page is null go to first page otherwise query for correct page
if (!is_null($_GET['page']))
{
$query = $query." LIMIT ".($_GET['page']*8-8).", 8";
}
else
{
$query = $query." LIMIT 0, 8";
}
//query result
$books = $db->query($query);
//get number of overall rows
$query2 = $db->query("SELECT * FROM book");
$count = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$count = $count->fetch();
$count = $count['totalRecords'];
?>
<table border =" 1">
<tr>
<th bgcolor="#6495ed"><a href="?order=course">Course #</th>
<th bgcolor="#6495ed"><a href="?order=courseTitle">Course Title</th>
<th bgcolor="#6495ed"><a href="?order=bookTitle">Book Title</th>
<th bgcolor="#6495ed"></th>
<th bgcolor="#6495ed"><a href="?order=price">Price</th>
</tr>
<?php foreach ($books as $book) : ?>
<tr>
<td><?php echo $book['course']; ?></td>
<td><?php echo $book['courseTitle']; ?></td>
<td><?php echo $book['bookTitle']; ?></td>
<td><?php
$bookcourse = $book['course'];
$isbn = $book['isbn13'];
$booklink = "<a href=\"course.php?course=$bookcourse&isbn=$isbn\">";
echo $booklink ;?><img src='images/<?php echo $book['isbn13'].'.jpg'; ?>'></a></td>
<td><?php echo $book['price']; ?></td>
</tr>
<?php endforeach; ?>
</tr>
</table>
<?php
//paging function... not sure if it works correctly?
for ($j=1; $j <= ceil($count/8); $j++)
{ ?>
<a href=<?php echo "?page=".$j."&order=".$thesort; ?>><?php echo $j; ?></a>
<?php
}?>
</body>
</html>
**course.php**
<?php
//get data from index.php
$course = $_GET['course'];
$isbn = $_GET['isbn'];
//connect to db
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
$query = "Select * FROM book, course, author, publisher
WHERE book.isbn13 = $isbn AND book.course = '$course' AND book.course = course.courseID AND book.bookID = author.bookID AND book.publisher = publisher.publisherID
ORDER BY book.bookID";
//query results
$books = $db->query($query);
//error troubleshooting
if (!$books) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
//count the number of rows in the result
$results = $books->fetchAll();
$rowCount = count($book);
//get data from results
foreach($results as $book){
$bookID = $book['bookID'];
$bookTitle = $book['bookTitle'];
$isbn = $book['isbn13'];
$price = $book['price'];
$desc = $book['description'];
$publisher = $book['publisher'];
$courseTitle = $book['courseTitle'];
$courseID = $book['courseID'];
$credits = $book['credit'];
$edition = $book['edition'];
$publishDate = $book['publishDate'];
$length = $book['length'];
$firstName = $book['firstName'];
$lastName = $book['lastName'];
}
if($numrows > 1)
{
foreach ($books as $book)
{
$authorArray[] = $book['firstName'] + ' ' + $book['lastName'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CIS Department Book Catalog</title>
</head>
<body bgcolor=white">
<table border="0">
<tr>
<td>
<img src='images/<?php echo $isbn.'.jpg'; ?>'>
</td>
<td>
<?php
echo "For Course: $courseID $courseTitle ($credits)";
echo "</br>";
echo "Book Title: $bookTitle";
echo "</br>";
echo "Price: $price";
echo "</br>";
echo "Author";
if ($numResults > 1)
{
echo "s:";
for ($i = 0; $i < $numResults; $i++)
{
if ($i!=0)
echo ", $authorArray[i]";
else
echo $authorArrat[i];
}
}
else
echo ": $firstName, $lastName";
echo "</br>";
echo "Publisher: $publisher";
echo "</br>";
echo "Edition: $edition ($publishDate)";
echo "</br>";
echo "Length: $length pages";
echo "</br>";
echo "ISBN-13: $isbn";
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php echo "Description: $desc"; ?>
</td>
</tr>
</table>
</body>
</html>
You should be using isset not is_null to keep it from warning about undefined variables.
$books is never defined It was defined, just incorrectly ... foreach needs it to be an array. You really don't need it anyway, fetch each row into the array with a while loop. (see my example below). You're also redefining $count several times in your query.
And like #Brad said. Use prepared statements and placeholders. Your database will end up hacked with your current code.
EDIT
Answer to your question. query() returns a statement handle. (I've defined it as $sth). fetch() returns a result which you need to pass one of the fetch mode constants (or define it by default earlier with $db->setFetchMode())
To get the books you need to have
$books = array();
$sth = $db->query($query);
while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
$books[] = $row; // appends each row to the array
}
Here's how your code should look to get a count.
// you're not using the $query2 you defined ... just remove it
$sth = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$result = $sth->fetch(PDO::FETCH_ASSOC);
$count = $result['totalRecords'];
Take a look at:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers Looks like a good guide to give you an in-depth understanding of how to use PDO. Pay special attention to error handling and to prepared statements!

Formatting Table with PHP

I can't figure out how to format my table so that there is a header for each section of attributes. I only see one header when there are actually more that I need to see.
For example I'm able to get DROID 4 by MOTOROLA and all of it's attributes go from Full Retail Price to Voice Dialing. After Voice Dialing there should be a second header for another phone. Clearly my logic is messed up and I have been struggling for about 4 hours on it. I also need the two tables to be side by side, not in a long list like this.
This is what I'm trying to achieve:
My code looks like this:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme.css" />
</head>
<body>
<?php
include_once 'config.php';
$conf = new config();
mysql_connect($conf->getdbServ(), $conf->getdbUser(), $conf->getdbPwd()) or die(mysql_error());
mysql_select_db($conf->getDB()) or die(mysql_error());
$selectedPhones = $_POST['phones'];
$totalSelected = count($selectedPhones);
//echo $totalSelected;
$idList = "";
for($i=0;$i < $totalSelected; $i++){
$idList .= $selectedPhones[$i] . ",";
}
$idList = substr($idList,0,-1);
$query = "Select name from ".$conf->getproductTbl()." WHERE id='$idList'";
$res=mysql_query($query);
//echo $idList;
$data = mysql_query("SELECT ".$conf->getproductTbl().".id, ".$conf->getproductAttr().".* from ".$conf->getproductTbl()."
LEFT JOIN ".$conf->getproductAttr()." ON ".$conf->getproductTbl().".id=".$conf->getproductAttr().".prodFK
Where ".$conf->getproductTbl().".id IN(" . $idList . ");");
echo "<table width = 100% border = '1' cellspacing = '2' cellpadding = '0'>";
while ($result = mysql_fetch_assoc($res))
{
echo "<th colspan='2'>".$result["name"]."</th>";
}
while ($row = mysql_fetch_assoc($data)) {
echo "<tr><td>";
echo $row["Name"];
echo "</td><td>";
echo $row["value"];
echo "</td></tr>";
}
echo "</table>";
?>
</body>
</html>
1 - You might want to look into MYSQL JOIN to combine your two queries. (http://www.tizag.com/mysqlTutorial/mysqljoins.php)
2 - Use CSS to style your result set.
You can try something like this.. I hope that will help you.
<table>
<tr>
<?php
for($i=0;$i < $totalSelected; $i++){
//$idList .= $selectedPhones[$i] . ",";
?>
<td><?php
$data = mysql_query("SELECT ".$conf->getproductTbl().".id, ".$conf->getproductAttr().".* from ".$conf->getproductTbl()."
LEFT JOIN ".$conf->getproductAttr()." ON ".$conf->getproductTbl().".id=".$conf->getproductAttr().".prodFK
Where ".$conf->getproductTbl().".id = ".$selectedPhones[$i]);
echo "<table width = 100% border = '1' cellspacing = '2' cellpadding = '0'>";
while ($result = mysql_fetch_assoc($res))
{
echo "<th colspan='2'>".$result["name"]."</th>";
}
while ($row = mysql_fetch_assoc($data)) {
echo "<tr><td>";
echo $row["Name"];
echo "</td><td>";
echo $row["value"];
echo "</td></tr>";
}
echo "</table>";
?>
</td>
<?php }?>
</tr>
</table>

jQuery multi-level sortable list IE Problem

Good afternoon Stackoverflow,
Today I got f'd by IE as usual when using the jQuery library with Ajax.
So whats my problem, well take a look at my live demo: http://194.247.30.66/~keizer/iemakesmesad/
Try ordening the items in FF / Chrome, then test it in IE and we'll all facepalm because of Bill Gates.
Possible explanation: IE grabs the whole ul instead of the ul inside the ul.. any solution?
Code of index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
// When the document is ready set up our sortable with it's inherant function(s)
$(document).ready(function() {
<?php
include_once("../ond/inc/php/connect.php");
$i = 0;
$result = mysql_query("SELECT * FROM paginas WHERE type='0' ORDER BY id ASC");
while($row = mysql_fetch_array($result))
{
$i++;
$result2 = mysql_query("SELECT * FROM paginas WHERE type=".$row{"id"}." ORDER BY id ASC LIMIT 1");
while($row2 = mysql_fetch_array($result2))
{
echo ' $("#submenu_list'.$i.'").sortable({
handle : \'.handle\',
update : function () {
var order = $(\'#submenu_list'.$i.'\').sortable(\'serialize\');
$("#info").load("process-sortable.php?"+order);
}
});
';
}
}
?>
$("#menu_list").sortable({
handle : '.handle',
update : function () {
var order = $('#menu_list').sortable('serialize');
$("#info").load("process-sortable.php?"+order);
}
});
});
</script>
</head>
<body>
<?php
$result = mysql_query("SELECT * FROM paginas_test WHERE type='0' ORDER BY position ASC");
echo '<table cellspacing="2" cellpadding="2">';
echo ' <tr>';
echo ' <th colspan="2" scope="col"><img src="../ond/inc/afb/report.png" />Volgordebepaling</th>';
echo ' </tr>';
echo '</table>';
echo '<ul id="menu_list">';
$i = 0;
while ($row = mysql_fetch_array($result))
{
$i++;
echo '<li style="list-style:none;" id="listItem_'.$row{"id"}.'">';
echo ' <img src="../testajax/arrow.png" alt="move" width="16" height="16" class="handle" /> '.$row{"titel"}.'<br />';
#mysql_query("SELECT * FROM paginas WHERE type='0' ORDER BY id ASC");
$result2 = mysql_query("SELECT * FROM paginas_test WHERE type=".$row{"id"}." ORDER BY position ASC");
echo '<ul id="submenu_list'.$i.'">';
while($row2 = mysql_fetch_array($result2))
{
echo '<li style="list-style:none;margin-left:15px;" id="sublistItem_'.$row2{"id"}.'">';
echo '<img src="../testajax/arrow.png" alt="move" width="16" height="16" class="handle" /> '.$row2{"titel"}.'<br />';
echo '</li>';
}
echo '</ul></li>';
}
echo '</ul>';
echo '<div id="info"></div>';
?>
</body>
</html>
Code of process-sortable.php:
<?php
include("../ond/inc/php/connect.php");
if(isset($_GET['listItem']))
{
foreach ($_GET['listItem'] as $position => $item)
{
$sql = "UPDATE `paginas_test` SET `position` = $position WHERE `id` = $item";
mysql_query($sql);
}
}
if(isset($_GET['sublistItem']))
{
foreach ($_GET['sublistItem'] as $position2 => $item2)
{
$sql = "UPDATE `paginas_test` SET `position` = $position2 WHERE `id` = $item2";
mysql_query($sql);
}
}
print_r ($sql);
?>
check this one: jQuery unexpected sortable behaviour

Categories