Image doesn't display using PHP - php

I'm trying to display the contents from database. Following query is working fine, but the problem is image does not show anymore.
<?php
session_start();
// Include config file
require_once "../auth/dbconnection.php";
$output='';
$sql='select `image`,`title`,`sub_title`,`username`,`blog_id`,`body`,`published` from `blog` WHERE user_id=? ';
$stmt=$conn->prepare( $sql );
$stmt->bind_param( 's',$_SESSION['user_id'] );
$res=$stmt->execute();
if( $res ){
$stmt->store_result();
$stmt->bind_result($image,$title,$sub_title, $username, $blog_id,$body,$published);
while( $stmt->fetch() ){
$filepath="../assets/img/blog_images/";
$title= substr($title,0,30);
$body= substr($body,0,500);
$date= date('dS F Y', strtotime($published));
$output .= '
<div class="col-sm-6 col-md-6 col-lg-4">
<div class="blog grid-blog">
<div class="blog-image">
<a href="#">';
$output .= ' <img style="height:190px; width:330px;" class="img-fluid" src="data:image/png;base64, %s" alt="" />'; base64_encode(file_get_contents($filepath.$image) ) ;
$output .= ' </a>
</div>
<div class="blog-content">
<h3 class="blog-title"> '.$title.' </h3>
<p> <code> '.$body.' </code> </p> <br>
<i class="fa fa-long-arrow-right"></i> Read More
<div class="blog-info clearfix">
<div class="post-left">
<ul>
<li><i class="fa fa-calendar"></i> <span>'.$date.'</span></li>
</ul>
</div>
<div class="post-right"><i class="fa fa-heart-o"></i>21 <i class="fa fa-eye"></i>8 <i class="fa fa-comment-o"></i>17</div>
</div>
</div>
</div>
</div>';
}
echo $output;
}else{
echo 'No any post found';
}
?>
Can anyone guide me how can fix the issue, i would like to appreciate if someone guide me regarding this. Thank You.

I assume that you omit sprintf function.
This should work.
sprintf('<img src="data:image/png;base64, %s" alt="" />', base64_encode(file_get_contents($filepath.$image));

You could put the image binary in separate variable to be easy to use
$binary = "data:image/png;base64," . base64_encode(file_get_contents($filepath . $image));
and use it like this
$output .= '<img style="height:190px; width:330px;" class="img-fluid" src="' . $binary . '" alt="" />';

Related

Can´t correctly write custom field data in custom function placed in functions.php

I need to write filter data of my custom post type in custom function placed in functions.php:
The majority are corrected, but I cannot process these lines:
<div class="cpt-studies-block-image picture">
<?php $thumb_img=wp_get_attachment_image_src(get_field('image'),'custom-crop-studien'); ?>
<img class="img" src="<?php print($thumb_img[0]); ?>">
</div>
and:
<a href="<?php the_permalink()?>" class="cpt-studies-block-link link-read-more"> <?php
include get_stylesheet_directory() . '/img/svg/icon_arrow.svg';
?>
<?php if (get_field('button_text')):
the_field('button_text');
else : echo __('More', 'dw');?>
<?php endif;?>
</a>
Code in folder for writing Custom Post Type data:
if($query->have_posts()):
while($query->have_posts()) : $query->the_post();?>
<div class="col-md-6">
<div class="cpt-studies-block">
<div class="row">
<div class="col-md-6">
<a class="zoom-picture-hover" href="<?php the_permalink()?>">
<div class="cpt-studies-block-image picture">
<?php $thumb_img=wp_get_attachment_image_src(get_field('image'),'custom-crop-studien'); ?>
<img class="img" src="<?php print($thumb_img[0]); ?>">
</div>
</a>
</div>
<div class="col-md-6">
<span><?php the_field('date')?></span>
<h3>
<a href="<?php the_permalink()?>">
<?php the_title()?>
</a>
</h3>
<p class="cpt-studies-block-text"><?php the_field('text')?></p>
<a href="<?php the_permalink()?>" class="cpt-studies-block-link link-read-more"> <?php
include get_stylesheet_directory() . '/img/svg/icon_arrow.svg';
?>
<?php if (get_field('button_text')):
the_field('button_text');
else : echo __('More', 'dw');?>
<?php endif;?>
</a>
</div>
</div>
</div>
</div>
<?php endwhile;
endif;
?>
Code in Custom function in functions.php:
if(have_posts($wp_query))
{
while(have_posts($wp_query))
{
the_post();
echo '<div class="col-md-6">'
.'<div class="cpt-studies-block">'.
'<div class="row">'.
'<div class="col-md-6">'
.'<a class="zoom-picture-hover" href="'.get_permalink().'">'
.'<div class="cpt-studies-block-image picture">'
.$thumb_img=wp_get_attachment_image_src(get_field('image'),'custom-crop-studien').
'<img class="img" src=".print($thumb_img[0]).">'
.'</div>'
.'</a>'
.'</div>'
.'<div class="col-md-6">'
.'<span>'.get_field('date').'</span>'
.'<h3>'
.'<a href="'.get_permalink().'">'
.get_the_title().
'</a>'
.'</h3>'
.'<p class="cpt-studies-block-text">'.get_field('text').'</p>'.
'<a href="'.get_permalink().'" class="cpt-studies-block-link link-read-more">'
include get_stylesheet_directory() . '/img/svg/icon_arrow.svg';
'</a>'.
'</div>'.
'</div>'.
'</div>'.
'</div>';
}
}
Please can someone give me advice, or do I need to change method on writing these lines?
You got a syntax error:
.'<div class="cpt-studies-block-image picture">' // Add semicolon.
.$thumb_img = wp_get_attachment_image_src(
get_field('image'),'custom-crop-studien'). // Assignement can't be concatenated
// and missing parenthesis
'<img class="img" src=".print($thumb_img[0]).">' // Resume echo.
So:
// Ommited
.'<div class="cpt-studies-block-image picture">';
$thumb_img = wp_get_attachment_image_src(
get_field('image'), 'custom-crop-studien'));
echo '<img class="img" src=".print($thumb_img[0]).">'
Or better yet, use templates (as I explained in this other question of yours)

PHP import images from directory into 2 column HTML row

I have found some PHP that I am trying to adapt onto my page but can not seem to get it to work. Here is the code:
<?php
$pagetitle = "Test Gallery";
$dirname = "img/folder_1/";
$images = glob($dirname."*.jpg");
?>
<?php $i=0; foreach($images as $image): ?>
<?php if($i%2 === 0) echo '<div class="row">' ?>
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
<?php if($i%2 === 0) echo '</div>' ?>
<?php $i++; endforeach ?>
I am trying to get the images to be pulled from a directory and each image is wrapped in a .col-sm-6 div then each 2 are wrapped in a .row div, then if there is an odd number of the files the last one would just be one .col-sm-6 div on its own. Below is the structure that I am trying to achieve:
<div class="row">
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<img class="lazy store-img" src="IMAGE_SOURCE" alt="" title="">
<h3>IMAGE_NAME</h3>
<button href="#" class="btn btn-primary">Purchase Image</button>
</div>
</div>
The IMAGE_NAME I would add something to pull through the imported filename so it can be displayed on the page and the IMAGE_SOURCE would be the images URL so for now please ignore those bits of text as I don't think it will affect this?
I am new to PHP and just can't seem to find why nothing is showing on the page unless this code is not suited to my needs?
P.s. if any of my syntax's are incorrect I apologies in advance.
$images will be filled by your golb
So basically you just edit the line
<?php if($i%2 === 0) echo '</div>' ?>
To
<?php if($i%2 === 1) echo '</div>' ?>
Here a more readable example:
<?php
$images = [
'https://via.placeholder.com/10x50','https://via.placeholder.com/20x50','https://via.placeholder.com/30x50','https://via.placeholder.com/40x50',
'https://via.placeholder.com/50x50','https://via.placeholder.com/60x50','https://via.placeholder.com/70x50',
];
?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"/>
<?php
$cols = 2; // dividable by 12 please
for( $i = 0; $i < count($images) && $image = $images[$i]; $i++) {
if( $i%$cols == 0 ) { echo '<div class="row">'; }
echo '<div class="col-sm-' . 12/$cols . '">';
echo '<img class="lazy store-img" src="' . $image . '" alt="" title="">';
echo '<h3>IMAGE_NAME</h3>';
echo '<button href="#" class="btn btn-primary">Purchase Image</button>';
echo '</div>';
if( $i%$cols == $cols-1 ) { echo '</div>'; } /* here comes the magic :) */
}
if( count( $images )%$cols > 0 ) {
echo '</div>';
}
?>

Displaying data from while loop into html code

I need tips or direction on how can I display data from mysql using echo. But I want to display it in html code. I want to display $row["title"] of first title in mysql instead title1 and $row["content"] of first content in mysql instead content1 and do that for all 3 divs. php code works fine I just can't figure out how to make that possible.
<div class="carousel-inner" style="background-size:cover;">
<div class="item active">
<img src="img/road1.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title1</h2>
<p>content1</p>
</div>
</div>
<div class="item">
<img src="img/road2.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title2</h2>
<p>content2</p>
</div>
</div>
<div class="item">
<img src="img/road3.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title3</h2>
<p>content3</p>
</div>
</div>-->
<?php
session_start();
include_once("db.php");
$sql = "SELECT * FROM news";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_assoc($query)) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<p>" . $row["content"] . "</p>";
}
} else {
echo "0 results";
}
?>
You're almost there. Just move the html into the echo of the while loop.
echo '<div class="carousel-inner" style="background-size:cover;">';
$counter = 1;
while($row = mysqli_fetch_assoc($query)) {
echo '
<div class="item ' . ($counter == 1 ? 'active' : '') . '">
<img src="img/road{$counter}.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>' . $row["title"] . '</h2>
<p>' . $row["content"] . '</p>
</div>
</div>';
$counter++;
}
echo '</div>';
The only issue is the image, realistically you'd save the image in the database with the title and content then use the same method but for this simple case lets just use a counter
please note that I change your entire code a little bit to make the desired results...
<div class="carousel-inner" style="background-size:cover;">
<?php
session_start();
include_once("db.php");
$sql = "SELECT * FROM news";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_assoc($query)) { ?>
<div class="item active">
<img src="img/road1.jpg">
<div class="carousel-caption d-none d-md-block">
<h2><?php echo $row["title"]; ?></h2>
<p><?php echo $row["content"]; ?></p>
</div>
</div>
<?php
}
} else {
echo "0 results";
}
?>
Also note that I'm repeating just the first image... You need an extra on planning to determine how to handle images in code and then update this one.

Use html in a php variable

I have this variable in php with html, but it doesn't work. Can you guys find any mistake...I tried and didn't find anything.
The code is:
$html .= '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<div class="box-produtos">
<a href="' . $url_imagem . '" class="magnifier" rel="shadowbox">
<img src="' . $url_imagem . '" class="img-responsive img-produtos center-block" onerror="imgError(this);">
</a>
<div class="facebook-btn" onclick="window.open("http://www.facebook.com/sharer/sharer.php?u=' . $base_url . '"/facebookPublish.php?idproduto="' . $idproduto . '", "sharer", "toolbar=0,status=0,width=548,height=325");"><i class="fa fa-facebook fc-facebook"></i>' . $lang["FACEBOOK_SHARE"] . '</div>
<div class="clearfix"></div>
<h5 class="prod-size">' . $produto . '<br>' . $refproduto . '</h5>
<div class="clearfix"></div>
<h5 class="text-center font-color">' . $lang['DEFAULT_PRICE'] . ' ' . $preco . ' €</h5>
' . $lang['GERAL_COMPRAR'] . '';
You can use Heredocs to mix PHP with HTML in pretty way.
$html .= <<< HTML
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<div class="box-produtos">
<a href="{$url_imagem}" class="magnifier" rel="shadowbox">
<img src="{$url_imagem}" class="img-responsive img-produtos center-block" onerror="imgError(this);">
</a>
<div class="facebook-btn" onclick="window.open("http://www.facebook.com/sharer/sharer.php?u={$base_url}/facebookPublish.php?idproduto={$idproduto}", "sharer", "toolbar=0,status=0,width=548,height=325");">
<i class="fa fa-facebook fc-facebook"></i>{$lang["FACEBOOK_SHARE"]}
</div>
<div class="clearfix"></div>
<a href="{$base_url}/{$langi}/produtosDesc/{$idproduto}">
<h5 class="prod-size">{$produto}<br/>{$refproduto}</h5>
</a>
<div class="clearfix"></div>
<h5 class="text-center font-color">
{$lang['DEFAULT_PRICE']} {$preco} €
</h5>
<a href="{$base_url}/{$langi}/produtosDesc/{$idproduto}" class="btn btn-skin center-block btn-prod">
{$lang['GERAL_COMPRAR']}
</a>
HTML;// no indentation, must be single in line, so remove this comment
Also you were messing with facebook link in onclick attribute.
If you want to avoid the mistakes of quotes you can try something like this :
$var="variables";
$html =<<<HTML
<h1>All your html code</h1>
<p>with all your $var or {$var}</p>
HTML;
echo $html;
it's safer.
Use <?php ?> whenever specifying the php variable.
You cannot spread a string over multiple lines. (Justinas sais you can. See comment below)
I think this question is related to your one:
Best Practices: working with long, multiline strings in PHP?
Edit 1:
I think an other solution could also be that you have your HTML in a separate file an then read its content to your variable.
$html .= file_get_contents("your-file.html");
Edit 2: Removed wrong statement. As mentioned in Justinas comment.

Translate Wordpress block with <?php _e(

I have made some block custom in my wordpress theme. I did have to edit the shortcode.php file to add a price table. The thing I just realize is that I need those words ( From , /DAY , Book ) being translated though the .po file of my theme. So I have tried to add this line to replace the word ( "From" for example ). But I have a error code, I guess I don't have a good syntax here but can't find the right one. Can you Help?
Here is the original code
/*CUSTOM PRICE*/
}elseif($type === 'content_block_custom_price'){
$result = '<div class="featurecustom text-center">';
$result .= '<div class="thumbnail">
<img src="'.AUTORENT_IMAGE.''.$img.'" alt="">
</div>
<p class="titlecustom">'.$title.'</p>
<p class="fromprice"> From</p>
<span class="pricenumber">'.$pricetype.'<sup>€</sup></span><span class="fromprice">/ DAY</span>
<hr>
<p class="customdescription">'.$des.'</p>
<div class="bookingbutton" style="vertical-align:middle"><span>BOOK </span></div>
';
$result .= '</div>';
return $result;
/* CUSTOM PRICE*/
Here is the bad code i try to have my word translate
/*CUSTOM PRICE*/
}elseif($type === 'content_block_custom_price'){
$result = '<div class="featurecustom text-center">';
$result .= '<div class="thumbnail">
<img src="'.AUTORENT_IMAGE.''.$img.'" alt="">
</div>
<p class="titlecustom">'.$title.'</p>
<p class="fromprice"> <?php _e('From','themename'); ?></p>
<span class="pricenumber">'.$pricetype.'<sup>€</sup></span><span class="fromprice"><?php _e('/DAY','themename'); ?></span>
<hr>
<p class="customdescription">'.$des.'</p>
<div class="bookingbutton" style="vertical-align:middle"><span><?php _e('Book','themename'); ?> </span></div>
';
$result .= '</div>';
return $result;
/* CUSTOM PRICE*/
Post solved problem question : One I have new entries such as "Book" " FROM" and "/DAY", I guess I will have to creat them into the poedit file? Or will they be automatically added?
Thanks :)
Here is the good code (just inserting the gettex like this '. __("From","theme name").':
/*CUSTOM PRICE*/
}elseif($type === 'content_block_custom_price'){
$result = '<div class="featurecustom text-center">';
$result .= '<div class="thumbnail">
<img src="'.AUTORENT_IMAGE.''.$img.'" alt="">
</div>
<p class="titlecustom">'.$title.'</p>
<p class="fromprice"> '. __("From","theme name").'</p>
<span class="pricenumber">'.$pricetype.'<sup>€</sup></span><span class="from price">'. __("/DAY","theme name") .'</span>
<hr>
<p class="customdescription">'.$des.'</p>
<div class="bookingbutton" style="vertical-align:middle"><span>'. __("Book","themename"); .' </span></div>
';
$result .= '</div>';
return $result;
/* CUSTOM PRICE*/
For translation of themes & plugins there is a very effective and easy free plugin: Loco Translate
This plugin is going to scan your theme for new items to translate…

Categories