I am new to PHP and trying to display data from the database.
However it only displays data from one row but I want to show the data from multiple rows where the condition match. Here is my code I am using:
<?PHP
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: checklogin.php");
}
$con = mysqli_connect("localhost", "root", "", "map_my_way");
$fetch_row = $_SESSION['username'];
$result = mysqli_query($con,"SELECT * FROM members where username='$fetch_row'");
while($row = mysqli_fetch_array($result)) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$email = $row['email'];
$m_no = $row['m_no'];
$v_name = $row['v_name'];
$capacity = $row['capacity'];
$fuel_type = $row['fuel_type'];
}
$result2 = mysqli_query($con,"SELECT s_a_name FROM locations where username='$fetch_row'");
$row2 = mysqli_fetch_array($result2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Profile Page</title>
<link rel="stylesheet" type="text/css" href="profile.css">
</head>
<body id="body">
<div id="mmw"> <span> MAP MY WAY </span></div>
<div id="title_box">
<button id="lvbutton">My Profile</button>
<button id="lvbutton">Maps</button>
<button id="lvbutton">Edit Profile</button>
<button id="lvbutton" style="float:right; margin- right:10px;">Sign-Out</button>
</div>
<div id="box">
<div id="name_box"><span>Welcome <?php echo($_SESSION['username']); ?></span></div>
<div id="box1">
<div> <p id="link">Your Information </p>
<ul style="margin-top:20px; padding-left:0;">
<li><span>First Name : <?php echo $first_name; ?></span></li><br>
<li><span>Last Name : <?php echo $last_name; ?></span></li><br>
<li><span>Email : <?php echo $email; ?></span></li><br>
<li><span>Age : <?php echo $m_no; ?></span></li><br>
<li><span>Current Vehical : <?php echo $v_name; ?></span></li><br>
<li><span>Fuel Type: <?php echo $fuel_type; ?> </span></li><br>
<li><span>Seating Capacity : <?php echo $capacity; ?></span></li><br>
</ul>
</div>
</div>
<div id="box2"> <p id="link">Saved Routes </p>
<ul style="margin-top:20px;">
<span> <?php foreach($row2 as $data)
{echo "route Name : $data <br>" ; };
?>
</span>
</ul>
</div>
</div>
</div>
</body>
</html>
Your query on the members table is only going to return one row, so you don't really need to have $row = mysqli_fetch_array($result) in a loop (that shouldn't break your script, though). Your query on the locations table will potentially return more than one row, so you do need to loop on that one. Something like:
$result2 = mysqli_query($con,"SELECT s_a_name FROM locations where username='$fetch_row'");
$savedRoutes = "";
while($row2 = mysqli_fetch_array($result2))
{
$savedRoutes .= "route Name : " . $row2['s_a_name'] . "<br/>";
}
will put all the data together in a string ($savedRoutes) that can be echoed down in the "Saved Routes" section of your html code.
Alternatively, you can put the loop down in the "Saved Routes" section and just echo out each line as you loop through. Personally I think putting the loop in the top and concatenating the data into a string is a bit cleaner and easier to read.
Related
I have search webpage, but when the search is run, there is a blank first result.
<?php include "headnav.php";
$count = 0;
$sql = "SELECT * FROM lost_property";
if (!empty($_POST)) {
$name = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['name']));
$item = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['item']));
$area = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['area']));
$sql = "
SELECT *
FROM lost_property
JOIN item
ON lost_property.itemID = item.itemID
JOIN area
ON lost_property.areaID = area.areaID
WHERE name LIKE '%$name%'
AND item LIKE '%$item%'
AND area LIKE '%$area%'
ORDER
BY lost_property.name ASC
";
$search_query = mysqli_query($dbconnect, $sql);
$count = mysqli_num_rows($search_query);
}
$result = $dbconnect->query($sql);
?>
<body>
<div class="form">
<h1>Search for lost property here:</h1>
<form action="" method="POST">
Name:
<input type="text" placeholder="Name" name="name">
Item type:
<select name="item" class="dropdown">
<option value="" disabled selected>Item</option>
<?php
$item_sql = "SELECT DISTINCT item FROM `lost_property`
JOIN item ON (lost_property.itemID = item.itemID)
ORDER BY item ASC
";
$item_query = mysqli_query($dbconnect, $item_sql);
$item_rs = mysqli_fetch_assoc($item_query);
do {
?>
<option value="<?php echo $item_rs['item']; ?>"><?php echo $item_rs['item']; ?></option>
<?php
} while ($item_rs = mysqli_fetch_assoc($item_query));
?>
</select>
Area (where it was found):
<select name="area" class="dropdown">
<option value="" disabled selected>Area</option>
<?php
$area_sql = "SELECT DISTINCT area FROM `lost_property`
JOIN area ON (lost_property.areaID = area.areaID)
ORDER BY area ASC
";
$area_query = mysqli_query($dbconnect, $area_sql);
$area_rs = mysqli_fetch_assoc($area_query);
do {
?>
<option value="<?php echo $area_rs['area']; ?>"><?php echo $area_rs['area']; ?></option>
<?php
} while ($area_rs = mysqli_fetch_assoc($area_query));
?>
</select>
<input type="submit" value="Search" name="btn">
</form>
</div>
<div class="gallery">
<h2>Search results:</h2>
<?php
//check for results. If there are none display error
if ($count < 1) {
?>
<div class="error">
<h1>No results were found.</h1>
</div>
<?php
} //end if
else {
do {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
while ($search_rs = mysqli_fetch_assoc($search_query));
} //end else
//if there are any display
?>
</div>
</table>
</body>
</html>
It's hard to see without any CSS, but no matter what is searched, there is always one result, but the h3 and p fields don't have any content. If there wasn't the no results error message it would pop up there too. What is causing this first result?
Use while (){}, if you use do instead it will run once first (credit to Magnus Eriksson).
It ends up like
else {
while ($search_rs = mysqli_fetch_assoc($search_query)) {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
} //end else
//if there are any display
?>
instead of
else {
do {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
while ($search_rs = mysqli_fetch_assoc($search_query));
} //end else
//if there are any display
?>
I have PHP code retrieving data from MySQL DB. What I want is to press a button then a popup must display data for that relevant id or display data on that id row. So for the first btn it works well but on other btn's it displays data from btn 1.
Is there any solution out there?
Thanks
$query = "SELECT * FROM users"
$results = mysqli_query ($conn, $query);
$chck_res = mysqli_num_rows($results);
if ($chck_res > 0) {
while($row = mysqli_fetch_array($results)) {
$id = $row['id'];
$name =$row['name'];
$lastName = $row['lName'];
?>
<div class="container">
<button onClick="popWin()">View data at <?php echo $id; ></button>
</div>
<div id="popup">
echo $id = $row['id'];
echo $name =$row['name'];
echo $lastName = $row['lName'];
</div>
<?php
}
}
CSS:
#popup {
display: none;
}
JS:
function popWin() {
document.getElementById('popup').style.display = "Block";
}
DOM elements must have unique ID, you can't get access to the second element with the same ID via getElementById.
Try to replace your divs with next:
<div>
<div class="container">
<button onClick="popWin(this)">View data at <?php echo $id; ></button>
</div>
<div class="popup">
<?= $id = $row['id']; ?>
<?= $name = $row['name']; ?>
<?= $lastName = $row['lName']; ?>
</div>
</div>
JS:
function popWin(btn) {
btn.parentNode.parentNode.getElementsByClassName("popup")[0].style.display = "Block";
console.log(btn.parentNode.parentNode.getElementsByClassName("popup")[0].innerHTML);
}
function popWin(btn) {
btn.parentNode.parentNode.getElementsByClassName("popup")[0].style.display = "Block";
console.log(btn.parentNode.parentNode.getElementsByClassName("popup")[0].innerHTML);
}
<div>
<div class="container">
<button onClick="popWin(this)">View data at 2</button>
</div>
<div class="popup">
name id 2
</div>
</div>
<div>
<div class="container">
<button onClick="popWin(this)">View data at 1</button>
</div>
<div class="popup">
name id 1
</div>
</div>
Your code has errors. you
did not terminate the select query
did not end php tag on echo id on line 14
<?php
$query = "SELECT * FROM users";
$results = mysqli_query ($conn, $query);
$chck_res = mysqli_num_rows($results);
if ($chck_res > 0) {
while($row = mysqli_fetch_array($results)) {
$id = $row['id'];
$name =$row['name'];
$lastName = $row['lName'];
?>
<div class="container">
<button onClick="popWin()">View data at <?php echo $id; ?></button>
</div>
<div id="popup">
<?php echo $id = $row['id'];
echo $name =$row['name'];
echo $lastName = $row['lName'];?>
</div>
<?php }}
I'm trying to materialize pagination. I want to fetch like
$sql2 = "select * from phptest.memo order by num desc limit $start,$start+$scale";
and i used while paragraph to show memo and ripple (ripple database has parent field that what number of memo and it's order num primary field) but I think it seems like typed wrong code what should i do? It's image that I want make
Expected result:
Error:
<?php
session_start();
// echo "<a href='memo.php?page=$i'> $i </a>";
$scale=5; // page per writing
// start recored number newest writing is up
// $page 값에 다른 시작 레코드 넘버값, 가장 높은 글번호(최신글 부터 밑으로)
$start = ($page - 1) * $scale; //0,5,10 ...
if(!isset($_REQUEST["page"]))
{
$page = 1; // initialize seeing page
}else{
$page = $_REQUEST["page"];
}
require_once '../lib/dbconn.php';
$pdo = db_connect();
if(isset($_SESSION["userid"])){
$userid = $_SESSION["userid"];
}else{
$userid = "";
}
// start recored number newest writing is up
try{
//$sql = "select * from phptest.memo order by num desc";
$sql2 = "select * from phptest.memo order by num desc limit $start,$start+$scale";
$stmh = $pdo->query($sql2);
} catch (PDOException $ex) {`enter code here`
print "오류: ".$ex->getMessage();
}
$total_record = $stmh->rowCount();
$number = $total_record - $start;
// 전체 페이지 수 계산..
if ($total_record % $scale == 0)
$total_page = floor($total_record/$scale);
else
$total_page = floor($total_record/$scale) + 1;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<link href="../css/common.css" rel="stylesheet" type="text/css" media="all">
<link href="../css/memo.css" rel="stylesheet" type="text/css" media="all">
</head>
<body>
<div id="wrap">
<div id="header">
<?php include "../lib/top_login2.php"; ?>
</div> <!-- end of header -->
<div id="menu">
<?php include "../lib/top_menu2.php"; ?>
</div> <!-- end of menu -->
<div id="content">
<div id="col1">
<div id="left_menu">
<?php
include "../lib/left_menu.php";
?>
</div>
</div>
<div id="col2">
<div id="title">
<img src="../img/title_memo.gif">
</div>
<?php
// if(isset($_SESSION["userid"])){
?>
<div id="memo_row1">
<form name="memo_form" method="post" action="insert.php">
<?php if(isset($_SESSION['nick'])){ ?>
<div id="memo_writer"><span >▷ <?=$_SESSION['nick'] ?> </span></div>
<?php }?>
<div id="memo1"><textarea rows="6" cols="95" name="content"></textarea></div>
<div id="memo2"><input type="image" src="../img/memo_button.gif"></div>
</form>
</div> <!-- end of memo_row1 -->
<?php // }
while ($row = $stmh->fetch(PDO::FETCH_ASSOC))
{
// $stmh = $pdo->query($sql2);
//$row[$i] = $row;
// $row = $stmh2->fetch(PDO::FETCH_ASSOC);
$memo_id = $row['id'];
$memo_num = $row['num'];
$memo_date = $row['regist_day'];
$memo_nick = $row['nick'];
$memo_content = $row['content'];
$memo_content = str_replace("\n", "<br>", $row['content']);
$memo_content = str_replace(" ", " ", $memo_content);
?>
<div id="memo_writer_title">
<ul>
<li id="writer_title1"><?= $memo_num ?></li> <!--article number -->
<li id="writer_title2"><?= $memo_nick ?></li>
<li id="writer_title3"><?= $memo_date ?></li>
<li id="writer_title4">
<?php
if($userid=="admin" || $userid==$memo_id)
echo "<a href='delete.php?num=$memo_num'>[삭제]</a>";
?>
</li>
</ul>
</div>
<div id="memo_content"><?= $memo_content ?>
</div>
<div id="ripple">
<div id="ripple1">덧글</div>
<div id="ripple2">
<?php
$sql3 = "select * from phptest.memo_ripple where parent=$memo_num";
$stmh3 = $pdo->query($sql3);
while ($row_ripple = $stmh3->fetch(PDO::FETCH_ASSOC))
{
$ripple_num = $row_ripple["num"];
$ripple_id = $row_ripple["id"];
$ripple_nick = $row_ripple["nick"];
$ripple_content = str_replace("\n", "<br>", $row_ripple["content"]);
$ripple_content = str_replace(" ", " ", $ripple_content);
$ripple_date = $row_ripple["regist_day"];
?>
<div id="ripple_title">
<ul>
<li><?= $ripple_nick ?> <?= $ripple_date ?></li>
<li id="mdi_del">
<?php
if($userid=="admin" || $userid==$ripple_id)
echo "<a href='delete_ripple.php?num=$ripple_num'>삭제</a>";
?>
</li>
</ul>
</div>
<div id="ripple_content"> <?= $ripple_content ?></div>
<?php
}
if(isset($_SESSION["userid"])){
?>
<form name="ripple_form" method="post" action="insert_ripple.php">
<input type="hidden" name="num" value="<?= $memo_num ?>">
<div id="ripple_insert">
<div id="ripple_textarea">
<textarea rows="3" cols="80" name="ripple_content"></textarea>
</div>
<div id="ripple_button"><input type="image" src="../img/memo_ripple_button.png"></div>
</div>
</form>
<?php } ?>
</div> <!-- end of ripple2 -->
<div class="clear"></div>
<div class="linespace_10"></div>
<?php
//$number--;
}
?>
<div id="page_num"> ◀ 이전
<?php
// page link num
// 게시판 목록 하단에 페이지 링크 번호 출력
for ($i=1; $i<=$total_page; $i++)
{
if ($page == $i) // ���� ������ ��ȣ ��ũ ����
{
echo "<b> $i </b>";
}
else
{
echo "<a href='memo.php?page=$i'> $i </a>";
}
}
?>
다음 ▶</div>
</div> <!-- end of ripple -->
</div> <!-- end of col2 -->
</div> <!-- end of content -->
</div> <!-- end of wrap -->
</body>
</html>
The SQL doesn't like doing maths in the limit clause. Do it first in PHP:
$sql2 = "select * from phptest.memo order by num desc limit $start," . ($start+$scale);
I am trying to repeat a div the same div multiple times with as many rows as i have in the database table. a non working example i made of what i want is below.
<?php for ($i=0; $i < 3; $i++) {
?><!-- switch the three with the number of rows in the table-->
I would want to loop the container and switch the database query with the value of i.
<div id = "bodyContainer">
<form class="review">
<div class="reviewContainer">
<div class = "images">
<?php
$link = mysqli_connect("localhost", "root", "root","DJP");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query = "SELECT * FROM reviews WHERE id = '<?php echo $i ?><!--switch the value of i here-->'";
$result=mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo '<img height = 90% width = 100% src="data:image/jpeg;base64,'.$row[3].' " />';
?>
</div>
<!--<div class="title">
<?php
//echo $row[1];
?>
</div>-->
<div class = "comment">
<?php
echo $row[2];
?>
</div>
<div class = "rating" style = "float: right;">
<?php
echo $row[4];
?>
<br/>
<br/>
stars
</div>
</div><!--end review-->
</form>
</div><!--end body container-->
<?php;}?><!-- end the for loop so all the divs can be re-done with a new entry for the query. I would move the $link out of loop also.-->
Just fetch all the rows once and then go through them as you print the data:
$link = mysqli_connect("localhost", "root", "root","DJP");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query = "SELECT * FROM reviews";
$result=mysqli_query($link, $query);
while($row = mysqli_fetch_array($result)){ ?>
<div id = "bodyContainer">
<form class="review">
<div class="reviewContainer">
<div class = "images">
<?php
echo '<img height = 90% width = 100% src="data:image/jpeg;base64,'.$row[3].' " />';
?>
</div>
<!--<div class="title">
<?php
//echo $row[1];
?>
</div>-->
<div class = "comment">
<?php
echo $row[2];
?>
</div>
<div class = "rating" style = "float: right;">
<?php
echo $row[4];
?>
<br/>
<br/>
stars
</div>
</div><!--end review-->
</form>
</div><!--end body container-->
<?php } ?>
Lets say I have a persons table :
forename surname age gender
--------------------------------------------
adam example 90 male
john example 90 male
If I wanted to display this information in separate divs, how could this be done? Say for example the following HTML.
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<!-- adams data here -->
</div>
<div class = "jumbotron">
<!-- johns data here -->
</div>
</div>
</div>
I'm aware on how to query the DB to get the information into PHP variables, I'm just not sure how to dynamically display the data in separate divs.
Below is how I am getting the data
<?php
if($result = $db->query("SELECT forename,surname FROM users ")){
if($count = $result->num_rows){
while($row = $result->fetch_object()){
echo $row->forename, '<br><br>';
echo $row->surname, '<br><br>';
}
$result->free();
}
}
?>
Just wrap the div inside a loop so you'll print a div for each result row
<?php foreach($result as $r): ?>
<div class = "jumbotron">
<?php echo $r['name'] // Print fields you need ?>
</div>
<?php endforeach; ?>
EDIT: Now I can see your query. Try this:
<?php
if($result = $db->query("SELECT forename,surname FROM users ")){
if($count = $result->num_rows){
while($row = $result->fetch_object()){
?>
<div class = "jumbotron">
<?php echo $row->forename; ?><br><br>
<?php echo $row->surname; ?><br><br>
</div>
<?php
}
$result->free();
}
}
?>
Well Joe, This is a fairly simple problem that has probably been answered before.
I'll use the mysqli class of php
first create a mysqli connection object in a file for best practice then include it in your main script.
<?php
$connection = new mysqli($host_address, $username, $password, $database);
?>
include this in your main script
<?php require "path\to\connection\script"; ?>
<?php
$sql_adam = "SELECT * FROM persons WHERE forename = 'adam'";
$sql_john = "SELECT * FROM persons WHERE forename = 'john'";
$qry1 = $connection->query($sql_adam);
$qry2 = $connection->query($sql_john);
?>
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<?php if ($qry1->num_rows >= 1){
while($adam = $qry1->fetch_assoc()){
foreach ($adam as $column => $data) {
echo "<p>$column : $data </p>";
}
}
}
</div>
<div class = "jumbotron">
<?php if ($qry2->num_rows >= 1){
while($john = $qry2->fetch_assoc()){
foreach ($john as $column => $data) {
echo "<p>$column : $data </p>";
}
}
}
</div>
</div>
</div>
Your Result should be something like
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<p>forename : adam</p>
<p>surname : example</p>
<p>age : 90</p>
<p>gender : male</p>
</div>
<div class = "jumbotron">
<p>forename : john</p>
<p>surname : example</p>
<p>age : 90</p>
<p>gender : male</p>
</div>
</div>
</div>