I'm trying to pass variables in an include that appears on a page multiple times. While the following sample may technically work, I'm sure there is a much better way of doing this. Any help would be appreciated.
index.php
<?php
$user_avatar = "user-1-avatar.jpg";
$user_username = "username-1";
$user_name = "User 1";
include '/_user-card.php';
?>
<?php
$user_avatar = "user-2-avatar.jpg";
$user_username = "username-2";
$user_name = "User 2";
include '/_user-card.php';
?>
_user-card.php
<div class="user-card">
<img src="<?php echo $user_avatar; ?>" alt="">
<p class="user-card__username"><?php echo $user_username; ?></p>
<p class="user-card__name"><?php echo $user_name; ?></p>
</div>
You can create data that you can use over and over again by using the following function.
function get_user_card($params = array()){
$output = '';
extract($params);
if( isset($user_avatar) && isset($user_username) && isset($user_name) ) {
ob_start();
?>
<div class="user-card">
<img src="<?php echo $user_avatar; ?>" alt="">
<p class="user-card__username"><?php echo $user_username; ?></p>
<p class="user-card__name"><?php echo $user_name; ?></p>
</div>
<?php
$output = ob_get_contents();
ob_end_clean();
}
return $output;
}
$user_1 = get_user_card(
array(
"user_avatar" => "user-1-avatar.jpg",
"user_username" => "username-1",
"user_name" => "User 1"
)
);
echo $user_1;
Related
I didn't build this PHP file, but I am trying to figure out why it is giving me errors. If the "Block layout mode" ACF variable is set to "Modal" then the block works, but gives me this error. "Undefined variable $vids on line 176". If I select the "Embed & Thumbnail" mode, then none of the block is displayed and I get this error. "Call to undefined function vc_embed_layout() on line 252". I can't pin down why this is happening, and I haven't been able to find any unclosed tags or anything in my php file. This is the file in question, and I've marked the lines that trigger errors.
<?php
global $theme_text_domain;
$block_class_identifier = 'blk__vidcol';
// default variables
$block_id = $top_class = $top_style = $inner_class = $inner_style = '';
// check for custom id
$block_id .= BLOCK::set_id( get_sub_field('content_block_id') );
// set block class, $i comes from FLEX class loop and represents the block order on a page
$top_class .= BLOCK::set_standard_classes( $i );
$top_class .= BLOCK::set_custom_classes( get_sub_field('content_block_classes') );
// check for top padding adjustment
$top_class .= BLOCK::set_padding_class( get_sub_field('block_padding_adjustment') );
$top_style .= BLOCK::set_padding_style( get_sub_field('block_padding_adjustment'), get_sub_field('custom_top_padding'), get_sub_field('custom_bottom_padding'));
// check for custom color theme
$top_style .= BLOCK::set_colors( get_sub_field('color_theme'), get_sub_field('text_color'), get_sub_field('custom_background_color') );
// check for width settings
$inner_class .= BLOCK::set_width_class( get_sub_field('content_width') );
$inner_style .= BLOCK::set_width_style( get_sub_field('content_width'), get_sub_field('custom_maximum_content_width') );
$block_assets = get_stylesheet_directory_uri() . '/inc/blocks/' . basename(__FILE__, '.php') . '/assets/';
/*
CUSTOM BLOCK SPECIFIC SETUP
*/
$layout = get_sub_field('block_layout_mode');
$top_class .= ' layout-' . $layout;
// title color
$h2_style = (get_sub_field('color_theme') == 'custom') ? ' color: ' . get_sub_field('custom_title_color') . ';' : '';
/**
* outputs code for the modal version of the video collection block
* #return html output
*/
if (!function_exists('vc_modal_layout')) {
function vc_modal_layout() {
global $block_class_identifier;
$cta_label = get_sub_field('cta_label');
$counter = 0;
$cta = array(
'style' => get_sub_field('cta_style'),
'button_color' => get_sub_field('button_color'),
'button_text_color' => get_sub_field('button_color')
);
$cta_class = BLOCK::get_cta_style( $cta, '.' . $block_class_identifier . ' .button');
?>
<?php // list section ?>
<?php if( have_rows('videos') ): ?>
<div class="vid-container">
<?php while ( have_rows('videos') ) : the_row(); ?>
<?php if ($counter == 0): ?>
<div class="vid-featured">
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/<?php echo get_sub_field('youtube_embed_code'); ?>?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
<a class="vid_overlay" data-fancybox data-src="#<?php echo $block_class_identifier; ?>_vid_0" href="javascript:;"></a>
</div>
<!-- modal -->
<div id="<?php echo $block_class_identifier; ?>_vid_0" class="modal video-modal" style="display: none;">
<div class="modal-inner">
<h3><?php echo get_sub_field('video_title'); ?></h3>
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/<?php echo get_sub_field('youtube_embed_code'); ?>?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<div class="vid-list">
<?php else: ?>
<div class="vid-item">
<div class="item-btn">
<a class="button <?php echo $cta_class; ?>" data-fancybox data-src="#<?php echo $block_class_identifier; ?>_vid_<?php echo $counter; ?>" href="javascript:;"><?php echo $cta_label; ?></a>
</div>
<div class="item-title"><?php echo get_sub_field('video_title'); ?></div>
</div>
<!-- modal -->
<div id="<?php echo $block_class_identifier; ?>_vid_<?php echo $counter; ?>" class="modal video-modal" style="display: none;">
<div class="modal-inner">
<h3><?php echo get_sub_field('video_title'); ?></h3>
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/<?php echo get_sub_field('youtube_embed_code'); ?>?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
<?php endif; ?>
<?php $counter++; ?>
<?php endwhile; ?>
</div>
</div>
<?php else: ?>
No videos defined.
<?php endif; ?>
<?
}
}
/**
* outputs code for the embed version of the video collection block
* #return html output
*/
if (!function_exists('vc_embed_layout')) {
function vc_embed_layout($vids, $i) {
?>
<?php if ( $vids ): ?> **this is line 176**
<div class="vid-container2">
<h2 class="vid-title"><?php echo $vids[0]['video_title']; ?></h2>
<div class="vid-container2-inner">
<div class="vid-embed">
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/<?php echo $vids[0]['youtube_embed_code']; ?>?rel=0&showinfo=0" frameborder="0" allowfullscreen onload="this.style.visibility = 'visible';"></iframe>
</div>
</div>
<div class="vid-thumbnails">
<?php foreach ($vids as $key => $vid): ?>
<?php $wrap_class = ($key == 0) ? ' tn-hide' : ''; ?>
<div class="tn-wrapper <?php echo $wrap_class; ?>" data-embed="<?php echo $vid['youtube_embed_code']; ?>" data-title="<?php echo $vid['video_title']; ?>">
<img src="https://img.youtube.com/vi/<?php echo $vid['youtube_embed_code']; ?>/mqdefault.jpg" alt="">
</div>
<?php endforeach; ?>
</div>
</div>
<script>
var vid_swap = function() {
$('.block_<?php echo $i; ?> .vid-embed').css({opacity: 1});
$('.block_<?php echo $i; ?> .tn-wrapper').on('click', function(e) {
var $this = $(this);
var embed_id = $this.attr('data-embed');
var title = $this.attr('data-title');
console.log('embed = ' + embed_id);
$('.block_<?php echo $i; ?> .vid-title').animate({opacity: 0}, 100);
$('.block_<?php echo $i; ?> .vid-embed').animate({opacity: 0}, 1000, function() {
$('.block_<?php echo $i; ?> .vid-embed, .block_<?php echo $i; ?> .vid-title').css('visiblity','hidden');
$('.block_<?php echo $i; ?> .vid-title').html( title );
$('.block_<?php echo $i; ?> .vid-embed iframe').attr('src', 'https://www.youtube.com/embed/' + embed_id);
$('.block_<?php echo $i; ?> .tn-wrapper.tn-hide').removeClass('tn-hide');
$this.addClass('tn-hide');
$('.block_<?php echo $i; ?> .vid-title').css('visiblity','visible').delay(500).animate({opacity: 1}, 500);
$('.block_<?php echo $i; ?> .vid-embed').delay(500).animate({opacity: 1}, 1000);
});
});
}
jQuery(document).on('block_init', vid_swap);
</script>
</div>
<?php else: ?>
No videos defined.
<?php endif; ?>
<?php
}
}
?>
<section id="<?php echo $block_id; ?>" class="<?php echo $block_class_identifier; ?> <?php echo $top_class; ?>" style="<?php echo $top_style; ?>">
<div class="inner <?php echo $inner_class; ?>" style="<?php echo $inner_style; ?>">
<?php // title section ?>
<?php if (get_sub_field('title')): ?>
<h2 style="<?php echo $h2_style; ?>"><?php echo get_sub_field('title'); ?></h2>
<?php endif; ?>
<?php $vids = get_sub_field('videos'); ?>
<?php if ($layout == 'modal') vc_modal_layout($vids); ?>
<?php if ($layout == 'embed') vc_embed_layout($vids, $i); ?> **This is line 252**
</div>
</section>
You're not accepting any arguments in vc_modal_layout() function declaration.
if (!function_exists('vc_embed_layout')) {
function vc_embed_layout() {
needs to have parameters in order to accept arguments.
something like this is what you're looking for:
if (!function_exists('vc_embed_layout')) {
function vc_embed_layout($vids=[], $i=0) {
And it's the same idea with vc_modal_layout, the function needs to be able to accept the variables from outside it.
When we call a function, the function needs to be able to accept all arguments passed to it. And all variables we use need to be defined, if there's a risk of them being undefined or empty arrays, we can check them with if(!empty($var)) or if(isset($var))
An alternative to passing the variable to the function is to access it as a global. But it's generally better to pass the variable to the function because when we pass the variable to a function in PHP it works with a copy of the variable's value inside the function. When we do something like this:
$var = 10;
function doIt(){
global $var;
$var++;
}
doit();
echo $var;
we could overcomplicate things..
let's have a closer look here:
if ($layout == 'modal') vc_modal_layout($vids);
if ($layout == 'embed') vc_embed_layout($vids, $i); ?> **This is line 252**
function vc_modal_layout(){ ... }
// should be:
function vc_modal_layout($vids){ ... }
function vc_embed_layout($vids, $i)
// looks good.
Aside from that, nothing stands out as really unusual & I'd want to have a look at the actual site to tinker with this problem further.
Below is my code for display information of an image including its file, but this is not displaying, I don't know why.
<?php
include('config/dbconnect.php');
if(isset($_GET['id']))
{
$id = $_GET['id'];
$sql = mysqli_query($con, "SELECT * FROM collage WHERE id = '$id'");
while($row = mysqli_fetch_array($sql)) {
$name = $row['name'];
$content = $row['content'];
$size = $row['size'];
$type = $row['type'];
$date_upload = $row['date_upload'];
$file = $row['file'];
}
}
?>
<div class='body-content'>
<div class='img-name-cont'><h3><?php echo $name; ?></h3></div>
<div class='img-detail-cont'>upload: <?php echo $date_upload; ?><br>type: <?php echo $type; ?><br>size: <?php echo $size; ?>KB </div>
<div class='img-file-cont'>
<img src="img/collage/<?php echo $row['file'] ?>" style="width:130px; height:100%"></div>
<div class='img-content-cont'><?php echo $content; ?></div>
</div>
First of all use inspect to check whether the image is actually pointed to by the code. that is the actual loation might not be pointed at. what is your folder structure.
" style="width:130px; height:100%">
your code is ok. as long as php echo $row['file'] returns a file
The problem here is "Your all the variables are local to the while loop". so you can't access it outside of the while loop. Try this code.
<?php
include('config/dbconnect.php');
if(isset($_GET['id']))
{
$id = $_GET['id'];
$sql = mysqli_query($con, "SELECT * FROM collage WHERE id = '$id'");
while($row = mysqli_fetch_array($sql)) {
?>
<div class='body-content'>
<div class='img-name-cont'><h3><?php echo $row['name']; ?></h3></div>
<div class='img-detail-cont'>upload: <?php echo $row['date_upload']; ?><br>type:
<?php echo $row['type']; ?><br>size: <?php echo $row['size']; ?>KB </div>
<div class='img-file-cont'>
<img src="img/collage/<?php echo $row['file']; ?>" style="width:130px; height:100%"></div>
<div class='img-content-cont'><?php echo $row['content']; ?></div>
</div>
<?php
}
}
?>
Be sure to check echo $row['file'] if it returns the correct string of your image path with the correct file extension .
try this one :
first of all you have to check if your image path ok or not using this php function:
<?php
$img=getimagesize($imagewithpath);
if($img=="")
{ echo "there is no image ";}
else{ ?> <img src="<?php echo $imagewithpath; ?>" style="width:130px; height:100%"> <?php } ?>
As answered by Dulaj Sanjaya all your variables are local so you can't use that outside of while.
Second if you want to use your code then you have taken all data of $row in different variables then used outside of file then why don't you used same $file for image why you have used $row['file']?
Simply replace this line as
<div class='img-file-cont'>
<img src="img/collage/<?php echo $file; ?>" style="width:130px; height:100%"></div>
I am trying to use $description variable outside the loop. Help me do it please.
<?php
$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());
$albums = array();
$description = "";
while ($row_album = mysql_fetch_assoc($res_album)) {
$description = $row_album['description'];
$albums[$row_album['title']] = array(
'images/albums/'.$row_album['title'].'/1.jpg',
'images/albums/'.$row_album['title'].'/2.jpg',
'images/albums/'.$row_album['title'].'/3.jpg',
'images/albums/'.$row_album['title'].'/4.jpg'
);
}
foreach ($albums as $name => $a) {
?>
<div id="album">
<a href="view_album.php?name=<?php echo $name; ?>" data-images="<?php echo implode('|', array_slice($a,1))?>" class="album">
<img src="<?php echo $a[0]?>" alt="<?php echo $name?>" />
<span class="preloader"></span>
</a>
<div class="album_info">
<h4><?php echo $name?></h4>
<p><?php echo $description; ?></p>
</div>
</div>
<?php
}
?>
Should I make an array, or define it first, i am totally confused, need help.
In your $albums array (in the while loop), store your images and description like this:
$albums[$row_album['title']] = array(
"description" => $row_album['description'],
"images" => array(
'images/albums/'.$row_album['title'].'/1.jpg',
'images/albums/'.$row_album['title'].'/2.jpg',
'images/albums/'.$row_album['title'].'/3.jpg',
'images/albums/'.$row_album['title'].'/4.jpg'
)
);
Then in your foreach loop, act like this:
<img src="<?php echo $a['images'][0]?>" alt="<?php echo $name?>" />
and
<p><?php echo $a['description']; ?></p>
Edit:
Don't forget to change this
array_slice($a,1)
to this:
array_slice($a['images'],1)
I would just combine the whole thing into a single loop; the below code is untested, but I hope you can follow it.
while ($row_album = mysql_fetch_assoc($res_album)) {
print_album($row_album);
}
function print_album(array $album)
{
$name = htmlspecialchars($album['title'], ENT_QUOTES, 'UTF-8');
$description = htmlspecialchars($album['description'], ENT_QUOTES, 'UTF-8');
$view_link = sprintf('view_album.php?%s', http_build_query([
'name' => $album['title'],
]);
$images = array_map(function($index) use ($album) {
return sprintf(
'images/albums/%s/%d.jpg',
urlencode($album['title']),
$index
);
}, range(1, 4));
$images_data = htmlspecialchars(join('|', array_slice($images, 1)), ENT_QUOTES, 'UTF-8');
?>
<div id="album">
<a href="<?php echo $view_link ?>" data-images="<?php echo $images_data; ?>" class="album">
<img src="<?php echo htmlspecialchars($images[0], ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo $name; ?>" />
<span class="preloader"></span>
</a>
<div class="album_info">
<h4><?php echo $name; ?></h4>
<p><?php echo $description; ?></p>
</div>
</div>
<?php
}
I've added escaping with the use of urlencode(), htmlspecialchars() and http_build_query() to prevent a potential break in your HTML (or XSS is the worst case).
Hope y'all can help!
I'm using a PHP driven link directory program and, fo some reason, the summary descriptions recorded to my MySQL database and being generated, BUT the HTML tags won't render on the page. I've included the code below and here's an http://abiautism.com/autism-resources/?page=pages&id=2 Any help would be greatly appreciated!
<?php if ($rowpages[IMAGENAME] != "") { ?>
<?php if ($rowpages[WIDTH] == '') $rowpages[WIDTH] = '128px'; ?>
<?PHP
$filename = "$svr_rootscript/product_images/$rowpages[IMAGENAME].jpg";
if (file_exists($filename)) $ext = jpg;
$filename = "$svr_rootscript/product_images/$rowpages[IMAGENAME].png";
if (file_exists($filename)) $ext = png;
?>
<?PHP if ($ext != '') { ?>
<img class="photo" src="product_images/<?php echo $rowpages[IMAGENAME]; ?>.<?php echo $ext; ?>" width="<?php echo $rowpages[WIDTH]; ?>">
<?PHP } ?>
<?PHP } ?>
<h1><?php echo $rowpages[HEADER]; ?></h1>
<h3><?php $description = preg_replace("/\n/","\n<BR>",$rowpages[CAPTION]); ECHO $description; ?></h3>
<?PHP if ($rowpages[SHOWADS] != '') { ?>
<div align ="center"><?php echo $rowxxx[ADS]; ?></div>
<?PHP } ?>
<b><p><? echo $pages_vst; ?></p></b>
<?php $description = preg_replace("/\n/","\n<BR>",$rowpages[PAGECONTENT]); ECHO $rowpages[PAGECONTENT]; ?>
You can use this
echo htmlspecialchars_decode($content_html);
This change the < to <
I have a query that selects 3 rows; but I only want to display the one row at a time, use the data from that row, then move to the next row, then repeat. How would this be accomplished? Table has 4 items in it.
PHP:
<?php
$server = "secret";
$user = "secret";
$pass = "secret";
$db = "secret";
$con=mysqli_connect($server,$user,$pass,$db);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'SELECT * FROM news ORDER BY id DESC LIMIT 3';
mysqli_select_db($con, $db);
$query = mysqli_query($con, $sql);
$number = 1;
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
}
mysqli_close($con);
?>
Attempt to display:
<div name='title'><?php echo $title; ?></div> || <div name='news_date'><?php echo $news_date; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post; ?></p>
<?php
$number++;
?>
Output of attempt:
Test
||
7/14/13
News 1
Testing to see if this will work lalalalalla
NOTE: Tried to repeat the attempt to see if it would work, but it displayed same as output but with a second one that was a duplicate except said News 2
Desired output look:
Newest Title | Newest Date
Newest news. Etc. Insert Big Paragraph of news here etc etc.
2nd Newest Title | 2nd Newest Date
2nd Newest news. Etc. Insert Big Paragraph of news here etc etc.
3rd Newest Title | 3rd Newest Date
3rd Newest news. Etc. Insert Big Paragraph of news here etc etc.
The problem is that you are overwriting your variables with each while() loop -
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
}
so when you try to echo $id, $title, $news_date, and $post, you will only get the last row data
you either need to add your html in the while loop -
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
?>
<div name='title'><?php echo $title; ?></div> || <div name='news_date'><?php echo $news_date; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post; ?></p>
<?php
$number++;
}
or save them to an array
$id = array();
$title = array();
$news_date = array();
$post = array();
while ($result = mysqli_fetch_array($query)) {
$id[] = $result['id'];
$title[] = $result['title'];
$news_date[] = $result['news_date'];
$post[] = $result['post'];
}
and then access the array in your display
<div name='title'><?php echo $title[$number-1]; ?></div> || <div name='news_date'><?php echo $news_date[$number-1]; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post[$number-1]; ?></p>
<?php
$number++;
?>
I used [$number-1] as I assume $number is starting at 1, and arrays are 0 based
edit here are ways to echo your html. It would be beneficial to visit the php documentation, as all of this is there. In these I set $number back to 0, but you can change it back to 1, and just change each of the $number->$number-1, and the $number+1->$number
using a for loop - http://php.net/manual/en/control-structures.for.php
<?php
for($number=0;$number<count($title);$number++){
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
}
?>
using a foreach loop - http://php.net/manual/en/control-structures.foreach.php
<?php
foreach($title as $number => $value{
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
}
?>
using a while loop - http://php.net/manual/en/control-structures.while.php
<?php
$number = 0;
while($number<count($title){
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
$number++;
}
?>
each of the above was done by closing out of php, and writing the html, and then opening php again. You could also just stay in php, and echo the html - http://php.net/manual/en/function.echo.php
<?php
for($number=0;$number<count($title);$number++){
echo "<div name='title'>".$title[$number]."</div> || <div name='news_date'>".$news_date[$number]."</div>";
echo "<p>News ".($number+1)."</p>";
echo "<p>".$post[$number]."</p>";
}
?>