Displaying PHP Functions With HTML/CSS - php

I have some php and css code that I'm trying to break down into functions. I need some advice on how to approach this.
<?php
$info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
while ($info_row = mysqli_fetch_array($info))
{
$info_id = $info_row['info_id'];
$info_title = $info_row['info_title'];
?>
<div style="width: 100%;">
<div style="float: left;">
<?php echo $info_id; ?>
</div>
<div style="float: left;">
<?php echo $info_title; ?>
</div>
<div style="clear: both;"></div>
</div>
<?php } ?>
This appears as such:
1 One
2 Two
3 Three
4 Four
Below is what I have so far with separating everything into functions:
function get_info()
{
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
while ($info_row = mysqli_fetch_array($info))
{
$result[] = $info_row;
}
mysqli_free_result($info);
return $result;
}
function display_info_id()
{
$result=forum();
foreach ($result as $info_row)
{
$info_id = $info_row['info_id'];
echo $info_id;
}
}
function display_info_title()
{
$result=forum();
foreach ($result as $info_row)
{
$info_title = $info_row['info_title'];
echo $info_title;
}
}
<?php get_info(); ?>
<div style="width: 100%;">
<div style="float: left;">
<?php display_info_id(); ?>
</div>
<div style="float: left;">
<?php display_info_title(); ?>
</div>
<div style="clear: both;"></div>
</div>
This displays as:
1234 OneTwoThreeFour
I understand why it displays as such, but I don't understand how to get it to show the way I want it to. Any advice would be helpful.
Edit--
Is this at all possible to do with the 3 functions I have? I do not want info_id and info_title in the same function.
When I look at software, such as WordPress, it seems I may have to surround my HTML in some kind of loop, and change the way the functions get info?

You are calling a separate loop for each of your variables. It is kind of unnecessary to split this into multiple functions, since the loop requires that the two variables be displayed together.
How would I handle it? I would store the SQL result into a complete array, then loop over that array to output your HTML. That could be split into two functions, if you wish. Maybe useful if you need to use the results more than once on the page.
I'm using the HEREDOC string syntax to combine the PHP variables, (wrapped in {}) with the HTML block. This saves you having to jump in and out of PHP via <?php ?>
// This function is fine.
function get_info()
{
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
while ($info_row = mysqli_fetch_array($info))
{
$result[] = $info_row;
}
mysqli_free_result($info);
return $result;
}
function display_result($result)
{
// Loop over your results and display each
foreach ($result as $r)
{
// Now use the HEREDOC syntax to form your HTML block instead
// of intermingling PHP function calls
echo <<<HTML
<div style="width: 100%;">
<div style="float: left;">
{$r['info_id']}
</div>
<div style="float: left;">
{$r['info_title']}
</div>
<div style="clear: both;"></div>
</div>
HTML;
// There must be no whitespace before or after the HTML; on the previous line!
}
}
Now to retrieve your data and display it:
<?php
$results = get_info();
display_result($results);
?>

You need to refactor your display logic into one loop, instead of two separate loops.
For example:
<?php get_info(); ?>
<div style="width: 100%;">
<div style="float: left;">
<?php display_info_id(); ?>
</div>
<div style="float: left;">
<?php
$result=forum();
foreach ($result as $info_row)
{
$info_id = $info_row['info_id'];
$info_title = $info_row['info_title'];
echo $info_id . " . $info_title . "<br/>\n";
}
?>
</div>
<div style="clear: both;"></div>
</div>

Related

Reload DIV with new images

I have an employee database which includes images as well as their work location (specialty). I have created a page where I fill out a form and upload the image to a directory and the path to the database. I then load the main page where I pull in all the images from the database (into the "photos" DIV. Everything works fine.
What I would like to do is reload the images in the DIV based on a MySQL query from a button. For example, instead of showing all employees, I only want to see those who have a specific job function i.e. Management. I currently have this accomplished by redirecting to a new page, where I run a specific query and that works fine as well. However, I'd like to learn how this is done without creating a new page for each query. I've spent many days looking at AJAX and PHP tutorials, which I how I was able to accomplish what I have, but I can't find a method to do what I want. This is the relevant part of my code:
Main.php
<div class="container-fluid">
<div class="row">
<div class ="col-lg-12" style="width: 18%; height: 100%; border:3px solid red;">
MANAGEMENT
HIGH
</div>
<?php
include ('db_connect.php');
//include_once ('functions.php');
$result = $db->query("SELECT * from monctonfir order by initials ASC");
if($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$imageURL = 'image/'.$row["file"];
$initial = $row["initials"];
$name = $row["name"];
?>
<div id="photos" class = "col-lg-1 no-gutters" style="margin-top:1rem;">
<div class="card text-center" style="width: 5rem;">
<a href = "#">
<img class="img card-img-top" src = "<?php echo $imageURL ?>">
</a>
<div class = "card-body">
<h5 class = "card-title round-button" style="text-align: center;"><?php echo $initial ?></h5>
</div>
</div>
</div>
<?php }
} ?>
</div>
Can someone point me in the right direction?
Thanks!
You don't need jQuery for what you are doing. You can use query/GET parameters to build your sql so you don't have to create a different page. Like:
<div class="container-fluid">
<div class="row">
<div class ="col-lg-12" style="width: 18%; height: 100%; border:3px solid red;">
MANAGEMENT
HIGH
ALL
</div>
<?php
include ('db_connect.php');
//include_once ('functions.php');
$sql = "SELECT * from monctonfir WHERE 1 ";
if(isset($_GET['job'])) $sql .= " AND job = '".$_GET['job']."' ";
$sql .= " order by initials ASC";
$result = $db->query($sql);
if($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$imageURL = 'image/'.$row["file"];
$initial = $row["initials"];
$name = $row["name"];
?>
<div id="photos" class = "col-lg-1 no-gutters" style="margin-top:1rem;">
<div class="card text-center" style="width: 5rem;">
<a href = "#">
<img class="img card-img-top" src = "<?php echo $imageURL ?>">
</a>
<div class = "card-body">
<h5 class = "card-title round-button" style="text-align: center;"><?php echo $initial ?></h5>
</div>
</div>
</div>
<?php }
} ?>
</div>
The simplest way is to use the load function of Jquery
Jquery
For example:
$( "#divID" ).load( "loadEmploye.php", { parameters1: 25, parameters2:3 });

PHP display comma separated GROUP_CONCAT values separately

This question is with reference to my previous question posted here PHP display results equivalent to comma separated values in the database.
I nearly solved the problem. Now I am stuck somewhere else which if solved my issue will be solved.
The problem is:
Please have a look at this code first
<div class="ads-container">
<?php
$cat = $pdo->prepare("SELECT * FROM ads_category");
$cat-> execute();
$i = 0;
while($s = $cat->fetch()){
$ads = $pdo->prepare("SELECT *, GROUP_CONCAT(memberships.mbs_color) FROM advertisements
INNER JOIN memberships ON FIND_IN_SET(memberships.mbs_id, advertisements.ad_memberships)
LEFT JOIN ads_category ON advertisements.ad_category = ads_category.ac_id
WHERE ad_credits >= ac_credits AND ad_category = :cat AND ad_status = 'active'
GROUP BY advertisements.ad_id");
$ads-> bindValue(':cat', $s['ac_id']);
$ads-> execute();
while($a = $ads->fetch()){ extract($a);
?>
<div class="" <?php if($i++ != 0){ echo "style='margin-top: 30px'"; } ?>>
<i class="fa fa-bullhorn" aria-hidden="true"></i> <?php echo $ac_category; ?>
</div>
<div class="col-sm-4">
<div class="adcover">
<div class="ad-title">
<?php echo $ad_title; ?>
</div>
<div class="ad-footer-two"> <?php echo $a['GROUP_CONCAT(memberships.mbs_color)']; // this is giving me the values comma separated perfectly ?>
<span class="membership-indicator" style="background: <?php echo $mbs_color; ?>; margin-top: 4px; margin-left: 5px"></span>
</div>
</div>
</div>
<?php } } ?>
</div>
Now the problem is when I echo <?php echo $a['GROUP_CONCAT(memberships.mbs_color)']; ?> I get the comma separed color values perfectly. But I want to display it as a color not as a word in <span class="membership-incdicator"></span> as exactly as in https://prnt.sc/hvj91s. So, how can I do that? Do I have to use foreach() function here? If yes then please tell me how to write that code. If not, then please tell me how to accomplish this.
This whole thing looks very messy, but explode the list and loop:
$mbs_colors = explode(',', $a['GROUP_CONCAT(memberships.mbs_color)']);
foreach($mbs_colors as $color) {
echo '<span class="membership-indicator" style="background: ' . $color . '; margin-top: 4px; margin-left: 5px"></span>';
}
Also, you can use an alias: SELECT *, GROUP_CONCAT(memberships.mbs_color) AS colors and then use: $a['colors'].
This does beg the question; why GROUP_CONCAT then? I'm not sure but there must be a better query.

how to change the formatting in the php code that renders questions from a text file

A webpage that displays quizzes generated from question.txt files is shown as follows:
I have the following code that is in a php document. As you can see, it is this part of the php that appears to generate the general appearance of the display, such as the title: "Test your Knowledge".
<!-- Main
============================================= -->
<section id="code">
<div class="container-fluid" style="text-align:center;">
<p></br></br></br></br></p>
<div class="row">
<div class="col-lg-2 text-left">
<p></br></br></br></br></p>
<?php include 'quiz-sidebar.php'; ?>
</div>
<div class="col-lg-10 text-center">
<h2 class="section-heading" style="color:black;">Test Your Knowledge : <?php include "content/quiz/". $_GET['quiz'] ."/title.txt"; ?></h2>
<p></br></p>
<div style="border-style: solid; border-radius: 5px; border-width: 5px;">
<p></p>
<form method="POST" action="<?php echo "quiz-result.php?quiz=".$_GET['quiz']; ?>">
<?php
$loadedQuestions = readQuestions("content/quiz/". $_GET['quiz'] ."/questions.txt");
displayTheQuestions($loadedQuestions);
?>
<input type="submit" name="submitquiz" value="Submit Quiz"/>
</form>
<p></p>
</div>
<p></br></br></br></br></p>
</div></div>
</div>
</section>
The HTML inside it is centre aligned, and I would like it to be left aligned. I would also like to allow for the ability for some introductory text to be added before question 1, without it automatically rendering as a question (with the answer bullets displaying).
The format is:
Question.txt file contains the questions
1. What is Python?: A) An ancient greek monster, B) A high level programming language, C) A low level programming language, D) A language only used for the web
2. Fill in the blanks. I _ _ _ _ _ _ _ _ _ matters in python! : A) Indentation, B) Illustriousness, C)Inventiveness, D) Irritation
Answer.txt file contains the answers
The php that generates the questions - which is also inside the same php document as the first bit of MAIN code - is below
function readQuestions($filename) {
$displayQuestions = array();
if (file_exists($filename) && is_readable($filename)) {
$questions = file($filename);
foreach ($questions as $key => $value) {
$displayQuestions[] = explode(":",$value);
}
}
else { echo "Error finding or reading questions file."; }
return $displayQuestions;
}
function displayTheQuestions($questions) {
if (count($questions) > 0) {
foreach ($questions as $key => $value) {
preg_match("/{{(\w*\d*\W*\D*)*}}/", $value[0], $output_array);
$to_import = "content/quiz/". $_GET['quiz'] . "/". substr($output_array[0], 2, -2);
if (!empty($output_array)){
$val = str_replace($output_array[0], "", $value[0]);
echo "<b>$val</b><br/>";
include ($to_import);
echo "</br></br>";
} else {
echo "<b>$value[0]</b><br/>";
}
$choices = explode(",",$value[1]);
foreach($choices as $value) {
$letter = substr(trim($value),0,1);
preg_match("/{{(\w*\d*\W*\D*)*}}/", $value, $output_array);
$val = str_replace($output_array[0], "", $value);
echo "<input type=\"radio\" name=\"$key\" value=\"$letter\" style=\"text-align:left;\">$val<br/>";
if (!empty($output_array)){
$to_import = "content/quiz/". $_GET['quiz'] . "/". substr($output_array[0], 2, -2);
echo "</br>";
include ($to_import);
echo "</br></br>";
}
}
echo "<br/>";
}
}
else { echo "No questions to display."; }
}
The main question is how to go about formatting the text inside the question.txt file (rendered by the php code above) which is displayed on the page, as explained above. (left align, as well as adding additional information without it being a question)
The second part of your question could be achieved by creating a link (above where the questions are rendered) to another text or php file, like so:
<div style="border-style: solid; border-radius: 5px; border-width: 1px;">
<p></p>
<form method="POST" action="<?php echo "quiz-result.php?quiz=".$_GET['quiz']; ?>">
<?php
$loadedQuestions = readQuestions("content/quiz/". $_GET['quiz'] ."/additionalinfo.php");
displayTheQuestions($loadedQuestions);
?>
Note the additionalinfo.php which is being loaded instead of what you have originally. Php won't let you deal with html files, so it would have to be a php or txt file you load here.

PHP putting the right row in the right html div

This one is going to be a bit hard to explain but I am going to try my best.
I have a database with a table called content with 3 columns, I’m trying to get the values as rows and put them in different <div>’s. here is what I wrote so far
<?php
$sql = "SELECT * FROM content";
$query = mysqli_query($db, $sql) or die (mysqli_error());
$contentDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$content_id = $row["id"];
$content_title= $row["title"];
$content_text = $row["text"];
$contentDisplay .= '<h1>'.$content_title.'</h1> <p>'.$content_text.'</p>' ."\n";
}
$row_cnt = $query->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
?>
The row count gives 4 rows which is correct amount of rows.
In my html I have <?php echo $contentDisplay; ?> which puts out all 4 rows after each other, but I need to show the first row in my first <div>, the second row in my second <div> and so forth. thanks in advance
Update: I forgot to say that I have my <div>'s in the html part with different styles. all i need is the first row in one <div> (like on top of the page) and second row in another <div> (like on the bottom of the page) :)
Update2: here is the html code
<div class="content-top">
<section>
<h1></h1>
<p></p>
</section>
</div>
<div class="content-left">
<section>
<h1></h1>
<p></p>
</section>
</div>
<div class="content-center">
<section>
<h1></h1>
<p></p>
</section>
</div>
<div class="content-right">
<section>
<h1></h1>
<p></p>
</section>
</div>
i want the first row to be displayed in <div class="content-top"> the second row in <div class="content-left"> the third row in <div class="content-center"> and the fourth row in <div class="content-right">
<?php
$sql = "SELECT * FROM content";
$query = mysqli_query($db, $sql) or die (mysqli_error());
$rows = [];
while ($row = mysqli_fetch_array($query))
$rows[] = '<h1>'.$row['title'].'</h1> <p>'.$row['text'].'</p>' . "\n";
?>
<div class="content-top">
<section>
<?php echo $rows[0]; ?>
</section>
</div>
<div class="content-left">
<section>
<?php echo $rows[1]; ?>
</section>
</div>
<div class="content-center">
<section>
<?php echo $rows[2]; ?>
</section>
</div>
<div class="content-right">
<section>
<?php echo $rows[3]; ?>
</section>
</div>
$contentDisplay .= '<div><h1>'.$content_title.'</h1> <p>'.$content_text.'</p></div>' ."\n";
Just add divs for each row? :) This way, each row in the database will get a div.
Each row will be appended to the $contentDisplay variable, but since all you are doing is printing it, you can print the html directly.
I'm not sure why you are being downvoted, since you are asking a valid question with code that shows what you have tried so far.

How to get multiple records to display in webpage on mysql query?

I know this is a stupid question, and I've tried looking at the other answers, but they are not working for me. I have taken over maintaining a site with a lot of pre-existent code, and need to add in a new query.
I have managed to get the query to work and to display in the webpage, but only the first record displays. I know somehow I'm missing the looping function, but I can't figure out how to add it to the function so all records display.
I've been fighting with this for hours, and would really appreciate some pointers!
Here's the code in the main listing.php file - the first query is pre-existing, the new query is to the getFeedback procedure starts with "$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";".
if(($PMDR->get('Authentication')->checkPermission('admin_view_real_prices')) || ($PMDR->get('Session')->get('user_id'))) {
$admin_user_can_view_prices = true;
$template_content->set('admin_user_can_view_prices',$admin_user_can_view_prices);
$sql = "CALL sp_Entertainers_Contact_Info(".$listing['unique_listing_id'].")";
//all variables come from db.php
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$rs = $mysqli->query($sql);
while($row = $rs->fetch_assoc())
{
$template_content->set('primaryEmail',$row['PrimaryEmail']);
$template_content->set('secondaryEmail',$row['SecondaryEmail']);
$template_content->set('cellPhone',$row['CellPhone']);
$template_content->set('homePhone',$row['HomePhone']);
$template_content->set('alternatePhone',$row['AlternatePhone (Please Specify)']);
$template_content->set('streetAddress',$row['StreetAddress']);
$template_content->set('entertainerCity',$row['City']);
$template_content->set('entertainerState',$row['State']);
$template_content->set('entertainerZip',$row['Zip']);
$template_content->set('entertainerNotes',$row['Note']);
}
$data = "";
$griddata = "";
$grid = "";
$entertainerid = $_POST['unique_listing_id'];
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";
$rs = $mysqli->query($sql2);
$numrows = mysqli_num_rows($rs)." Rows";
while($row = $rs->fetch_assoc()) {
$allRows[] = $row;
$style = ($altRowCount % 2 == 0 ? ' class="row" ' : ' class="row tdg" ');
$template_content->set('eventID',$row['EventID']);
$template_content->set('dateOfEvent',$row['DateOfEvent']);
$template_content->set('clientFollow',$row['ClientFollowUp']);
$template_content->set('performerFollow',$row['PerformerFollowUp']);
$griddata .= "
<div $style>
<div class='col-xs-2 col-sm-2 col-md-2' onclick=\"popupEvent('".$row['EventID']."')\">".$eventID."</div>
<div class='col-xs-2 col-sm-2 col-md-2'>".$dateOfEvent."</div>
<div class='col-xs-4 col-sm-4 col-md-4'>".$clientFollow."</div>
<div class='col-xs-4 col-sm-4 col-md-4'>".$performerFollow."</div>
</div>
";
$altRowCount = $altRowCount + 1;
}
$mysqli->close();
$grid = "
<div style='max-height: 110px; overflow: scroll;'>
<table class='fancygrid'>
<tbody>
".$griddata."
</tbody>
</table>
</div>
<!-- <div style='width: 100%; font-weight: bold; color: red;'>".$numrows."</div> -->
";
echo $gridHeader.$grid;
} //getEntertainerFeedback
} // is an office user logged in? -- end
Here's the code that is in the included listing.tpl file that contains the HTML for the webpage:
<div class="row">
<div class='col-xs-2 col-sm-2 col-md-2' onclick="popupEvent(".$row['eventID'].")"><?php echo $eventID ?></div>
<div class='col-xs-2 col-sm-2 col-md-2'><?php echo $dateOfEvent ?></div>
<div class='col-xs-4 col-sm-4 col-md-4'><?php echo $clientFollow ?></div>
<div class='col-xs-4 col-sm-4 col-md-4'><?php echo $performerFollow ?></div>
</div>
I tried adding
<?php
foreach ($allRows as $row) {
?>
<?php } ?>
around the html code above but that just causes no records to display at all, not even one.
Since you have to be logged in to view this data, I can't share the link, but here's what the blue logged in area looks like with the one record showing at bottom of blue box:
ETA: FYI - I also tried just echoing .grid in my html code - but that gives me not results at all, not sure why.
Any help to point me in the right direction or tell me what I'm missing is greatly appreciated!!
Thanks!
First of all, you have opened database connection twice
$data = "";
$griddata = "";
$grid = "";
$entertainerid = $_POST['unique_listing_id'];
# remove this line, just to be sure it doesn't cause any problems
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";
Secondly, debug your query result by printing something in while loop, just to be sure that query returns multiple rows as result
And last thing I should try is to declare $allRows as an Array before your while loop, just for safety
$allRows = array();
while($row = $rs->fetch_assoc()) {
$allRows[] = $row;
Then try this approach
<?php
foreach ($allRows as $row) {
?>
<!-- HTML -->
<?php } ?>
Edit:
This looks like some kind of View object, so you have predefined HTML code in it and you just fill it with your values from database, so I think your while statement is overriding values in your view with each loop and that's the reason why you probably get one record. Your View is probably designed to hold one row/data
$template_content->set('eventID',$row['EventID']);
$template_content->set('dateOfEvent',$row['DateOfEvent']);
$template_content->set('clientFollow',$row['ClientFollowUp']);
$template_content->set('performerFollow',$row['PerformerFollowUp']);

Categories