Echoing variables from database - php

I have some PHP code that sets variables from a database. I'll explain, please let me know if it does not make sense.
So, I have a query to select * from the table if class = '$class'. That all works I got it working.
I then set the variables like this $id = $row["id"]; and that all works, in my HTML code I have <p><?php echo $id?></p> and if their class = $class it will display it, however, if it does not meet those requirements the variables are not set, so I get the error Notice: Undefined variable: id in C:\wamp64\www\studentplanner\account\homework.php on line 73.
What I want to do is only output the results in HTML if the requirement was met.
No idea if that makes sense or not!
$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$teacher_set = $row["teacher_set"];
$class = $row["class"];
$name = $row["name"];
$description = $row["description"];
}
}
<p><?php echo $id?></p>
<p><?php echo $teacher_set?></p>
<p><?php echo $class?></p>
<p><?php echo $name?></p>
<p><?php echo $description?></p>

set flag variable before while loop then use that variable to decide whether to print data in html or not
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
// output data of each row
$data_exist = true;
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$teacher_set = $row["teacher_set"];
$class = $row["class"];
$name = $row["name"];
$description = $row["description"];
}
}
if($data_exist)
{
?>
<p><?php echo $id?></p>
<p><?php echo $teacher_set?></p>
<p><?php echo $class?></p>
<p><?php echo $name?></p>
<p><?php echo $description?></p>
<?php
}
?>

$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
?>
<p><?php echo $row["id"];?></p>
<p><?php echo $row["teacher_set"];?></p>
<p><?php echo $row["class"];?></p>
<p><?php echo $row["name"];?></p>
<p><?php echo $row["description"];?></p>
<?php } } ?>

Related

Nested while loop in PHP in getting data from database

<?php
$sqlquerypmenu = "select *
from subsubmenu
where submenu_id=1
and position='left'
and status=1";
if($querypmenu = sqlsrv_query($conn,$sqlquerypmenu)){
if(sqlsrv_has_rows($querypmenu) === true){
while($rowdata = sqlsrv_fetch_array($querypmenu, SQLSRV_FETCH_ASSOC)){
?>
<h4 class="title-small folder_name"> <?php echo $rowdata ['website_title']; ?> </h4>
<?php
$id = $rowdata['id'];
$filequerymenu = "select *
from upload_files
where main_menu='value_name'
and sub_menu='value_key'
and subsub_menu= $id ";
if($filemenu = sqlsrv_query($conn,$filequerymenu)){
if(sqlsrv_has_rows($filemenu) === true){
while($filedata = sqlsrv_fetch_array($filemenu, SQLSRV_FETCH_ASSOC)){ ?>
<a class="smalltext font_val" href="<?php echo DOCUMENT_URL.$filedata ['file_name']; ?> " target="_blank" ><?php echo $filedata['document_name']; ?></a>
<?php
}
}
}
}
}
}
?>
In the nested while loop the second while loop only shows the first row of data and does not show the rest of the data.
How can I fix this?
Consider querying the database once with one JOIN query. Possibly opening up another fetch within a while loop causes instances issues:
<?php
...
$sql = "select s.website_title, u.file_name, u.document_name
from upload_files u
inner join subsubmenu s ON u.subsub_menu = s.id
where u.main_menu = 'value_name'
and u.sub_menu = 'value_key'
and s.submenu_id = 1
and s.[position] = 'left'
and s.[status] = 1
order by s.id, s.website_title;"
$title = "";
if($result = sqlsrv_query($conn, $sql)){
if(sqlsrv_has_rows($result) === true){
while($rowdata = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
if($title != $rowdata['website_title']) {
$title = $rowdata['website_title']
?>
<h4 class="title-small folder_name"> <?php echo $rowdata ['website_title']; ?> </h4>
<?php
}
?>
<a class="smalltext font_val" href="<?php echo DOCUMENT_URL.$filedata ['file_name']; ?> " target="_blank" ><?php echo $filedata['document_name']; ?></a>
<?php
}
}
}
?>

Output Multiple Database Results

I currently have this code set up:
$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
// output data of each row
$data_exist = true;
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$teacher_set = $row["teacher_set"];
$class = $row["class"];
$name = $row["name"];
$description = $row["description"];
}
}
And then:
<?php if ($data_exist){?>
<p><?php echo $id ?></p>
<p><?php echo $teacher_set?></p>
<p><?php echo $name?></p>
<p><?php echo $description?></p>
<?php
}?>
However, the issue is if there is multiple results in the database it only outputs one of them, how can I prevent this from happening and output two?
I want to make it so every row has their own section, like this: http://prntscr.com/hcgtqn so if there is only one result, one one will show etc.
You have to echo data in a loop. Right now you are reassigning values in while($row = mysqli_fetch_assoc($result)) iterations and printing just the last one.
You need to print each time you read a row from the database.
about the styles, you can represent it in many ways. In the code below I present it in a table.
<table>
<thead>
<tr>
<th>id</th>
<th>teacher set</th>
<th>name</th>
<th>description</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$teacher_set = $row["teacher_set"];
$class = $row["class"];
$name = $row["name"];
$description = $row["description"];
// you need to print the output now otherwise you will miss the row!
// now printing
echo "
<tr>
<td>".$id."</td>
<td>".$teacher_set."</td>
<td>".$name."</td>
<td>".$description."</td>
</tr>";
}
}
else // no records in the database
{
echo "not found!";
}
?>
</tbody>
</table>
</body>
</html>

select all not working in mysql

pls i tried to display all content in a database, it keeps dispaying the last inserted, kindy help out.
<?php
include 'database/condb.php';
$query = mysql_query("SELECT * FROM posts ");
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags= $row["hashtags"];
?>
<?php
}
?>
<?php
echo $id;
echo $body;
?>
Either print the values in while loop or store them in an array to print them outside the loop.
while($row = mysql_fetch_assoc($query)){
echo $row["id"];
echo $row["body"];
}
condb.php
<?php
$con = mysqli_connect("localhost","username","password","databasename");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
index.php
<?php
include 'database/condb.php';
$query = "SELECT * FROM posts";
$res = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($res)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags= $row["hashtags"];
echo $id;
echo $body;
}
?>
For storing data, sometimes using array becomes helpful. I usually recommend it:
<?php
include 'database/condb.php';
$query = mysql_query("SELECT * FROM posts");
$array = [];
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags = $row["hashtags"];
$array[$id] = ['username'=>$username, 'body'=>$body, 'date_added'=>$date_added, 'hasttags'=>$hasttags];
}
?>
<?php
foreach($array as $id => $value){
echo $id; //Prints id
echo "<br>";
echo $value['username'].", ".$value['body'].", ".$value['date_added'].", ".$value['hasttags'];
}
?>
Or you can simply do this:
<?php
include 'database/condb.php';
$query = mysql_query("SELECT * FROM posts");
$array = [];
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags = $row["hashtags"];
?>
<?php
echo $id.", ".$username.", ".$body.", ".$date_added.", ".$hasttags;
}
?>
<?php
include 'database/condb.php';
$query = mysql_query("SELECT * FROM posts ");
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags= $row["hashtags"];
echo $id;
echo "<br>";
echo $body;
?>
<?php
}
?>
As an answer to the question "pls i tried to display all content in a database, it keeps dispaying the last inserted, kindy help out."
Put echo $id, echo $body be inside the loop.

Generate title from database and show related post

I have a DB name askadoc , where people can ask about their problem. I want to show all question(or you can say the titles) together in a page. And then when user click on a question, the question will show in a different page with it's comments/details. To do this i have tried the below code and its working perfectly. but how can i do it without using button ?
<?php
$comment = "SELECT * FROM `askadoc` ";
$result = mysqli_query($conn, $comment);
$question = "";
$id="";
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$question = $row["question"];
?>
<form action="post.php" method="post">
<?php
echo $id;
echo "<input type='hidden' name = 'id' value = ".$id.">";
echo "<button>".$question."</button>";
echo "<br>";
?>
</form>
<?php
}
}
?>
I think you don't need form this. You can user anchor like this.
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$question = $row["question"];
?>
<?php echo $question ?>
<?php
}
}
Now when you click this anchor, you get question id inside post.php, so easily you can display a particular question comments.
You can use anchor tag then pass the question id to post.php
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$question = $row["question"];
?>
<?php
echo "<a href='post.php?question_id=".$id."' target='_blank'>".$question."</a>";
echo "<br>";
?>
<?php
}
}
Then to get the value of question_id use $_GET['question_id'];
$questionId = $_GET['question_id']
and its better to check if question_id does exist.
$questionID = isset($_GET['question_id'])? $_GET['question_id'] : '';
if(!empty($questionID)){
//Use $questionID here to query some data from database
}

PHP/MySQL double loop

I am working on a directory where some of the listings have a images associated with them and others do not. I am wondering how I can write a loop within a loop to get my results.
Example, User selects state they want results from, query goes to DB requesting all listings in that state.
<?php
if (isset($_POST['searchButton'])) {
$state = $_POST['state'];
$query = "SELECT * FROM directory LEFT JOIN directory_images ON directory.id = directory_images.user_id WHERE directory.state = '$state' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo "<p>Sorry, there are no listings in '$state', check back soon!</p>\n";
}
else
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$id = $row['id'];
$name = $row['name'];
$address = $row['address'];
$city = $row['city'];
$state = $row['state'];
$zip = $row['zip'];
$has_support_pics = $row['file_name'];
?>
<h4><?php echo $name ?></h4>
<p><?php echo $address ?><br/>
<?php echo $city . ' ' . $state . ', ' . $zip; ?><br/>
</p>
<?php
// check to see if ID has extra images
if (isset($has_support_pics)) {
$query2 = "SELECT file_name FROM directory_images WHERE user_id = '$id'";
$result2 = mysql_query($query2) or die(mysql_error());
echo $query2.'<br/>';
?>
<ul class="support_images">
<?php
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
$support_image = $row['file_name'];
echo $support_image.'<br/>';
}
?>
</ul>
</div>
<br/>
</div>
<?php
}
echo "<hr/>";
}
}
?>
Do NOT run queries in loops - use a join.
Here is a tutorial: http://thewebmason.com/tutorial-parent-child-lists/

Categories