Render data from PHP DB query in HTML - php

I am a newbie to PHP but trying to learn it to enhance my programming skillset
So far i have the following PHP code in my page to return some data from my Database:
<?php
//code missing to retrieve my data
while($row = mysql_fetch_array($result))
{
echo '$row['Name']';
}
mysql_close($connection);
?>
This is working in that I can see the names from my database displayed on screen. I have seen as well that I can include html in the echo to format the data. However if I have the html code like below in a jQuery accordion outside my PHP code in the page - how can I dynamically place the Names in the specific h3 tags - so the first name in my table is Joe so that comes back in [0] element of array - is there a way I can reference this from my html code outside the php?
<div id="accordion">
<h3>Joe</h3>
<div>
<p>
Some blurb about Joe
</p>
</div>
<h3>Jane</h3>
<div>
<p>
Some blurb about Jane
</p>
</div>
<h3>John</h3>
<div>
<p>
Some Blurb about John.
</p>
</div>
</div>

Try something like this:
<?php while($row = mysql_fetch_array($result)) { ?>
<h3><?php echo $row['name']; ?></h3>
<div>
<p>Some blurb about Joe</p>
</div>
<?php } ?>
I'm assuming 'Some blurb about Joe' would also have to be replaced by a field in the DB, which you can accomplish in the same manner as the name.
#Gert is correct - the original mysql API is deprecated and should not be used anymore. Look into mysqli or PDO, instead.

add your html in while loop like this
<?php
//code missing to retrieve my data
while($row = mysql_fetch_array($result))
{
?>
<h3><?php echo $row['Name']?></h3>
<div>
<p>
Some blurb about <?php echo $row['Name']?>
</p>
</div>
<?php
}
mysql_close($connection);
?>

Like this :
<div id="accordion">
<?php
while($row = mysql_fetch_array($result))
{
<h3><?php echo $row['Name'] ?></h3>
<div>
<p>
Some blurb about Joe
</p>
</div>
} ?>
</div>

Related

Echo an image tag with site_url() inside PHP tags

I have a loop in my view that outputs all the content gathered from the database:
<?php foreach($content as $contentRow): ?>
<?php
echo $contentRow->value;
?>
<?php endforeach; ?>
This works fine for HTML strings like:
<h2><strong>Example Text</strong></h2>
however I have some image content that I would like to display and I have tried the following database entries to no avail:
<img src="<?php echo site_url('pathToImage/Image.png'); ?>" alt="Cover">"
<img src="site_url('pathToImage/Image.png')" alt="Cover\">"
I feel like I am missing a step on how to use PHP values in this way.
How do I access the URL of the image and use that to show the image?
Full Code Edit
<?php
$CI =& get_instance();
?>
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="col-md-2"></div>
<div class="col-md-20">
<!--<form class="form-center" method="post" action="<?php echo site_url(''); ?>" role="form">-->
<!-- <h2 class="">Title</h2>
<h2 class=""SubTitle/h2>-->
<?php echo $this->session->userdata('someValue'); ?>
<!--//<table class="" id="">-->
<?php foreach($content as $contentRow): ?>
<tr>
<td><?php
echo $contentRow->value;
?></td>
</tr>
<?php endforeach; ?>
<!--</table>-->
<!--</form>-->
</div>
<div class="col-md-2"></div>
</div>
</div>
</div><!-- /.container -->
and the values are being read out in $contentRow->value;
I have to verify this, but to me it looks like you are echo'ing a string with a PHP function. The function site_url() is not executed, but simply displayed. You can execute it by running the eval() function. But I have to add this function can be very dangerous and its use is not recommended.
Update:
To sum up some comments: The use of eval() is discouraged! You should reconsider / rethink your design. Maybe the use of tags which are replaced by HTML are a solution (Thanks to Manfred Radlwimmer). Always keep in mind to never trust the data you display, always filter and check!
I'm not going to accept this answer as #Philipp Palmtag's answer helped me out alot more and this is more supplementary information.
Because I'm reading data from the database it seems a sensible place to leave some information about what content is stored. In the same table that the content is stored I have added a "content type" field.
In my view I can then read this content type and render appropriately for the content that is stored. If it is just text I can leave it as HTML markup, images all I need to do is specify the file path and then I can scale this as I see fit.
I have updated my view to something akin to this and the if/else statement can be added to in the future if required:
<?php foreach($content as $contentRow): ?>
<?php if ($contentRow->type != "image"): ?>
<?php echo $contentRow->value; ?>
<?php else: ?>
<?php echo "<img src=\"".site_url($contentRow->value)."\">"; ?>
<?php endif; ?>
<?php endforeach; ?>

How can I mix PHP and HTML code?

I have a while loop and I have a HTML code inside the while loop. Inside this HTML code there is PHP code reading a variable that depends on the condition of the while loop.
This variable should be evaluated by PHP. I wrote the code below to solve this but it doesn't work.
$row[0] depends on the condition of while. My code only outputs an empty space for this variable.
<?php
while ($row = mysql_fetch_row($stt)) {
$html='<div class="data">
<?php echo nl2br($row[0]."\n"); ?>
<p>comment
like
share</p>
<p>
0 <span>likes</span>
</p>
<p>
_____________________
</p>
</div>';
echo $html;
}
?>
If you want to display something row by row, do this:
<?php
while($row = mysql_fetch_row($stt)){
$html="<div class='data'>" . nl2br($row[0]) . "\n<p>comment<a href=''>like</a><a href=''>share</a></p><p>0<span>likes</span></p><p></p></div>";
echo $html;
}
?>
> <?php echo nl2br($row[0]."\n"); ?>
this part should be outside of $html.
The interpreter on server side couldnt run.Accordin to php, this part is not a code block. It is just a text.
I found the answer of my question!!!
This is the solution:
<?php
while($row = mysql_fetch_row($stt)){ ?>
<div class="data">
<?php echo nl2br($row[0]."\n"); ?>
<p>comment
like
share</p>
<p>
0
<span>likes</span>
</p>
<p>
_____________________
</p>
</div>
<?php
}
?>

How to display certain comments stored on a database

I've created a form for a comment box that I'm going to use on a couple of different pages. It sends the data to a table called "comments" in my database that has columns "id" "author" "body" "created" and "page_name". I'm new to php and I'm trying to figure out how to just display the comments that have the same "page_name" value as the current page.
To get the "page_name", I used this code in the form:
<input type="hidden" name="page_name" value="<?=$_SERVER['REQUEST_URI']?>" />
This is the code I'm building to display the comments:
<div id="comments">
<?php foreach($comments as $comment): ?>
<div class="comment" style="margin-bottom: 2em;">
<div class="author">
<b><?php echo htmlentities($comment->author); ?>:</b>
</div>
<div class="meta-info" style="font-size: 0.8em;">
<?php echo datetime_to_text($comment->created); ?>
</div>
<div class="body">
<?php echo strip_tags($comment->body, '<strong><em><p>'); ?>
</div>
</div>
<?php endforeach; ?>
<?php if(empty($comments)) { echo "No Comments."; } ?>
</div>
I'm just not sure how to tell the page to display only the comments that have the same "page_name" value as the page the user is on. Any help would be appreciated!
You have to query the data corresponding to the url like.
For database connection use the code below:
<?php
// Create connection
$db_con=mysql_connect('servername','db username','dbpassword');
if (!$db_con)
{
die('Could not connect: ' . mysql_error());
}
$connection_string=mysql_select_db('db name',$db_con);
?>
For query use the code:
$url=$_SERVER['REQUEST_URI'];
$query=mysql_query("select * from comments where page_name='".$url."'");
while($result=mysql_fetch_row($query))
{
echo $result[0]."<br>".$result[1]."<br>"; // echo all values that are needed for displaying. You can do the coding for displaying formatted values inside this loop.
}

Show div only if mySQL info exists

I have a MySQL database storing some basic user info, so: name, email, and two phone numbers. I want to make a page with dynamic php text showing the users info, but in the database only one phone number is required. On the page I have:
<p id="first"> Some non-dynamic text </p>
<p> <?php echo $row_rsCustomer['first_name']; ?> </p>
<p> <?php echo $row_rsCustomer['email']; ?> </p>
<p> <?php echo $row_rsCustomer['phone_one']; ?> </p>
<p id="phonetwo"> <?php echo $row_rsCustomer['phone_two']; ?> </p>
<p id="second"> Some non-dynamic text </p>
I dont want the #second to be pushed down if the #phonetwo is empty. I was thinking of using some javascript like this:
if( #phonetwo.innerhtml == ""){
#phonetwo.style.display="none";
But I was wondering if there's a way to do this using php? The javascript solution will work I suppose, but I'm pretty sure I've seen somewhere a more "correct" way to do this, I just don't remember what it was nor can I find it anywhere.
Just wrap the paragraph in a conditional
<?php if(isset($row_rsCustomer['phone_two']) && $row_rsCustomer['phone_two']):?>
<p id="phonetwo"> <?php echo $row_rsCustomer['phone_two']; ?> </p>
<?php endif?>
<?php if (!empty($row_rsCustomer['phone_two'])) { ?>
<p id="phonetwo"><?php echo $row_rsCustomer['phone_two'] ?></p>
<?php } ?>
Just follow this pattern anytime you need to hide HTML from PHP:
<? if (your condition) { ?>
Html
<? } ?>
It is much better than doing it in JS since it does't send any data to the browser.
First check is it empty or not
<?php if(!empty($row_rsCustomer['phone_two'])) { ?>
<p id="phonetwo"> <?php echo $row_rsCustomer['phone_two']; ?> </p>
<?php } ?>
check if $row_rsCustomer['phone_two'] is not empty and then display your <p> :
<?php if (isset($row_rsCustomer['phone_two'])) { ?>
<p id="phonetwo"><?php echo $row_rsCustomer['phone_two'] ?></p>
<?php } ?>

Add HTML elements to the current page using PHP

So I have the need to dynamically add html content using php which isnt the tricky part but I'm trying to put the HTML into a different location in the document than where the PHP is being run. So for example:
<div id="firstDiv">
<?php
echo "<div id=\"firstDivA\"></div>";
echo "<div id=\"secondDivA\"></div>";
?>
</div>
<div id="secondDiv">
</div>
But I want to be able to place the some HTML inside "secondDiv" using the PHP that is executed in the "firstDiv". The end result should be:
<div id="firstDiv">
<div id="firstDivA"></div>
</div>
<div id="secondDiv">
<div id="secondDivA"></div>
</div>
But I have no idea how to go about doing that. I read about some of the DOM stuff in PHP 5 but I couldn't find anything about modifying the current document.
You can open/close "blocks" of PHP wherever you like in your HTML
<div id="firstDiv">
<?php echo '<div id="firstDivA"></div>'; ?>
</div>
<div id="secondDiv">
<?php echo '<div id="secondDivA"></div>'; ?>
</div>
You can also capture the output if necessary with ob_start() and ob_get_clean():
<?php
$separator = "\n";
ob_start();
echo '<div id="firstDivA"></div>' . $separator;
echo '<div id="secondDivA"></div>' . $separator;
$content = ob_get_clean();
$sections = explode($separator, $content);
?>
<div id="firstDiv">
<?php echo $sections[0]; ?>
</div>
<div id="secondDiv">
<?php echo $sections[1]; ?>
</div>
Why not just move the relevant code to the right place?
<div id="firstDiv">
<?php
echo "<div id=\"firstDivA\"></div>";
?>
</div>
<div id="secondDiv">
<?php
echo "<div id=\"secondDivA\"></div>";
?>
</div>
The .php file is continuous thus if you have two separate <?php ?> tags they will be able to share the same variables.
<div id="firstDiv">
<?php
echo "<div id=\"firstDivA\"></div>";
$div2 = "<div id=\"secondDivA\"></div>";
?>
</div>
<div id="secondDiv">
<?php echo $div2 ?>
</div>
This will give the desired effect. (Demonstrates the use of variables)
I'm not sure what you're asking. Perhaps just add an echo statement to the second div.
<div id="firstDiv">
<?php echo "<div id=\"firstDivA\"></div>"; ?>
</div>
<div id="secondDiv">
<?php echo "<div id=\"secondDivA\"></div>"; ?>
</div>
Or do you mean you want to make DIV changes after PHP? Try jQuery!
Or do you mean you want to make DIV changes before PHP is finished? Perhaps phpQuery is good for you then.
If you want to work with XML-data (read XHTML), you'd rather use an appropriate XML processor.
DomCrawler is an excellent to work with DOM. It works with the native DOM Extension and therefore is fast and widely used.
Here an example from the doc on how to add content:
$crawler = new Crawler();
$crawler->addHtmlContent('<html><div class="foo"></div></html>');
$crawler->filter('div')->attr('class') // returns foo

Categories