How to parse php inside html - html

I tried to parse the php query into html, but on the html page it shows array.
My query looks like this: $comments = get_comments( array('post_id' => $post->ID, 'status' => 'approve') );
I tried to print it on the html page using this: $html .= $comments;

As you can see from the examples.
And as Tom J Nowell commented, you need to loop through each comment and append the comment to the $html.
$args = array(
'status' => 'approve',
'post_id' => $post->ID,
);
$comments = get_comments( $args );
foreach ( $comments as $comment ) :
$html .= $comment->comment_author . '<br />' . $comment->comment_content . '<br />';
endforeach;

Related

Wordpress wpdb not inserting/updating with HTML data

So simply put, I have my PHP code generating a bunch of HTML. I then want to update a database entry like so
$wpdb->update("wp_table",
array( 'content' => $html ),
array( 'id' => 1 ),
array( '%s' ),
array( '%d' )
);
This simply does not work. Nothing in the database changes.
To debug, I placed the exact same code right above with one minor change, and it DOES WORK:
$wpdb->update("wp_sn_cached_popular_display",
array( 'content' => "hello" ),
array( 'id' => 1 ),
array( '%s' ),
array( '%d' )
);
(I swapped out the $html for a direct string.)
I can't even begin to comprehend why, and I've played around with it a lot. I've even done this and it DOES WORK too:
$string = "hello";
$wpdb->update("wp_sn_cached_popular_display",
array( 'content' => $string),
array( 'id' => 1 ),
array( '%s' ),
array( '%d' )
);
It's just the one $html variable is causing this function to not run, or something?
Compiling the $html variable is a bunch of stuff like this:
$html .= '<li>';
$html .= '<div class="upcoming-left">';
$html .= '<time datetime="' . $date . '" class="icon">';
$html .= '<em>' . $date_day.'</em>';
$html .= '<strong>' . $date_month . '</strong>';
$html .= '<span>' . $date_num . '</span>';
$html .= '</time>';
$html .= '</div>';
$html .= '<div class="upcoming-right">';
$html .= '<span class="upcoming-title">' . $upcoming_title . '</span>';
$html .= '<span class="upcoming-desc">' . $upcoming_desc . '</span>';
$html .= '<div class="clear"></div>';
$html .= '</div>';
$html .= '</li>';
//...
Any ideas why this is?
Bonus fun time: This appears to work on my local xampp insall, not the live site.
This could be an issue with table datatypes
https://www.w3schools.com/sql/sql_datatypes.asp
depending on what the table is set to it may not support the string length of your html variable or certain chars in it.
It looks like you concat your .html var multiple times. It's a pretty long string in the end. to test this try to save a very long manually entered string. try with special chars. look at the table structure. This is just some ideas and where my thoughts go.

HTML Table formatting Issue

I am trying to align contents of two arrays in a tabular format and send an email. But the second column in the table doesn't align as desired. The content of the second column appears as a single row.
I'm attaching output table as well:
#!/usr/bin/perl
use strict;
use warnings;
use MIME::Lite;
use HTML::Entities;
my $msg;
my #Sucess = qw(s1 s2 s3 s4 s5 s6);
my #Failed = qw(f1 f2 f3 f4);
my $html = '<table style="width:600px;margin:0 100px" border="1" BORDERCOLOR="#000000">
<thead><th bgcolor="#9fc0fb">Successful</th><th bgcolor="#9fc0fb">Failed</th></thead>
<tbody>';
$html .= "<tr><td>$_</td>" for #Sucess;
$html .= "<td>$_</td>" for #Failed;
$html .= " </tr>";
$msg = MIME::Lite->new(
from => 'foo#abc.com',
To => 'foo#abc.com',
Subject => 'Status of Update',
Type => 'multipart/related'
);
$msg->attach(
Type => 'text/html',
Data => qq{
<body>
<html>$html</html>
</body>
},
);
MIME::Lite->send ('smtp','xyz.global.abc.com' );
$msg->send;
You need to replace your code that builds up the table with something that works in a logical order. HTML tables need to be defined row by row. You can't process all of the successes and then all of the failures.
I'd replace your middle section of code with something like this:
use List::Util qw[max];
my $max = max($#Sucess, $#Failed);
for (0 .. $max) {
$html .= '<tr><td>';
$html .= $Sucess[$_] // '';
$html .= '</td><td>';
$html .= $Failed[$_] // '';
$html .= "</td></tr>\n";
}
But actually, I would never put raw HTML in a Perl program. Use a templating system instead.
First you loop over each item in #Sucess and for each one you:
Create a new row
Create a cell in that row
$html .= "<tr><td>$_</td>" for #Sucess;
Then you look over each item in #Failed and for each one you:
Create a cell in the last row you created (for the most recent #Sucess)
$html .= "<td>$_</td>" for #Failed;
Finally, you explicitly close the last table row you created:
$html .= " </tr>";
To get the layout you desire (which is distinctly non-tabular) you need to work row by row. You can't deal with all the #Sucess and then all the #Failed.
my #Sucess= qw(s1 s2 s3 s4 s5 s6);
my #Failed= qw(f1 f2 f3 f4);
my $html = "<table>\n";
do {
my $s = shift #Sucess;
my $f = shift #Failed;
$html .= sprintf("<tr> <td> %s </td> <td> %s </td> </tr> \n", map { $_ // '' } $s, $f);
} while ( #Sucess or #Failed );
$html .= "</table>";
print $html;

Yii2.0 pagination issue second page not working

How do I do a pagination? I have a search form and a search button which passes in a date range. The first page is working successfully, however when I click on the second page, it shows everything. How do I pass the date range into my pagination?
EDIT:
Below is my ReportSearch.php (model)
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 5,
//'params' => array('search' => 'true', 'from_dt'=>$stockmovement_summary_from_sales_date, 'to_dt'=> $stockmovement_summary_to_sales_date),
],
]);
$dataProvider->setSort([
'defaultOrder' => [
'd_item.desc_e_tx' => SORT_ASC,
],
'attributes' => [
'd_item.desc_e_tx'
]
]);
return $dataProvider;
}
Below is my controller:
$searchModel = new ReportSearch();
$dataProvider = $searchModel->searchStockMovementSummary($stockmovement_summary_from_sales_date, $stockmovement_summary_to_sales_date);
return $this->render('stockmovementreportsummary', [
'search' => 'true',
'dataProvider' => $dataProvider,
'from_dt' => $stockmovement_summary_from_sales_date,
'to_dt' => $stockmovement_summary_to_sales_date,
'model' => $searchModel,
]);
Below is my index.php
$reports = $dataProvider->getModels();
$i=1;
echo "<table class='table table-striped table-bordered'>";
echo "<tr><th>#</th><th>Item</th><th>Total Summary Usage Qty</th><th>Current Stock On Hand</th><th>Measurement</th></tr>";
foreach ($reports as $report) {
$item_key = $report['report_item_key'];
$item_model = Item::find()->where(['item_key' =>$item_key])->one();
$item_e_desc_tx = $item_model->desc_e_tx;
$item_c_desc_tx = $item_model->desc_c_tx;
$item_qty_no = $item_model->qty_no;
$item_measurement_tx = $item_model->measurement;
echo "<tr>";
echo "<td>" . $i++ . "</td>";
echo "<td>" . Html::a($item_key, array('stockmovementreportdetailbyitem', 'item_key' => $item_key, 'search' => 'true', 'from_dt' => $from_dt, 'to_dt'=>$to_dt)) . "<br>" . $item_e_desc_tx . "<br>" . $item_c_desc_tx ."</td>";
echo "<td>" . $report['total_summary_usage_qty'] . "</td>";
echo "<td>" . $item_qty_no . "</td>";
echo "<td>" . $item_measurement_tx . "</td>";
echo "</tr>";
}
echo "</table>";
echo \yii\widgets\LinkPager::widget([
'pagination'=>$dataProvider->pagination,
]);
GridView should be used but I do not think it will help. Do you by any chance use POST instead of GET to filter the results? If you take a look here https://github.com/yiisoft/yii2/blob/master/framework/data/Pagination.php#L257 at the createUrl function you will see that it uses getQueryParams http://www.yiiframework.com/doc-2.0/yii-web-request.html#getQueryParams() to create the query string. If you use POST then this function will not pick up the params properly hence the next page pagination will fail.
Ok, because you actually do use POST then you have to create your own pagination function that takes post into consideration. Or just use GET. You are not performing any operations to the DB you can safely use GET. It is better for everybody.
You have to edit the code in your action.
Read this documentation.
And edit $dataProvider->pagination

mysql query different meta_key and display them separately

I am a new to mysql and my question is difficult for me to describe. Wordpress stores a lot of postmeta as various meta_keys that contain various meta_values. I'm having a problem trying to query by a particular meta_key but and then being able to display 2 different meta_keys and their values. Here is what I have so far which properly displays all of the video urls from a particular wordpress category...
<?php
$myquery=mysql_query("
SELECT * FROM foy_postmeta AS pm
INNER JOIN foy_term_relationships AS tr ON (pm.post_id = tr.object_id)
INNER JOIN foy_posts AS p ON (pm.post_id = p.ID)
WHERE pm.meta_key='video_url'
AND tr.term_taxonomy_id='27'
AND p.post_status='publish'
ORDER BY p.post_date DESC
");
$rows = array();
while($row=mysql_fetch_array($myquery)){
$rows[] = $row;
}
?>
And then I put this into rows within my html which properly displays all of the video titles and their paths...
<?php
foreach( $rows as $row ) {
<div>my video title: <?php echo $row["post_title"]; ?></div>
<div>my video url: <?php echo $row["meta_value"]; ?></div>
}
?>
Now, what I would like to do is to keep this same row list, but to also write out another meta_key and it's value, something like this....
<?php
foreach( $rows as $row ) {
<div>my video title: <?php echo $row["post_title"]; ?></div>
<div>my video url: <?php echo $row["meta_value"]; ?></div>
<div>my video format is: <?php echo $row["meta_value"]; ?></div>
}
?>
But I'm not sure how I can display 2 meta_values within the same loop since they have separate meta_keys within the same postmeta table.
you can use wp_query for this. Its the wordpress database query for posts which makes things easier when dealing with post_meta.
http://codex.wordpress.org/Class_Reference/WP_Query
for example for the above
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'video_url',
)
),
'tax_query' => array(
array(
'taxonomy' => 'your taxonomy name here',
'field' => 'slug',
'terms' => 'whatever'
)
),
'orderby' => 'date',
'order' => 'DESC',
);
$query= new wp_query($args);
?>
while ( $query->have_posts() ) : $query->the_post();
$meta = get_post_meta( $post->ID );
var_dump($meta);
?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
now for every post you can access the post_meta (check what the array var_dumps for the keys)
or if you want to persist with mysql use a foreach loop for each row and pass the id to get_post_meta($id); you can then use the postmeta for every row.
I found a solution that although works, I'm thinking there is a better way to do it. I removed the specific meta_key item within the query so that I could grab all meta_keys, and then used if statements within the foreach loop to create variables of the particular ones I wanted to display:
<?php
$myquery=mysql_query("
SELECT * FROM foy_postmeta AS pm
INNER JOIN foy_term_relationships AS tr ON (pm.post_id = tr.object_id)
INNER JOIN foy_posts AS p ON (pm.post_id = p.ID)
WHERE tr.term_taxonomy_id='27'
AND p.post_status='publish'
ORDER BY p.post_date DESC
");
$rows = array();
while($row=mysql_fetch_array($myquery)){
$rows[] = $row;
}
<?php
foreach( $rows as $row ) {
// sets video url and video layout values as variables
if ($row["meta_key"] == "video_url" ){ $videourl = $row["meta_value"]; }
if ($row["meta_key"] == "video_layout" ){ $videolayout = $row["meta_value"]; }
if ($row["meta_key"] == "video_url" ){
?>
<div>my video url: <?php echo $videourl ?></div>
<div>my video format is: <?php echo $videolayout ?></div>
<?php
}
}
?>

How to get all metavalue for a specific custom field for all posts in one category?

I'm trying to get the sum for all the meta values of one custom field. I now get the sum for the metavalues of the whole site. I want it to be restricted to the category you're in.
The code now looks like this:
<?php
$thevariable = $wpdb->get_var($wpdb->prepare("
SELECT SUM($wpdb->postmeta.meta_value)
FROM $wpdb->postmeta, $wpdb->posts
WHERE $wpdb->postmeta.meta_key='mycustomfield'
AND $wpdb->postmeta.post_id=$wpdb->posts.id
"));
echo '<h1>' . $thevariable . '</h1>';
?>
Can somebody help me to filter out one category?
Would be amazing!
M
Inside your WP files, you can add this lines; I guess It will do what you are looking for.
<?php
$MySum = 0;
$args = array(
'category_name' => 'MyCategory',
'meta_key' => 'mycustomfield',
'posts_per_page' => '-1' );
// The Query
$the_query = new WP_Query( $args);
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
$MySum += get_post_meta($post_id, $key, true);
endwhile;
echo '<h1>' . $MySum . '</h1>';
// Reset Post Data
wp_reset_postdata();
?>