how to format the display of results after a sql query - php

i have been trying to format my results which is being sorted by the first letter of the surname but having problems
i need it to echo in the following format
<section>
<div id="slider">
<div class="slider-content">
<ul>
<li id="LETTER"><a name="LETTER" class="title">LETTER</a><ul>
<li>SURNAME</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</section>
i am have tried to split it so (see code bellow) but it not rendering correctly
<html>
<head>
<title>MySQLi Read Records</title>
</head>
<body><section>
<div id="slider">
<div class="slider-content">
<ul>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = " SELECT name,
surname,
mobile,
UPPER (LEFT(surname, 1)) AS letter
FROM contacts
ORDER BY surname";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database record
//creating our table heading
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<li id="', $row['letter'], '"><a name="', $row['letter'],'" class="title">', $row['letter'],'</a><ul>';
$lastLetter = $row['letter'];
echo "bottom";
}
echo "<li><a href='#'>{$surname} - {$name}</a></li>";
}
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?> </ul>
</li>
</ul>
</div>
</div>
</section>
</body>
</html>
i need to find where and how to echo these sections so it would be like this
:- UPDATE -:
with the reply i got itested it and it goes something like this
<body>
<section>
<div id="slider">
<div class="slider-content">
<ul>
<li id="E"><a name="E" class="title">E</a>
<ul>
bottom
<li><a href='#'>egg - smash</a></li>
<li id="S"><a name="S" class="title">S</a>
<ul>
bottom
<li><a href='#'>surname</a></li>
<li><a href='#'>surname</a></li>
<li><a href='#'>surname</a></li>
<li id="Z">
<a name="Z" class="title">Z</a>
<ul>
bottom
<li><a href='#'>zoo</a></li>
<!-- </ul> BAD UL ?-->
</li>
</ul>
</div>
</div>
</section>
</body>
</html>
when it should be
<section>
<div id="slider">
<div class="slider-content">
<ul>
<li id="s"><a name="s" class="title">s</a><ul>
<li>surname</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</section>

ALWAYS indent your code, AlWAYS run tests on variables, do not take steps skipping simple testing before like looping
<body>
<section>
<div id="slider">
<div class="slider-content">
<ul>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = " SELECT name,
surname,
mobile,
UPPER (LEFT(surname, 1)) AS letter
FROM contacts
ORDER BY letter ASC";
//execute the query
$result = $mysqli->query( $query );
//TEST 1st print_r($result); if not working there is an error on your sql
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database records
//creating our table heading
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<li id="', $row['letter'], '"><a name="', $row['letter'],'" class="title">', $row['letter'],'</a><ul>';
$lastLetter = $row['letter'];
echo "bottom";
}
echo "<li><a href='#'>{$surname} - {$name}</a></li>";
}
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
<!-- </ul> BAD UL ?-->
</li>
</ul>
</div>
</div>
</section>
</body>

Related

Echo html code from php to html

I'm working on my own project for a music site and i'm blocked on a situation. Right now i'm working on the playlist and i want to echo from php(i'm working with odbc connection) on html, but it's not putting all the data, only the first row, and i want all the data from database to be echo in the playlist.
I tried to make an echo statement in php which to send row by row with html code.
This is my PHP:
<?php
error_reporting(6);
include("connect.php");
include("checklogin.php");
$username = $_SESSION['username'];
//echo $username;
$sql="select name from [YourTube].[dbo].[yt_url]
where username='$user_check'";
$rs=odbc_exec($conn,$sql);
//echo $sql;
while(odbc_fetch_row($rs)){
$name = odbc_result($rs, 1);
//print("$name\n");
}
?>
And i have tried to put something like this in php>>
<?php if($rs) { ?>
<li class="list_item selected">
<div class="title" action="../php/songs.php"><?php echo
odbc_result($rs, 1)?></div>
</li>
<?php } ?>
And the result is just the first row from database, but if i print $name it's showing all the rows.
The html code for playlist:
<div class="list_wrapper">
<ul class="list">
<li class="list_item selected">
<div class="info">
<div class="title" action="../php/songs.php"><?php echo
odbc_result($rs, 1)?></div>
</div>
</li>
</ul>
</div>
And like i said, this code on html it's showing only one row in playlist, not all of them. And i'm thinking to do something like echo from php in html code for every row something like this:
<li class="list_item selected">
<div class="info">
<div class="title" action="../php/songs.php"><?php echo
odbc_result($rs, 1)?></div>
</div>
</li>
Can someone help me with this? I'm working on this thing for some days and i can't figure out how to do it.
Thank you in advance!
Bogdan
You have to apply while() inside if() like below:-
<?php if($rs) {
while(odbc_fetch_row($rs)){
?>
<li class="list_item selected">
<div class="title" action="../php/songs.php"><?php echo odbc_result($rs, 1)?></div>
</li>
<?php }
} ?>

MySQLi query in variable/function (that can be later used to echo content)

So I'm stuck with a problem. I'm creating some kind of "templated" page (no, I can't use Twig or anything like that) in PHP, that will later be incremented with actual content.
My main problem here is to echo links in navbar. I'm using MaterializeCSS, so in order to make the navbar responsive is to write the links twice inside different ULs. I can easily echo it one time, like this:
<?php
$sql = "SELECT id, pagename, filename FROM NavbarLinks";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$navstructure =
<<<HTML
<header>
<nav class="$primarycolor">
<div class="container">
<div class="nav-wrapper">
$sitename
<ul class="right hide-on-med-and-down">
HTML;
echo $navstructure;
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<li>' . $row['pagename'] . '</li>
' ;
}
}
echo "
</ul>
</div>
</div>
</nav>
</header>";
?>
This works with no errors. The problem is, I need that (according to MaterializeCSS specifications/documentation):
<nav>
<div class="nav-wrapper">
Logo
<i class="material-icons">menu</i>
<ul class="right hide-on-med-and-down">
// links
</ul>
<ul class="side-nav" id="mobile-demo">
// links again
</ul>
</div>
</nav>
So what I wanted to do was simple: Make a navbar.php and have the structure on a HEREDOC variable, and in the variable $navbarlinks I would print all the links I got from the first code I showed you. The problem for me is that putting the links in a variable instead of showing all the results will only print one, and I couldn't find a way to change this.
What should I do to have a $navbarlinks or navbarlinks() that prints all the mySQL results and work everywhere?
You want to just put it in an array for later use. You should also try to separate your PHP from your HTML, this might be a good start but still needs things like HTML escaping. Note in particular the use of alternative syntax and short echo tags.
<?php
$links = [];
$sql = "SELECT id, pagename, filename FROM NavbarLinks";
$result = $conn->query($sql);
if ($result) {
while($row = $result->fetch_assoc()) {
$links[] = array_map('htmlspecialchars', $row);
}
}
// PHP is finished now, here's the HTML
?>
<?php if (count($links)):?>
<header>
<nav class="<?=$primarycolor?>">
<div class="container">
<div class="nav-wrapper">
<?=$sitename?>
<ul class="right hide-on-med-and-down">
<?php foreach ($links as $link):?>
<li><?=$link['pagename']?></li>
<?php endforeach?>
</ul>
<ul class="side-nav" id="mobile-demo">
<?php foreach ($links as $link):?>
<li><?=$link['pagename']?></li>
<?php endforeach?>
</ul>
</div>
</div>
</nav>
</header>
<?php endif?>
no longer practicing php but as far as i can remember html/css elements don't have to be pass to a variable.. you can just end php before the css elements and open php again from your loop
<?php
$sql = "SELECT id, pagename, filename FROM NavbarLinks";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
?>
<HTML
<header>
<nav class="$primarycolor">
<div class="container">
<div class="nav-wrapper">
<?php=$sitename?>
<ul class="right hide-on-med-and-down">
<?php
while($row = $result->fetch_assoc()) {
echo '<li>' . $row['pagename'] . '</li>
' ;
}
?>
</ul>
</div>
</div>
</nav>
</header>";
<?php
}
?>
<!-- end -->

Data from MySQL not showing while building dynamic menu in PHP

I'm building a dynamic menu using PHP and MySQL but results are not showing:
The website structure is built below:
<div id="container">
<ul class="nav">
<li>home</li>
<li>
destinations &triangledown;
<div id="subMenu">
<div class="nav-column">
Europe
</div>
<div class="nav-column" >
Africa
</div>
<div class="nav-column" >
Asia
</div>
<div class="nav-column">
Oceania
</div>
<div class="nav-column">
North America
</div>
<div class="nav-column">
South America
</div>
</div>
</li>
<li>about</li>
<li>contact</li>
</ul>
</div>
Then i have a continents DB and then another DB with countries, which connect to their respective continent.
So, in the subMenu div, i want to call each continent and then in each div cnt_submenu_, loop through a unordered list of 9 results and then show another with the same number of results and so on until all the countries with the same id reaches the end.
Here is what i'm trying to do with the PHP code below:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<div id="container">
<ul class="nav">
<li>home</li>
<li>destinations
<div id="subMenu">
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "site_comboios";
//Open DB connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
//check connection
if($mysqli->connect_errno) {
echo 'Error connecting to database';
exit();
}
//show sub-menu
$query = "SELECT * FROM continentes ORDER BY id";
$result = mysqli_query($mysqli, $query);
$div = 0;
while ($row = mysqli_fetch_assoc($result)) {
$país = $row['continente'];
echo "<div class='nav-column'><a href='#' class='continente' data-id='cnt_submenu'>" .($país). "</a></div> "; </div> ";
}
?>
</div>
</li>
<li>about</li>
<li>contact</li>
</ul>
</div>
<div id="cnt_submenu_" class="submenu_continente active">
<?php
//retrieve european countries from DB and open <ul> with 9 results
$conn = mysqli_connect("localhost:3306","root","","site_comboios");
$sql_countries = "SELECT * FROM countries ORDER BY id WHERE id_continentes = 1" ;
$res_countries = mysqli_query($conn, $sql_countries);
if($res_countries > 0) {
while ($row_countries = mysqli_fetch_assoc($res_countries)) {
$país = $row_countries['id_continente'];
echo "<ul><li><a href='#'>". $país ."";
}
} else if ($res_countries == 9) {
echo '</li></ul>';
}
?>
<span class="close">x</span>
</div>
Thanks for pointing me out in the right direction.
Edited I'm trying to show through 9 results onto a , close it and open another with 9 results until the end of the countries with id = 1.
Added the jquery to open each continent div below but i'm not doing it right:
//Open and close each div with country list
$('.continente').hover(function(){
menuHide('submenu_continente' . $(this).data("id") );
$('#cnt_submenu_' . $(this).data("id") ).show();
},function(){
$('#cnt_submenu_' . $(this).data("id")).mouseleave( function() {
$(this).hide();
});
});

PHP: split a mySQLi array in two divs?

I'm currently working on a page that calls a mySQL database to populate a list of members. However, I need that list to be split into two equal parts, so that half can float to the left and half to the right. However, I have beat this horse to death and still cannot figure out how to split the array.
Here's what I have currently:
<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
if ( $rowcount > 0 ) { ?>
<div class="members-left">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
</div>
However, I want the output to look something like this (let's say my table has 10 members):
<div class="holder">
<!--output first half of members from table: -->
<div class="members-left">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>
<!--output second half of members from table: -->
<div class="members-right">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>
</div>
I've tried setting counters and using things like if($i <= $rowcount/2), but to no avail. Any help would be greatly appreciated—I'm very new to mySQL and have limited knowledge of PHP, so this one has me stumped.
add a control variable like "$i". add +1 to $i every loop. and check if $i reached half of number of rows. if reached close ul and div and open new div and ul and set $i to 0
<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
$i=0;
if ( $rowcount > 0 ) { ?>
<div class="members-right">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php
$i++;
if($i>=($rowcount/2)){
echo '</ul></div>
<div class="members-right">
<ul class="members">';
$i=0;
}
} ?>
</ul>
</div>
<?php } ?>
</div>
You could use a for loop for the first half and just finish the second half with a while loop that goes until there are no more results.
First half:
for($i = 0; $i <= $rowcount/2 && $row = $members->fetch_assoc(); $i++)
Second half
while ($row = $members->fetch_assoc())
Example with HTML
<div class="members-left">
<ul class="members">
<?php for($i = 0; $i <= $rowcount/2 && $row = $members->fetch_assoc(); $i++) { ?>
<li class="member">
// do something with $row
</li>
<?php } ?>
</ul>
</div>
<div class="members-right">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
// do something with $row
</li>
<?php } ?>
</ul>
</div>
I would recommend you to make 2 arrays of your members and then print them out. The advantage is you will have more control of the members and your code will be more readable for later use;
<?php
$i =0;
while ($row = $members->fetch_assoc()) {
if($i % 2 == 0)
{
$right_members[] = $row;
}
else
{
$left_members[] = $row;
$i++;
}
echo '
<div class="members-right">
<ul class="members">';
foreach($right members as $r_member){
echo '<li class="member">...</li>';
}
echo '
</ul>
</div>';
//SAME WITH LEFT MEMBERS
?>
Having a counter was an idea, I will not debate on having model logic in view ;)
well, a solution would be :
<div class="holder">
<div class="members-column">
<ul class="members">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
$i = 0;
while ($row = $members->fetch_assoc()) {
?>
<li class="member">
//SOME CONTENT HERE
</li>
<?
// Check if current row is the 'middle count', creating a new column
if ($i === ceil($rowcount / 2)) : ?>
</ul>
</div>
<div class="members-column">
<ul class="members">
<?php endif; ?>
<?php
$i++;
}
?>
</ul>
</div>
</div>

Different submenus if SQL result is empty

I have a menu with different submenus, where I want to show a different specific sub-submenu if the SQL result is empty or not.
If the username (the session username) exist in that database, it will output the firstname and lastname, since $result is not empty. However, if I login to an account that does not have the username in that database, I does not output the <li class='last'><span>SubSub1: EMPTY RESULT</span></li>.
It just outputs this:
<li class='active has-sub'><span>Sub1</span>
<ul>
</li>
</ul>
When it should have been:
<li class='active has-sub'><span>Sub1</span>
<ul>
<li class='last'><span>SubSub1: EMPTY RESULT</span></li>
</ul>
Why does it come out empty? What am I doing wrong?
<form action="user.php" method="GET">
<div id="cssmenu">
<ul>
<li class='active has-sub'><a href='#'><span><?php echo htmlentities($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?></span></a>
<ul>
<tr>
<li class='last'><span>Menu1</span></li>
<li class='last'><span>Menu2</span></li>
<li class='active has-sub'><span>Menu3</span>
<ul>
<li class='active has-sub'><span>Sub1</span>
<ul>
<?php
require('connections/db_connection.php');
$username = $_SESSION['username'];
$sql = "SELECT name, lastname FROM servers";
$sql .= " WHERE username = '$username'";
$result = $connection->query($sql);
while($row = $result->fetch_assoc()){
$name = $row['name'];
$lastname = $row['lastname'];
if (empty($result)){
?>
<li class='last'><span>SubSub1: EMPTY RESULT</span></li>
<?php
}else{
?>
<li class='last'><a href=""><span>SubSub1: <?php echo $name; ?><br>
Last name: <?php echo $lastname; ?></span></a></li>
<li class='last'><span>SubSub2</span></li>
<?php
}
}
$connection->close();
?>
</li>
</ul>
<li class='last'><span>Sub2</span></li>
<li class='last'><span>Sub3</span></li>
</li>
</ul>
<li class='last'><span>Logout</span></li>
</tr>
</ul>
</li>
</ul>
</div>
</form>
If your $result is empty - you will never enter
while($row = $result->fetch_assoc())
as there's nothing to fetch.
So I suppose you should check number of returned rows. Number will be 1 if a user is found in your database and 0 - otherwise.
So code can be like this (I suppose you use mylsqi):
$result = $connection->query($sql);
if (0 < $result->num_rows) {
$row = $result->fetch_assoc(); // you can fetch only one result if you're sure that there's only one user;
$name = $row['name'];
$lastname = $row['lastname'];?>
<li class='last'><a href="">
<span>SubSub1: <?php echo $name; ?><br>
Last name: <?php echo $lastname; ?>
</span>
</a></li>
<li class='last'><span>SubSub2</span></li>
<?php
} else {
// no user found:?>
<li class='last'><span>SubSub1: EMPTY RESULT</span></li>
<?php
}
And be the way:
</li>
</ul>
Remove this </li> as you already closing li in your ifs.

Categories