Display and check for multiple key in php echo - php

I am trying to output a key value from JSON data and want to check for multiple keys.
I want to display the title of a movie and or tv show.
if($channel=="multi" AND !empty($movies)){
foreach ($movies as $movie) {
if(!empty($movie['poster_path'])){
echo '<div class="mov">
<a href="'.$movie['media_type'].'/'.$movie['id'].'">
<img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
<h2 class="title">'.$movie['title'].'</h2>
</a>
</div>';
}
}
}
whereas <h2 class="title">'.$movie['title'].'</h2> also needs to check for <h2 class="title">'.$movie['name'].'</h2>
How can I check for both 'title' and 'name' in the same go?
I am pretty new to all this and learning on the go. So please correct me as well if there are any mistakes in my coding!

If you're trying to get $movie['title'] or $movie['name'] (because you're unsure what the variable will be called) you can use an if statement. (This is not a pretty way of writing it -- but it is the clearest way).
if($channel=="multi" AND !empty($movies)){
foreach ($movies as $movie) {
if(!empty($movie['poster_path'])){
echo '<div class="mov">
<a href="'.$movie['media_type'].'/'.$movie['id'].'">
<img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
<h2 class="title">';
//AN IF STATEMENT TO CHOOSE EITHER TITLE OR MOVIE
if(!empty($movie['title']) {
echo $movie['title'];
} else {
echo $movie['name'];
}
echo .'</h2>
</a>
</div>';
}
}
}
Alternatively, you could also make $movie['title'] equal to $movie['name'] if it is not blank.
if($channel=="multi" AND !empty($movies)){
foreach ($movies as $movie) {
if(!empty($movie['poster_path'])){
// MAKE MOVIE TITLE = MOVIE NAME IF IT IS NOT BLANK
if(!empty($movie['name'])){
$movie['title'] = $movie['name'];
}
echo '<div class="mov">
<a href="'.$movie['media_type'].'/'.$movie['id'].'">
<img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
<h2 class="title">'.
$movie['title'].
'</h2>
</a>
</div>';
}
}
}
There are usually many ways to solve a problem. Think through the logic. If this than that. If not this, than that instead.

Related

How to display images in a heredoc in codeIgniter

Hi i wanted to know how i want to know how i would write the image tag and access the string to get the image out of the database. When i refresh my page it only shows the title that i have got out of the database and not the image i want to know how i can get the image out of the database in the heredoc.
In my database i have a string for example Images/pokemon.png
<?php
foreach ($result as $row) {
echo <<<_END
<h4 class="card-title mt-5"> $row->title</h4>
<img src="<?php echo base_url('application/' . $row->image)?>" alt=""/>
_END;
}
?>
The closing identifier must not be indented, so it should look like this.
<?php
foreach ($result as $row) {
echo <<<_END
<h4 class="card-title mt-5"> $row->title</h4>
<img src="<?php echo base_url('application/' . $row->image)?>" alt=""/>
_END;
}
?>
For reference

Don't repeat values in loop

I've the following query
As you see jigsaw repeats twice because the movie has two categories
but i would like to echo both categories but not twice the movie..
<?php
while ($mInfo = $testquery->fetch(PDO::FETCH_ASSOC)) {
?>
<div class="col-xs-6 col-sm-4 col-md-3">
<a href="movie.php?title=<?php echo $mInfo['titleEN']; ?>&m=<?php echo $mInfo['imdbID']; ?>" title="<?php echo $mInfo['titleEN']; ?>" alt="<?php echo $mInfo['titleEN']; ?>" target="_self">
<div class="movie-info">
<img src="assets/images/poster/<?php echo $mInfo['poster']; ?>.jpg" alt="<?php echo $mInfo['titleEN']; ?>">
</div>
<div class="movieinformation">
<div class="movie-title"><?php echo $mInfo['titleEN']; ?></div>
<div class="movie-categories">I WOULD LIKE TO ECHO THE CATEGORIES HERE</div>
</div>
</a>
</div>
<?php
}
?>
So far i just could do it, could anyone help me with that?
Here's a concept for such tasks. I kept it with general names and left out html on purpose.
$oldMainId = null; // Initialize to null to start with. This will be needed later.
while ($item = $result->fetch()) { // get your items (movies in your case)
if($oldMain != $item['mainId']) {
// only show title if you haven't yet
echo $item['mainTitle'];
}
// always show the category though
echo $item['sub'];
// re-set the 'old' variable.
$oldMainId = $item['mainId'];
}
I would use
OPTION 1
$res = $stmt->fetchAll(PDO::FETCH_GROUP);
Then it will group on the first column, assuming that is movie ID, or something unique to the movie you would get multiple rows in a nested array for that movie.
Then when you iterate thorough them you can loop over the nested array for the genre stuff
OPTION 2
Another option is to use GROUP_CONCAT and group by the movie id,
SELECT GROUP_CONCAT(genre) AS genre, ... WHERE ... GROUP BY movieID
But be aware that GROUP_CONCAT does have a setting for max length and it will silently truncate your data if it exceeds it.
OPTION 3
You can build the structure yourself (same as fetch group does)
$data = [];
while ($mInfo = $testquery->fetch(PDO::FETCH_ASSOC)) {
$key = $mInfo['movieid']
if(!isset($data[$key])) $data[$key] = [];
$data[$key][] = $mInfo;
}
Then go through that and do your html by using a second foreach($data as ...) It has to be done after organizing the data as the order of the result is unknown.

what is wrong with this piece of code? html + php

i've a simple function, which has two parameters, one for the image url, and other for the attributes for the image
function image_found($url,$attributes)
{
if(#getimagesize($url))
{
echo '<img src="'.$url.'" '.$attributes.'/>';
}
else
{
echo '<img src="'.base_url().'/site_images/image_not_found.svg" '.$attributes.'/>';
}
}
now what i'm trying to do is create a clickable image, if the image is found, now this is the html code
echo '<div class="panel-body">';
echo '<div class="col-md-12 col-lg-12 col-sm-12 text-center">';
$url = base_url().'product_images/'.$result->product_image.'.'.$result->image_type;
$attributes = 'height="200px" width="100%"';
echo ''.image_found($url,$attributes).'';
echo '</div>';
echo '</div>';
and this is the output i'm getting
<div class="panel-body">
<div class="col-md-12 col-lg-12 col-sm-12 text-center">
<img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/>
</div>
</div>
i don't know what is wrong here, i'm using bootstrap
Just use return statements instead of echo in your function and your problem should be solved ;-)
The better way is verify if your image exists (remove #) and then return (instead of echo):
...
if(file_exists('your/path/to/image'))
return '<img src="'.$url.'" '.$attributes.'/>';
else
return '<img src="'.base_url().'/site_images/image_not_found.svg" '.$attributes.'/>'
...
When you need to return a value from a function, use return statement instead of echo
When echo is used the output immediately gets printed instead of getting returned to the place where the function call is. Here is an illustration.
function printer(){
echo 'second';
}
echo 'first'.' '.printer().' '.'last';
The Output:
secondfirst last
This is the exact same thing happening with your code. The echo in image_found() gets printed as
<img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/>
The rest of the echo statement gets printed as
So using a return statement should solve your problem

PHP Code is printing text not typed code

I have created a homepage editor tool in a script I purchased. The function of this homepage editor is to allow me to create different sections and display them one on top of the other in the order they are created. Which in hopes will give me an effect of several blocks that stretch width of the screen.
All seems to work well except one piece. I input my html and php code into the field in the admin panel and it saves to the db as I wrote it. However, when I go to echo each section back to the homepage it just displays my php code as plain text and doesn't interpret it as php and do its function.
Here is code from the homepage.php that prints the results.
<?php
session_start();
require_once("inc/config.inc.php");
if (isset($_GET['ref']) && is_numeric($_GET['ref']))
{
$ref_id = (int)$_GET['ref'];
setReferal($ref_id);
header("Location: index.php");
exit();
}
/////////////// Page config ///////////////
function get_all_section($section_id='')
{
$sql="SELECT * FROM `cashbackengine_homepage` WHERE 1";
if($section_id!="")
{
$sql.=" AND section_id='".$section_id."'";
}
$sql.=" AND section_status=1";
$sql.=" ORDER BY section_order ASC";
//echo $sql;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$section_array[]=array(
'section_id' =>$row['section_id'],
'section_name' =>$row['section_name'],
'section_desc' =>$row['section_desc'],
'section_order' =>$row['section_order'],
'section_status' =>$row['section_status'],
'last_updated' =>$row['last_updated'],
);
}
return $section_array;
}
$get_all_section=get_all_section('');
/*$get_all_section2=get_all_section('2');
$get_all_section3=get_all_section('3');
$get_all_section4=get_all_section('4');
$get_all_section5=get_all_section('5');*/
for($i=0; $i<count($get_all_section);$i++)
{
//echo htmlspecialchars_decode($get_all_section[$i]['section_desc']);
//echo htmlspecialchars_decode(stripslashes(str_replace(" ","",(str_replace("<br />","\n",$get_all_section[$i]['section_desc'])))));
echo $get_all_section[$i]['section_desc'];
}
?>
I am certain the problem has to do with the echo at the end. But I am unsure how to use htmlspecialchars to make it work with php if it even will. Or if I have to put something weird in my saved section.
Here is one of my sections. Any help is greatly appreciated. Thank you.
<div style="height:260px; width:100%; background-color:#000; margin:0px; color:white;">
<div id="header">
<div id="logo"><img src="<?php echo SITE_URL; ?>images/logo.png" alt="<?php echo SITE_TITLE; ?>" title="<?php echo SITE_TITLE; ?>" border="0" /></div>
<div class="start_saving">
<div id="links">
<?php if (MULTILINGUAL == 1 && count($languages) > 0) { ?>
<div id="languages">
<?php foreach ($languages AS $language_code => $language) { ?>
<img src="<?php echo SITE_URL; ?>images/flags/<?php echo $language_code; ?>.png" alt="<?php echo $language; ?>" border="0" />
<?php } ?>
</div>
<?php } ?>
<div id="welcome">
<?php if (isLoggedIn()) { ?>
<?php echo CBE_WELCOME; ?>, <span class="member"><?php echo $_SESSION['FirstName']; ?></span><!-- | <?php echo CBE_ACCOUNT ?>--> | <?php echo CBE_BALANCE; ?>: <span class="mbalance"><?php echo GetUserBalance($_SESSION['userid']); ?></span> | <?php echo CBE_REFERRALS; ?>: <span class="referrals"><?php echo GetReferralsTotal($_SESSION['userid']); ?></span>
<?php }else{ ?>
<a class="signup" href="<?php echo SITE_URL; ?>signup.php"><?php echo CBE_SIGNUP; ?></a> <a class="login" href="<?php echo SITE_URL; ?>login.php"><?php echo CBE_LOGIN; ?></a>
<?php } ?>
</div>
</div></div>
</div>
It looks like you're getting these section contents pieces out of your database, and not from a file stored on your web server. Is that correct?
Assuming that's true, then my next question would be, who populates this data? Is this taken in any way from user input? The reason why I ask is because of my next suggestion, which may or may not be received well.
The reason why your PHP code isn't executing, is because it's being retrieved from the database and output as a string, not as code. So how do you execute code that's stored in a string, you ask? Well, the answer to that question is to use eval() on the string. But this is where you have to be really careful!!!!!!! If any part of that string could have possibly come from an untrusted source, then malicious PHP code could be executed, which could potentially give evildoers a way into your server, where they can find all the information in your database, server, etc. Make sure you know where your code is coming from before executing it!
You make a good point that it's HTML mixed with PHP. So I see two possible solutions...
This post suggests that you could do eval(' ?>'. $section .' <?php'); This makes sense, you're breaking out of PHP before you eval your string, and so requiring the included string to open its own PHP tags to write PHP code.
Another way I can think of would be to throw the contents into a temporary file, and then include() that file:
// get contents, store in $contents
$filename = tempnam(sys_get_temp_dir(), 'section');
file_put_contents($filename, $section);
include($filename);
unlink($filename);

Show first 5 items in list, hide/toggle display of others (PHP)

I'd like to show the first 5 names in a list and toggle the display of any additional names as a single block.
I've currently got the names list as an array object though I'm happy to change it to an array if the solution would be simpler with that.
Here's what I have so far which is *in*complete because I don't know how to create the hidden div of names:
PHP
$names_count=0;
echo '<div id='nameList' class='toggler'>';
foreach($names as $name){
echo '<a id='name'.$name->acct_id.'>'.$name->full_name.'</a>';
if($names_count<=4){
echo '</div><!--toggler div-->';
}
else
<div class='namesList' style='display:none'>
//put additional names in hidden div?
</div>
}
$names_count++;
} //endforeach
JS:
UPDATE Sorry for the confusion. This isn't really a javascript question so I deleted that tag but I'm including the following jQuery code snippet for completeness with the PHP
$('.toggler').click(function(){
var id=this.id;
$('#'+id).toggle();
});
PHP
$names_count = 0;
echo '<div id="nameList" class="toggler">';
foreach($names as $name) {
echo '<a id="name' . $name->acct_id . '">' . $name->full_name . '</a>';
if ($names_count == 4) {
echo '</div><div class="hidden">';
}
$names_count++;
}
echo '</div>';
JS
$('.toggler').click(function(){
$(this).next().toggle();
});
CSS
.hidden {
display: none;
}
Here's an example with two while loops.
$names = array('Bob', 'Andy', 'Tim', 'Max', 'Roger', 'John', 'Test');
$nameCount = count($names);
$nameIndex = 0;
echo '<div id="nameList" class="toggler">';
// Show the first 5 names.
while ($nameIndex < min(5, $nameCount)) {
$name = $names[$nameIndex++];
echo '<a id="name' . $name . '">' . $name . '</a>';
}
// Show the remaining names in a hidden div.
if ($nameIndex < $nameCount)
{
echo '<div class="hiddenNames" style="display:none">';
while ($nameIndex < $nameCount) {
$name = $names[$nameIndex++];
echo '<a id="name' . $name . '">' . $name . '</a>';
}
echo '</div>';
}
echo "</div>";
That code produces the following output.
<div id="nameList" class="toggler">
<a id="nameBob">Bob</a>
<a id="nameAndy">Andy</a>
<a id="nameTim">Tim</a>
<a id="nameMax">Max</a>
<a id="nameRoger">Roger</a>
<div class="hiddenNames" style="display:none">
<a id="nameJohn">John</a>
<a id="nameTest">Test</a>
</div>
</div>
It also safe if you have less than 5 names; the script would produce :
<div id="nameList" class="toggler">
<a id="nameBob">Bob</a>
<a id="nameAndy">Andy</a>
<a id="nameTim">Tim</a>
</div>
For the JS, I would probably do something along the lines of :
$('.toggler').click(function(){
$('.hiddenNames').toggle();
});
Even if the code is a bigger, I find it easier to follow and probably easier to maintain in the long run. (Opinion)
Hope this helps!
To make a <div> hidden:
<div style="display: hidden"></div>
Then the jQuery should make it visible with the .toggle() command.

Categories