Is there a better way to write this php code? - php

return'
<li>
<img class="avatar" src="images/' . $picture . '" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>' . $username . '</strong> '. autolink($tweet).'
<div class="date">'.relativeTime($dt).'</div><div class="date">'. $reply_info . '</div> <a class ="reply" href="home.php?replyto=#'. $username .'&status_id='. $id .'&reply_name=' .$username.'"> reply </a>
</div>
<div class="clear"></div>
</li>';
I was wondering if there is a cleaner way to write this code, and taking in mind processing time, if that really means anything.
p.s. this code is part of a function, this is the return statement!

Yes. Use double quotes for the PHP string (and single quotes for the HTML attributes), then you can just use PHP variables in the string, like so:
"<a href='nano.com/$username'>";
Is processing time really an issue? I doubt it, but profile to be sure.
Edit: If anyone is unsure about using single quotes in HTML attributes, have a look at this question. It's pretty unanimously agreed that single quotes are fine. If anyone can give a decent counter-argument I'd be happy to hear it.

You could use HEREDOC syntax :
$auto = autolink($tweet);
$rel = relativeTime($dt);
return <<<ENDOFRETURN
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div><div class="date">$reply_info</div> <a class ="reply" href="home.php?replyto=#$username&status_id=$id&reply_name=$username"> reply </a>
</div>
<div class="clear"></div>
</li>
ENDOFRETURN;

Cleaner template and php code -> use MVC

Yes, there is one, and you don't need MVC (only a template):
<li>
<a href="nano.com/<?=$username ?>">
<img class="avatar" src="images/<?=$picture ?>" width="48" height="48" alt="avatar" />
</a>
<div class="tweetTxt">
<strong><?=$username ?></strong>
<? echo autolink($tweet) ?>
<div class="date"><?=relativeTime($dt) ?></div>
<div class="date"><?=$reply_info ?></div>
<a class="reply" href="home.php?replyto=#<?=$username?>&status_id=<?=$id?>&reply_name=<?=$username?>">
reply
</a>
</div>
<div class="clear"></div>
</li>
Must read: http://wiki.yet-another-project.com/php/the_one_single_step_for_a_cleaner_code . It describes how you have to use the code above.

I would cut in several pieces and use sprintf() to tie it all together.

You can use a template engine i.e. smarty, twig, ...

Related

Php isset inside an echo validation

Hi I want to check the following validation:
echo '<div id="msg"><?php echo isset($msg)?$msg:''; ?></div>';
I know that is wrong, what is the correct way to do that?
You're already within the PHP realm, you're running PHP.. you can't start another PHP. Also single quote ' wont expand variables.
I'm running on a lot of assumptions from your project
Using your logic you could do this:
echo '<div id="msg">' . (isset($msg) ? $msg : '') . '</div>';
but it would be best to not just output the div when the variable isn't set
if(isset($msg)) {
echo "<div id=\"msg\">$msg</div>";
}
More info on what you're trying to achieve would let me educate you more on best practices.
Your edit suggestion still has you trying to start a new php block within a php
block.
You suggested to edit my answer (which was weird) with this:
echo '<div class="container">
<form action="includes/ajax.php" id="profilePictureUpload" class="dropzone">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
<h1>Gallery</h1>
<div class="alert alert-warning my-2">
<i class="fa fa-2x fa-exclamation-circle float-right"></i>
<ol class="m-0">
<li>Image uploading limit is 5.</li>
<li>One image not more then 5MB.</li>
</ol>
</div>
<div id="msg"><?php echo isset($msg)?$msg:''; ?></div>
</div>';
If you had read what i posted, you need to replace that 1 <div id="msg"... with what i posted. Did you check?

Unable to Display Images from MySQL

I am unable to display images from MySQL. I've checked path etc. but still there are broken images on site. Below is my Code. Please guide me.
<div id="right_content">
<div id="headline">
<div id="headline_content"> <b>Welcome Guest!</b> <b style="color:#F56013">Shopping Cart</b> <span>-Items: -Price: </span> </div>
</div>
<div id="products_box">
<?php
$get_products ="SELECT * FROM products ORDER BY rand() LIMIT 0,6";
$run_products = mysqli_query($con,$get_products);
while($row_products=mysqli_fetch_array($run_products)){
$prod_id = $row_products['product_ID'];
$prod_title = $row_products['product_title'];
$prod_cat = $row_products['category_ID'];
$prod_brand = $row_products['brand_ID'];
$prod_price = $row_products['product_price'];
$prod_desc = $row_products['product_desc'];
$prod_img =$row_products['product_img1'];
echo "
<div id='single_product'>
<h3>$prod_title</h3>
<img src='admin_area/product_images/$prod_img' width='180' height='180' />
</div>
";
}
?>
</div>
As per comment, problem is solved. The images were not moving into the directory and i didn't check that. When i manually copied them into the specified directory the problem was gone.
When you write html please note that you should always use double and not single quotes for tag properties. So for example
src='admin_area/product_images/$prod_img'
should be
src="admin_area/product_images/$prod_img"
and so on. Since you are doing echo using double quotes you should escape double quotes with .
So your echo should look like:
echo "
<div id=\"single_product\">
<h3>$prod_title</h3>
<img src=\"admin_area/product_images/$prod_img\" width=\"180\" height=\"180\" />
</div>
";
IMHO it is better to write plain html and use php only to echo variables just to avoid this kind of problems with the generated code. So I'd write:
?>
<div id="single_product">
<h3><?php echo $prod_title; ?></h3>
<img src="admin_area/product_images/<?php echo $prod_img; ?>" width=\"180\" height=\"180\" />
</div>
<?php } ?>
This will save you a lot of headache in case of debugging if your code is not working

Avoid showing icons that don't contain a value

I've already been searching for a couple of hours for a solution. What I want to do is make icons that don't got a value (in the php) not show up.
Here's an image of what I currently have.
So for instance if only twitter and facebook got values, they should only appear on the screen.
Below is the code, and I hope someone got a solution for this.
Cheers!
<ul class="social-buttons">
<div class="wrapping">
<a class="social" href="http://twitter.com/<?php echo $profile_data['twitter']; ?>" target="_blank"><li class="twitter"></li></a>
<a class="social" href="http://facebook.com/<?php echo $profile_data['facebook']; ?>" target="_blank"><li class="facebook"></li></a>
<a class="social" href="skype:<?php echo $profile_data['skype']; ?>?chat"><li class="skype"></li></a>
<a class="social" href="http://instagram.com/<?php echo $profile_data['instagram']; ?>"><li class="instagram"></li></a>
<a class="social" href="http://dribbble.com/<?php echo $profile_data['dribbble']; ?>"><li class="dribbble"></li></a>
<a class="social" href="http://linkedin.com/in/<?php echo $profile_data['linkedin']; ?>"><li class="linkedin"></li></a>
</div>
</ul>
You need to use the if statement with !empty(). The !empty() checks if a variable is NOT empty. Than proceed with the code. Like the example given here:
<?php
if(!empty($profile_data['twitter'])){
?>
<a class="social" href="http://twitter.com/<?php echo $profile_data['twitter']; ?>" target="_blank"><li class="twitter"></li></a>
<?php
}
?>
If the variable is empty, it wont give the outputed code, in your case the <a> with the icon.
i think you can do like:
<ul class="social-buttons">
<div class="wrapping">
<?php if $profile_data['twitter'] {?>
<a class="social" href="http://twitter.com/<?php echo $profile_data['twitter']; ?>" target="_blank"><li class="twitter"></li></a>
<?php } ?>
....
</ul>
Imo, a probably better way to do this is to perform a pre-processing of the data i.e. $profile_data, before you use it in your view so the view would no longer need to handle the processing logic. After which, the view can output your links by using a more concise construct e.g. for loop, that does not use any conditional branching.

Use 'variables' in HTML?

Insead of having to alter values for every item in the list as so
<li class="item drawing">
<a class="fancybox" rel="group" href="images/portfolio/skateboard_l.jpg">
<img src="images/portfolio/skateboard.jpg" alt="skateboard"/>
<h3>Skateboard</h3>
</a>
</li>
Is it possible to have something like
item="Skateboard
<li class="item drawing">
<a class="fancybox" rel="group" href="images/portfolio/[item-lowercase][if "item"_l.jpg exists, echo"_l"].jpg">
<img src="images/portfolio/[item-lowercase].jpg" alt="[item-lowercase]"/>
<h3>[item]</h3>
</a>
</li>
So I can just change the item variable for each item in the list rather than all the seperate entries. I assume this would be done using PHP or JS?
Thanks.
You want to use templates I guess.
If you want to do it client side in JS:
underscore
Mustache.js
Handlebars.js
The best solution that I can think of is to build an array (I would use PHP)... then use a while loop to build your list... put it all in a function and call it wherever you need it...
For example:
<?php
function itemList(){
$items=array ("skateboard","rollerskates","scooter","rollerblades");
reset($items);
while (list(, $value) = each($items)) {
echo '<li class="item drawing">';
echo '<a class="fancybox" rel="group" href="images/portfolio/' . $value . '_l.jpg">';
echo '<img src="images/portfolio/' . $value . '.jpg" alt="' . $value . '"/>';
echo '<h3>' . $value . '</h3>'; echo '</a>';
echo '</li>';
}
}
?>
Then in your HTML file (where you want the list to be displayed):
<ul><?php itemList(); ?></ul>
If you put the function in a separate .php file, you have to include it in the HTML document:
<?php include ('/url/of/list.php'); ?>
You can do this in PHP using echo.
For instance, if the image name was stored in $images["myImage"] and the alt was $imageAlts["myImage"
<img src="images/portfolio/<?php echo $images["myImage"]; ?>.jpg" alt="<?php echo $imageAlts["myImage"]; ?>"/>
Looks like AngularJS would help as well. It lets you do stuff like this:
<!doctype html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>
Smarty is a good template system for PHP. If you'd like to use PHP for templating over JavaScript, just start with one of the tutorials there (or look into other PHP template systems).
A classic way to do this in PHP would be to create an array of items in PHP and then iterate over the array, creating the HTML list items with the appropriate [item-lowercase] entries.
I would consider doing the [if item exists] as part of the process that builds your data array so you don't have to do anything complicated when you build your html. Then, just loop through your array and display whatever is in $theItem.
This is, of course, a simplification.
foreach($itemList as $key=>$theItem){
?>
<li class="item drawing">
<a class="fancybox" rel="group" href="images/portfolio/<?php echo $theItem ?>
<img src="images/portfolio/[item-lowercase].jpg" alt="[item-lowercase]"/>
<h3>[item]</h3>
</a>
</li>
<?php
}

Displaying an <img> tag inside a div class

I have a problem here that deals with the displaying of a photo inside a variable within a div class.
Here's my code below and help me find solutions. Thanks
if($newimage){
$url = 'http://www.client.jaobuilders.com/uploads/profile_picture/upload_photos/$newimage';
} else {
$url = 'http://www.client.jaobuilders.com/images/blank_photo.jpg';
}
return '
<div class="comment">
<div class="avatar">
'.$link_open.'
<img src="'.$url.'" width="50px" height="50px"/>
'.$link_close.'
</div>
$newimage is a variable and the value will depend on the user who logged in.
I really don't know what to do. Help me.
You have a problem with quotes - some of them are lacking. Also you did not close <div> tag:
return '
<div class="comment">
<div class="avatar">
'.$link_open.'
<img src="'.$url.'" width="50px" height="50px"/>
'.$link_close.'
</div>
</div>';
I can only hope this return statement is enclosed in some kind of function or method. Or at least it is the only return statement in a file that has been properly included somewhere (like $my_divs = include('some_file.php');).

Categories