Nested while loop in PHP in getting data from database - php

<?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
}
}
}
?>

Related

Echoing variables from database

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 } } ?>

PHP include(); not including file

I am trying to include a separate snippet of code to fetch data from MySQL tables. My page code:
<?php session_start(); ?>
<html>
<?php include('head.php'); ?>
<body>
<?php include('navigation.php'); ?>
<div id="container">
<?php
$section = "Movies";
print "THIS IS A TEST";
//$_SESSION['sectiontemp'] = $section;
include('section-grabinfo.php');
include('footer.php');
?>
</div>
</body>
</html>
My section-grabinfo.php page:
<?php
print "THIS IS A TEST";
$sql = mysqli_query($conn, "SELECT * FROM article JOIN person ON article.author=person.id WHERE section='".$section."' AND status=1 ORDER BY aid DESC LIMIT 1;");
if ($sql == 'false') {
print "SQL doesn't work";
}
elseif ($sql == 'true') {
print "Works all fine";
}
else {
print "Wrong code.";
}
while ($row = mysqli_fetch_assoc($sql)) {
$title = $row['title'];
$preview = $row['preview'];
$author = $row['name'];
$person_id = $row['author'];
$id = $row['id'];
$username = $row['username'];
include('featured-article.php');
}
//LEAVE SPACE FOR ADS
?>
<div id="secondaryArticleSection">
<?php
$sql2 = mysqli_query($conn, "SELECT * FROM article JOIN person ON article.author=person.id WHERE aid<(SELECT max(aid) FROM article WHERE section='."$section."' AND status=1) AND section='".$section."' AND status=1 ORDER BY aid DESC;");
while ($row = mysqli_fetch_assoc($sql2)) {
$title = $row['title'];
$preview = $row['preview'];
$author = $row['name'];
$person_id = $row['author'];
$id = $row['id'];
$username = $row['username'];
include('secondary-article.php');
}
?>
</div>
Basically my problem is that section-grabinfo.php and footer.php are not being included on the main page. Please keep in mind that this worked completely when I had this on my laptop computer (not the server I'm currently working with). Thank you.
If it is really an including trouble, you could try to include this way
<?php include(__DIR__.'/head.php'); ?>

Print every review stored in the database

I am in the process of building a institute review system and i just completed inserting reviews to the database. However i am in a fix as to how to display to the user all the reviews related to the particular institute.
Below is my code to retrieve review information along with the name of the person who has left the review:
$get_review_query = "SELECT * FROM reviews WHERE institute_id = {$id}";
$result = mysqli_query($connection, $get_review_query);
if(!$result) {
die("Database query failed.");
}
$count = mysqli_num_rows($result);
if($count == 0) {
$output = "There're no reviews for this institute.";
} else {
while($row = mysqli_fetch_assoc($result)) {
$review_contents = $row['content'];
$institute_id = $row['institute_id'];
$student_id = $row['student_id'];
$date = $row['created_on'];
$query_student_name = "SELECT f_name, l_name FROM students
WHERE student_id = {$student_id}";
$result1 = mysqli_query($connection, $query_student_name);
if(!$result1) {
die("Database query failed.");
} else {
$row1 = mysqli_fetch_assoc($result1);
$student_f_name = $row1['f_name'];
$student_l_name = $row1['l_name'];
}
}
}
Now i want to display the reviews somewhere down the page:
<!-- display reviews -->
<fieldset>
<legend>Reviews for <?php echo $name; ?></legend>
<br>
<?php
foreach($row as $value) {
?>
<legend><?php echo $student_f_name . " ". $student_l_name; ?> said:</legend>
<div id = "items" class="">
<?php echo $review_contents; ?>
</div>
<br>
<div>
<?php echo $date; ?>
</div>
<?php } ?>
</fieldset>
The above foreach loop doesn't work. It probably creates an infinite loop. I have tried using a for loop with $count as the maximum counter but that doesn't work either. Please suggest a for loop that prints all the reviews from the database.
try this
$get_review_query = "SELECT * FROM reviews WHERE institute_id = {$id}";
$result = mysqli_query($connection, $get_review_query);
if(!$result) {
die("Database query failed.");
}
$reviews = array();
$count = mysqli_num_rows($result);
if($count == 0) {
$output = "There're no reviews for this institute.";
} else {
while($row = mysqli_fetch_assoc($result)) {
$query_student_name = "SELECT f_name, l_name FROM students
WHERE student_id = {$student_id}";
$result1 = mysqli_query($connection, $query_student_name);
if(!$result1) {
die("Database query failed.");
} else {
$row1 = mysqli_fetch_assoc($result1);
$row['f_name'] = $row1['f_name'];
$row['l_name'] = $row1['l_name'];
}
$reviews[] = $row;
}
}
if( $reviews ){
?>
<fieldset>
<legend>Reviews for <?php echo $name; ?></legend>
<br>
<?php
foreach($reviews as $review) {
?>
<legend><?php echo $review['f_name'] . " ". $review['l_name']; ?> said:</legend>
<div id = "items" class="">
<?php echo $review['content']; ?>
</div>
<br>
<div>
<?php echo $review['created_on']; ?>
</div>
<?php } ?>
</fieldset>
<?php
}

mysqli data fetch using explode no result getting

From table, i am fetching $rows['colorVariants']; but its value i am getting like:-
[JEADV9Q23ESG25HY,JEADV9Q2NFRNYV5Q,JEADV9Q2PNBTXGNX,JEADV9Q2XKWPXWSX,JEADY8ABWH9XNF4B,JEADZWEBDHWRJ2NQ,JEADZWEBRWZ4B4VS,JEADZWEBXDCGSYCF,JEAEYYX95YYC4DRA]
Then i used substr to remove square bracket.
Explode this value and again need to fetch it it the same table for similar products, but i am not getting any result.
<?php
$table = table1; // Table Name
$mysqli = mysqli connection // Mysqli Connection here
$result = $mysqli->query( "SELECT * FROM $table_name WHERE `id` = '$q' ");
while ( $rows = $result->fetch_assoc() ) {
$rows['colorVariants'] = [JEADV9Q23ESG25HY,JEADV9Q2NFRNYV5Q,JEADV9Q2PNBTXGNX,JEADV9Q2XKWPXWSX,JEADY8ABWH9XNF4B,JEADZWEBDHWRJ2NQ,JEADZWEBRWZ4B4VS,JEADZWEBXDCGSYCF,JEAEYYX95YYC4DRA] // Result Copy Sample
// substr using for remove square bracket
$colorVariants = substr($rows['colorVariants'], 1);
$newColorVariants = substr($colorVariants, 0, '-1');
$finalColorVariants = explode(',', $newColorVariants);
}
?>
<?php
for($i = 0; $i < count($finalColorVariants); $i++) {
$color = $finalColorVariants[$i];
$color = $mysqli->real_escape_string($color);
$colorVariants = $mysqli->query( "SELECT id,store,title,imageUrlStr,mrp,price,productBrand FROM $table_name WHERE `productId` = '".$color."' ");
if ($colorVariants) {
while ($rows = $colorVariants->fetch_assoc()) {
$id1 = $rows['id'];
$store1 = $rows['store'];
$title1 = $rows['title'];
$imageUrlStr1 = $rows['imageUrlStr'];
$mrp1 = $rows['mrp'];
$price1 = $rows['price'];
$productBrand1 = $rows['productBrand'];
}
?>
<div class="cloth-inner-similar-box">
<div class="cloth-inner-similar-boxin">
<img src="<?php echo $imageUrlStr1; ?>" />
</div>
<div class="cloth-inner-similar-boxin-offer">
<div class="cloth-inner-similar-boxin-offer-in">
<p>30% OFF</p>
</div>
</div>
<div class="cloth-inner-similar-boxin-head">
<?php echo $title1; ?>
</div>
<div class="cloth-inner-similar-price border-solid-bottom border-solid-top">
Best Buy # <?php echo $price1; ?>/-<?php echo $productBrand1; ?>
</div>
</div>
<?php
} }
$mysqli->close();
?>

php & pdo & mysql countrows returning 0

I have now spent several hours without getting anywhere.
I want to display number of rows in my query and here here is my code:
<?php
$user_id = 1;
$statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
$statement->execute(array(':id_user_profile'=> $id_user_profile));
$rResult = $statement->fetchAll();
echo count($rResult);
echo "<h2>Interesi</h2>";
while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){
?>
<div class="interest" id = "int<?php echo $row['id'];?>">
<span class = "intr-ico <?php echo $row['icon_class'];?>"></span>
<?php echo $row['name'];?>
</div>
<?php
}
?>
And i getting number 10 but now im not getting any interests displayed.
If you use this code now:
<?php
//$user_id = 1;
$statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
$statement->execute(array(':id_user_profile'=> $id_user_profile));
echo "<p>" . $statement->rowCount(). " interests:</p>";
while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){
?>
<div class="interest" id = "int<?php echo $row['id'];?>">
<span class = "intr-ico <?php echo $row['icon_class'];?>"></span>
<?php echo $row['name'];?>
</div>
<?php
}
?>
And now im getting all the interests displayed but it counts: 0 interests.
Any ideas who i can count number of interests?
If you read the documentation for PDOStatement::rowCount you will see this line
If the last SQL statement executed by the associated PDOStatement was
a SELECT statement, some databases may return the number of rows
returned by that statement. However, this behaviour is not
guaranteed for all databases and should not be relied on for portable
applications.
The work around is to count() function from php like you did. If that did not work then use COUNT(*) as result_count. then when you fetch read that value.
And i getting number 10 but now im not getting any interests displayed
problem
The reason why the result aren't displaying is because you fetched all the row already so you cannot use fetch() again.
solution
Use the array returned by fetchAll() instead and use a foreach instead
$rows = $statement->fetchAll();
echo "<p>" . count($rows). " interests:</p>";
foreach ($rows as $row){
//echo $row['name']
}
<?php
//$user_id = 1;
$statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
$statement->execute(array(':id_user_profile'=> $id_user_profile));
echo "<p>" . $statement->rowCount(). " interests:</p>";
$counter = 0; //declare counter
while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){
$counter++; //increment counter
?>
<div class="interest" id = "int<?php echo $row['id'];?>">
<span class = "intr-ico <?php echo $row['icon_class'];?>"></span>
<?php echo $row['name'];?>
</div>
<?php
}
?>
[NOTE: Edit by #DinoAmino removed the emphasis characters around the two uses of $counter, which caused the code to not compile for the question asker]
I solved my problem like this:
Here is the updated solving version. Thank you all for the input:
<?php
$user_id = 1;
$statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
$statement->execute(array(':id_user_profile'=> $id_user_profile));
$rows = $statement->fetchAll();
if(count($rows) >= '1') {
?>
<div class="your-interests">
<?php
echo "<p>" . count($rows). " interests:</p>";
foreach ($rows as $row){
?>
<div class="interest" id = "int<?php echo $row['id'];?>">
<span class = "intr-ico <?php echo $row['icon_class'];?>"></span>
<?php echo $row['name'];?>
</div>
<?php
}
?>
</div>
<?php } ?>

Categories