PHP echo formatting of html - php

I am trying to echo out multiple table rows on my sql query and provide them with alternating colors to improve the aesthetic value of my site. I am fairly new to php and I am extremely fussy over the presentation of my code and therefore I would like to include the output html into my PHP block to improve readability.
I have browsed some past threads but I am still rather unclear of how the formatting of a string works in PHP, the code below shows my attempt of formatting the output:
echo '<tr class=" . 'if( $class_style %2 == 0 ){ echo "row_dark"; } else echo "row_light"' . ">';
What am I doing wrong here?
Regards
Alex.

You can't put an if structure in an echo.Use that :
echo '<tr class="'. ($class_style %2 == 0) ? 'row_dark' : 'row_light' . '">';
It's a ternary operation.

You should use like this right syntax:
echo '<tr class="'.($class_style %2 == 0 ? "row_dark" : "row_light").'">';

It should be
echo '<tr class=" '. instead of echo '<tr class=" .'

<?php echo '<tr class="'.(($class_style %2 == 0)?'row_dark':'row_light').'">';?>
or
<?='<tr class="'.(($class_style %2 == 0)?'row_dark':'row_light').'">';?>

Related

Making a 2 coloumn table with PHP without 'echoing' so much

I am working with PHP and My SQL to get data from an SQL database and show it in 2 columns.
I have figured out how to do it with the code as below. However I am working with a complex HTML template and don't want to echo every single HTML line to get it work - It will be very complicated to read and fix if there is an issue!
<table>
<?php
$i = 0;
while($row = $result->fetch_assoc()) {?>
<?php if (++$i % 2 != 0) echo "<tr>";?>
<?php echo "<td>" .$row['fname']."</td>"; ?>
<?php if ($i % 2 == 0);
} if ($i % 2 != 0); ?>
<td></td></tr>
</table>
I have simplified the template as below. Here I am 'echoing' within the HTML which I find easier to read and understand:
<div class=container>
<div id="fname"><a>First Name:</a><?php echo $row['fname'];?></div>
<div id="website"><a>Website:</a><?php echo $row['website'];?></div>
</div>
To summarize, is it possible to take my data from the database and show it in 2 columns without having to echo every single HTML line. Keeping my HTML structure similar to the above?
The column layout I am try to achieve is as below:
1 | 2
-----
3 | 4
-----
5 | 6
-----
I have not been able to find an example anywhere! Thanks!
There are advantages to writing HTML out in PHP script and there are also advantages to breaking into PHP from your HTML script. It really just depends on the circumstances.
For example if I am writing html that is generated from loops of has alot of variable inputs I will write the HTML inside the PHP. However, If I am writing a big chunk of HTML with only a few variables I will break into PHP from the HTML.
It really just depends on the circumstances.
That being said, when writing HTML from inside of PHP I will break it down and concatenate the HTML as much as possible. That way I am not breaking in and out of PHP to get the task accomplished. The more you code the easier that will get.
Below is how I would write your code. Notice I never broke in and out of PHP.
echo
'<table>';
$i = 0;
while($row = $result->fetch_assoc()) {
echo
'<tr>';
echo
'<td>' . $row['fname'] . '</td>' .
'<td>' . $row['lname'] . '</td>';
echo
'</tr>';
}
echo
'</table>';
Hope this helps.
You could do something like this in PHP, just another very simple option.
$str = '';
while($row = $result->fetch_assoc()) {
$str .= '<tr><td>'.$row['value1'].'</td><td>'.$row['value2'].'</td></tr>';
}
I don't know all the correct keys in the $row, but I think you get the idea.
And than the HTML would be like this:
<table>
<?php echo $str; ?>
</table>
Just a little hint. You can google on a MVC construction. This stands for Model View Controller and it is in my opinion the best way to keep your code organised.

PHP If statement for file_exists for image or video content from database to avoid blank space on website when no data is present

Having an issue with a blog webpage I’m trying to create which includes a database. The database contains 3 columns: 'title' 'content' which are both text and 'media' which is a mediumblob for images.
<?php echo "img src='data:image/jpeg;base64,".base64_encode($row['media'])."'>"; ?>
Everything works fine except when I don't include an image (in the data row) and just include a 'title' & 'content' it leaves a blank square on the page where an image should of been.
So firstly any advice towards an if statement (or something like that) that would check if file_exists (for specifically images) and display it, else exclude <img> (to avoid the blank square).
Something like this (which I know is totally wrong, sorry):
<?php
if (file_exists($row['media'])) { echo
"?php echo "img src='data:image/jpeg;base64,".base64_encode($row['media'])."'>"; ?>"
;}
else { echo
"!--?php echo "img src='data:image/jpeg;base64,".base64_encode($row['media'])."'>"; ?>-->"
;}
?>
Ideally with this blog, every entry will contain EITHER an image OR an embedded video via iframe, which I assume is something like this:
<iframe src="?php echo $emeddedLink; ?>"</iframe> (Haven't tried it as yet)
But I don't want a blank <iframe> showing on the website when using an image for the blog entry and vice versa I don't want a blank <img> box when using an embedded video.
Please any help would be greatly appreciated and apologies in advance for what might seem like a very basic question but I’ve been searching and can't seem to find anything really to avoid the blank square when I don't include an image in a data row... Thanks!
Typically you'd have an IF statement within your loop that spits out the list of content from your database. Something like this.
<?php
$sql = '
SELECT
*
FROM
`my_table`
';
$query = mysql_query($sql) OR die(mysql_error());
print '<table>';
print '<tr><td>Title</td><td>Content</td><td>Media</td></tr>';
while ($row = mysql_fetch_assoc($query)) {
print '<tr>';
print '<td>'. $row['title'] .'</td>';
print '<td>'. $row['content'] .'</td>';
print '<td>'
if (
$row['media'] == '' ||
$row['media'] == null ||
empty($row['media']) ||
!$row['media']
) {
print 'No Media Available';
}
else {
print $row['media'];
}
print '</td>';
print '</tr>';
}
print '</table>';
?>
That should get you going if I understand what you want to do. I tried to format the code to be as easy to read for a beginner as possible. The lines that would most closely pertain to your issue above are these lines here:
if (
$row['media'] == '' ||
$row['media'] == null ||
empty($row['media']) ||
!$row['media']
) {
print 'No Media Available';
}
else {
print $row['media'];
}
I put all the contingencies within the if statement because I'm not sure what you have going on in your database. The only thing I think you'll need to change, given the fact that the image is stored as a blob in your database, is instead of printing out the $row['media'] directly, you'd have to parse it and create an image using whatever strategy you see fit for your project.
Using your code above as an example, it would look like this:
if (
$row['media'] == '' ||
$row['media'] == null ||
empty($row['media']) ||
!$row['media']
) {
print 'No Media Available';
}
else {
print '<img src="data:image/jpeg;base64,'. base64_encode($row['media']) .'"/>';
}
Hope this helps!
You can simply add an if statement into the template to check whether the value isn't empty
<?php if(!empty($media)) { ?>
<img src="<?php echo $media ?>">
<?php } ?>

Simple HTML Dom Parse Tables

I want to parse the news from the website which is : http://www.bakirkoykhb.gov.tr/?module=bizden_haberler , what i'm facing is the website has many tables without classes and very complicated and so on as you can see if you check the source code of the page, i get the headings like those ones :
Japonya-Türkiye Tıp Derneği'den Ziyaret
Saglık-Sen Gen. Başk.Memiş'ten Ziyaret
Vali Mutlu’ dan Ziyaret
and so on with my code below. but i don't have any idea that how can i parse the links which are contained under "Devamını Oku".
$html = file_get_html('http://www.bakirkoykhb.gov.tr/?module=bizden_haberler');
$j = 0;
foreach($html->find('b') as $element2){
echo "
<h3 ><a target=\"_blank\" href=\"#somethingtohere\">". $element2->plaintext . "</a></h3>
";
$j++;
if($j > 5) break;
}
Hope you can help, thank you.
This should do for you
echo "<h3 ><a href='http://www.bakirkoykhb.gov.tr/".$html->find('a',$j+22)->href."'>". $element2->plaintext . "</a></h3>";

Insert function name with php

I'm trying to do a simple task, insert a second function name under "onmouseover" but probably something is wrong with the syntax.
echo '<div onmouseover="changeText(); <?php if($title==""){echo changeViz();}; ?> ">';
I probably need to escape some quotes and add some, but i can't figure out the correct solution.
Thanks
Nothing it's working. Let me give you the complete code...:
echo '<div class="frame" onmouseover="changeText(\''.$text[$i].'\'); <?php if($title[$i]==""){echo changeViz();}; ?>">';
You are nesting <?php ?> inside existing php code, which is a syntax error. Instead, concatenate in the javascript function changeViz() as a quoted string.
This version uses a ternary operator to duplicate the if() statement you had originally.
echo '<div onmouseover="changeText(); ' . ($title == '' ? 'changeViz();' : '') . '">';
The ternary operation here will concatenate changeViz(); onto the echo string if $title == "", or otherwise just concatenate on an empty string.
Update after seeing full code:
You have the quote escaping correct in the first part.
echo '<div class="frame" onmouseover="changeText(\'' . $text[$i] . '\'); ' . ($title == '' ? 'changeViz();' : '') . '">';
You can make your code much more readable if you do not try to do everything in one line:
$onmouseover_action = "changeText(); ";
if($title==""){
$onmouseover_action .= "changeViz(); ";
}
echo '<div onmouseover="'.$onmouseover_action.'">';
It makes your code easier to maintain, and you have less need to comment it, because it describes itself quite much better.
Try this:
echo '<div class="frame" onmouseover="changeText(\''.$text[$i].'\'); '. ($title[$i]=="")?'changeViz();':'').'">';

Echo with Shorthand If not behaving properly

I'm programming in PHP, I'm using a 'shorthand if' to echo some HTML code on to the page, but it is behaving in odd ways.
echo '<div id="filter_bar">
<ul>';
echo '<li>Trending</li>' : '>Trending</a></li>';
echo '<li>Most Picked</li>' : '>Most Picked</a></li>';
echo '<li>Newest</li>' : '>Newest</a></li>';
echo '</ul></div>';
The resulting code that I get as a result is this
class="filter_selected">Trending</a></li> class="filter_selected">Most Picked</a></li> class="filter_selected">Newest</a></li>
As you can see, the opening list tags are not showing... but they do if I replace the first period '.' on each line with a ',' comma.
So this works, with the commas
Should I be using a comma here? Everywhere online sheems to show a period '.'
The reason is:
echo '<li>' . true ? 'aaa' : 'bbb'; will give you aaa,
because it is same with '<li>1' ? 'aaa' : 'bbb'
And you should do like this:
echo '<li>' . (true ? 'aaa' : 'bbb');
Maybe you can make your life a bit easier:
echo '<div id="filter_bar"><ul>',
'<li>' : '>', 'Trending</li>',
'<li>' : '>', 'Most Picked</li>',
'<li>' : '>', 'Newest</li>',
'</ul></div>';
Which will use commas (no need to repeat echo that much) and you don't need to repeat strings that much if you only want to insert the class attribute.
Then you made use of parenthesis where they were not needed (see Operator Precedence Docs) but at the place where those are needed, you didn't use them (the last case).
Additionally it's better to fill those values to variables upfront, so you can debug stuff easier (and you don't mix $_GET with output, so to prevent mixing output logic with input variables).
That done you could have learned that your issue is not within the echo but just the expression you've formulated with the ternary operator.
$class_trending = $_GET['select'] == "trending" ? ' class="filter_selected"' : '';
$class_most_picked = $_GET['select'] == "most_picked" ? ' class="filter_selected"' : '';
$class_newest = ($_GET['select'] == "newest") || empty($_GET['select']) ? ' class="filter_selected"' : '';
echo '<div id="filter_bar"><ul>',
'<li><a href="?select=trending"', $class_trending, '>Trending</a></li>',
'<li><a href="?select=most_picked"', $class_most_picked, '>Most Picked</a></li>',
'<li><a href="?select=newest"',$class_newest , '>Newest</a></li>',
'</ul></div>';
dunno your problem but this code looks an ugly mess for me.
I'd make it this way:
in the PHP code I'd prepare variables first.
$sections = array(
'newest' => 'Newest',
'trending' => 'Trending',
'most_picked' => 'Most Picked',
);
if (empty($_GET['select']) OR !$choice = array_search($sections,$_GET['select'])) {
$choice = 'newest';
}
and then in the template run smooth and short loop:
<div id="filter_bar">
<ul>
<? foreach ($sections as $sect => $name): ?>
<li>
<a href="?select=<?=$sect?><? if ($choice == $sect) ?>" class="filter_selected"<? endif ?>><?=$name?></a>
</li>
<? endforeach ?>
</ul>
</div>
One possible solution is
echo "<li><a href='?select=newest'";
echo ($_GET['select'] == "newest" || empty($_GET['select'])) ? ' class="filter_selected">Newest</a></li>' : '>Newest</a></li>';
Change your parentheses to the following:
echo '<div id="filter_bar">
<ul>';
echo '<li>Trending</li>' : '>Trending</a></li>');
echo '<li>Most Picked</li>' : '>Most Picked</a></li>');
echo '<li>Newest</li>' : '>Newest</a></li>');
echo '</ul></div>';
If you do not do this, PHP does not know what exactly your condition is. Also have a look at operator precendence as this explains why it works using commas.
By the way: The ?: is called ternary operator.

Categories