This is probably a stupid question, but I'm new to coding so here goes :-).
I'm trying to create a simple plugin for WordPress. The plugin gets data from a MySQL database and echos out a table with the results. My problem is when I use echo the plugin is places first on the page even if i put the shortcode in the middle of the page. I understand that is because I use echo instead of return. I just don't get how to use return in my case. Any help would be much appreciated :-).
Here's my code:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
echo '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
echo '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
echo '</tbody>
</table>';
}
add_shortcode( 'startlist', 'create_startlist' );
You want to assign your output to a variable, instead of echoing:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
$output = '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
$output .= '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
$output .= '</tbody>
</table>';
return $output;
}
add_shortcode( 'startlist', 'create_startlist' );
This uses concatenation to continue to fill the variable through your function. You then set the return to the $output variable.
Firstly read more about Shortcodes Output : https://codex.wordpress.org/Shortcode_API#Output
There are two ways that I can think of at this moment.
Using ob_start... basically you need to wrap you code in ob_start()
function create_startlist() {
ob_start();
/* CODE HERE */
return ob_get_clean();
}
Second is to use a concatenation operator
function create_startlist() {
$output = '';
$output .= 'OUTPUT HERE';
return $output;
}
Related
I am trying to retrieve data from wp database here with my plugin code below. I have manually added records in the db but my plugin doesn't want to retrieve my data. I don't know where am I going wrong here.
<?php
/**
* Plugin Name: Member Details
*/
function custom_view() {
global $wpdb;
echo '<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Bank</th>
<th>Account Number</th>
<th>Deposited Amount</th>
<th>Deposit Date</th>
<th>Period [Days]</th>
</tr>';
$results = $wpdb->get_results("select * from users");
foreach( $results as $user_data) {
// $roi = $user_data->amount * $user_data->period;
// $amount_growth = $roi - $user_data->amount;
echo "<tr>
<td>$user_data->user_nicename</td>
<td>$user_data->user_email</td>
<td>$user_data->bank</td>
<td>$user_data->account_num</td>
<td>$user_data->amount</td>
<td>$user_data->deposit_date</td>
<td>$user_data->period</td>
<td></td>
<td></td>
</tr>";
}
echo '</table>';
}
add_shortcode('views', 'custom_view');
?>
Can somebody help me here? Thanks
Two important things:
1° your data was not returning because you did not pass the table prefix, ie the table name was wrong.
Example "users" is correct "wp_users" or the prefix you used when creating in the database.
You can use the $wpdb->users variable which will automatically return it with the prefix you registered in wp
2° shortcodes must always end in a return and not in echo.
I left an example for you to call with php manually if you want to use it. but you can use it directly in the editor just by calling shortcode normally :)
If my answer helps you. Vote and put as right answer to close this question please :)
<?php
/**
* Plugin Name: Member Details
* Plugin URI: https://mysite.co.za
* Description: All Member Details List
* Version: 1.0
* Author: Empire Investment
* Author URI: https://mysite.co.za
*/
function custom_view() {
global $wpdb;
$output .= '<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Bank</th>
<th>Account Number</th>
<th>Deposited Amount</th>
<th>Deposit Date</th>
<th>Period [Days]</th>
</tr>';
$results = $wpdb->get_results("select * from $wpdb->users");
foreach( $results as $user_data) {
// $roi = $user_data->amount * $user_data->period;
// $amount_growth = $roi - $user_data->amount;
$output .= "<tr>
<td>$user_data->user_nicename</td>
<td>$user_data->user_email</td>
<td>$user_data->bank</td>
<td>$user_data->account_num</td>
<td>$user_data->amount</td>
<td>$user_data->deposit_date</td>
<td>$user_data->period</td>
<td></td>
<td></td>
</tr>";
}
$output .= '</table>';
return $output;
}
add_shortcode('views', 'custom_view');
//example usae with php
echo do_shortcode( $content, '[custom_view]' );
This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 5 years ago.
I have used dompdf to create pdf file, I have used a portion of the html file ie between to generate pdf . (cut & pasted manual way)
since I have a valid pdf out put now, I want to further automate the process,
I want to copy all contents between tables
<table> </table>
to a file, would like to know what would be possible options in php.
any suggestion is highly appreciated
Don't use regex, instead use DomDocument.
The following class will extract out the content between any element. So load your html from your file, or just pass it the contents of ob_get_contents()
<?php
class DOMExtract extends DOMDocument
{
private $source;
private $dom;
public function __construct()
{
libxml_use_internal_errors(true);
$this->preserveWhiteSpace = false;
$this->strictErrorChecking = false;
$this->formatOutput = true;
}
public function setSource($source)
{
$this->source = $source;
return $this;
}
public function getInnerHTML($tag, $id=null, $nodeValue = false)
{
if (empty($this->source)) {
throw new Exception('Error: Missing $this->source, use setSource() first');
}
$this->loadHTML($this->source);
$tmp = $this->getElementsByTagName($tag);
$ret = null;
foreach ($tmp as $v) {
if ($id !== null) {
$attr = explode('=', $id);
if ($v->getAttribute($attr[0]) == $attr[1]) {
if ($nodeValue == true) {
$ret .= trim($v->nodeValue);
} else {
$ret .= $this->innerHTML($v);
}
}
} else {
if ($nodeValue == true) {
$ret .= trim($v->nodeValue);
} else{
$ret .= $this->innerHTML($v);
}
}
}
return $ret;
}
protected function innerHTML($dom)
{
$ret = "";
foreach ($dom->childNodes as $v) {
$tmp = new DOMDocument();
$tmp->appendChild($tmp->importNode($v, true));
$ret .= trim($tmp->saveHTML());
}
return $ret;
}
}
$html = '
<h3>HTML Table Example</h3>
<div>
<table id="customers">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
</div>';
$dom = new DOMExtract();
$dom->setSource($html);
echo '
<table cellspacing="0" cellpadding="3" border="0" width="100%">',
//match and return only tables inner content with id=customers
$dom->getInnerHTML('table', 'id=customers'),
//match all tables inner content
//$dom->getInnerHTML('table'),
'</table>';
https://3v4l.org/OkbQW
<table cellspacing="0" cellpadding="3" border="0" width="100%"><tr><th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr><tr><td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr><tr><td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr><tr><td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr><tr><td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr><tr><td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr><tr><td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr></table>
Try This
To Extract Data between tags try this code
Here $source will be your complete html code. And $match will be the data extracted between tags.
Code:
preg_match("'<table>(.*?)</table>'si", $source, $match);
if($match) echo "result=".$match[1];
Reference: Preg match text in php between html tags
this is my controller
function search_keyword()
{
$cari = $this->input->GET('cari');
$data['dapat'] = $this->order_test_m->search($cari);
$this->load->view('admin/a',$data);
}
this is my model
function search($cari)
{
$this->db->from("uhd_user_order AS t1");
$this->db->join("uhd_user_product_order AS t2", "t1.user_order_id = t2.user_order_id");
$this->db->where('user_order_reference',$cari);
$query = $this->db->get('uhd_user_order');
return $query->result();
}
this is my view
<tr>
<th>No.</th>
<th>Customer Name</th>
<th>Product Code</th>
<th>Payment Type</th>
<th>Delivery Date</th>
<th>Total Price</th>
<th style="text-align: center;padding-right: 15px;">Action</th>
</tr>
<?php if($dapat !== NULL) { ?>
<?php foreach ($dapat as $row => $test) {
?>
<tr>
<td><?= $test->user_order_id?></td>
<td><?= $test->sender_name?></td>
<td><?= $test->user_product_order_id?></td>
<td><?= $test->payment_type ?></td>
<td><?= $test->time.$test->date ?></td>
<td><?= $test->delivery_price?></td>
</tr>
<?php }
}else{
echo "<td colspan='3'>no customer for the result!</td>";
}
?>
</table>
guys i need help here
im new in codeigniter.
i need to make a search but the search result are needing 2 table from my database. time, date and user_product_order_id are from the uhd_user_product_order, and user_order_id, sender_name, payment_type, and user_order_reference(this the search key) are from uhd_user_order
in the view i can view it from my table uhd_user_order, but i cant view the time, date and the user_product_order_id
can you help me how to join the 2 table so i can see the best result from the search
Use this code on your model
public function search($cari){
$this->db->select('*');
$this->db->from("uhd_user_order AS t1");
$this->db->join("uhd_user_product_order AS t2", "t2.user_order_id = t1.user_order_id"); # confirm user_order_id in both table
$this->db->where('user_order_reference',$cari);
$query = $this->db->get();
return $query->result();
}
function search($cari)
{
$this->db->from("uhd_user_order AS t1");
$this->db->join("uhd_user_product_order AS t2", "t1.user_order_id = t2.user_order_id");
$this->db->where('user_order_reference',$cari);
$query = $this->db->get('uhd_user_order');
return $query->result();
}
become
function search($cari)
{
$this->db->join("uhd_user_product_order" , "uhd_user_order.user_order_id = uhd_user_product_order.user_order_id");
$this->db->where('user_order_reference',$cari);
$query = $this->db->get('uhd_user_order');
return $query->result();
}
I have dynamically generated table in PHP but in response this table is not being created as datatable even i have used datatable plugin in file.
I have also one table that is generated on the page ready event with same schema and it has datatable behaviour.
so whats problem with dynamically generated table?
Plz Help
Thanks.
My code is as below :
ajax.php
$projectArr=$database->select("odeskuserdetails","OdeskUserId,UserName","IsDeleted=0");
$grand=0;
for($i=0;$i<count($projectArr);$i++){
$query="SELECT count(JobStatusId) as count from jobstatus where CreatedDate BETWEEN '".$_REQUEST['dateFrom']."' AND '".$_REQUEST['dateTo']."' and StatusId=3 and UserId in (SELECT UserId FROM odsekuserassignment where OdeskUserId =".$projectArr[$i]['OdeskUserId'].")";
$result= mysql_query($query);
$row= mysql_fetch_array($result);
$k=$i+1;
$projectArr[$i]['Sr.No.']=$k;
$projectArr[$i]['Total Jobs']=$row['count'];
$grand +=$row['count'];
}
// Sort the array by Total Jobs.
usort($projectArr, function ($a, $b) {
return ($b['Total Jobs'] - $a['Total Jobs']);
});
// Table Creation Starts :
echo '<table id="table2" class="tablesorter table table-bordered table-condensed table-hover table-striped" >
<thead>
<tr>
<th><center>Sr. No.</center></th>
<th><center>Odesk Account</center></th>
<th><center>Total Jobs Applied</center></th>
</tr>
</thead>
<tbody>';
if(is_array($projectArr))
{
$cval='0';
foreach ($projectArr as $data) {
if (!is_array($data)) {
if($cval=='0')
{
$cval ='1';
echo '<tr class="allPrjRow">';
echo '<td><center>'.$projectArr["Sr.No."].' </center></td>';
echo '<td><center>'.$projectArr["UserName"]. '</center></td>';
echo '<td><center>'.$projectArr["Total Jobs"].'</center></td>';
echo '</tr>';
} }
else
{
echo '<tr class="allPrjRow">';
echo '<td><center>'.$data["Sr.No."].'</center></td>';
echo '<td><center>'.$data["UserName"].'</center></td>';
echo '<td><center>'.$data["Total Jobs"].'</center></td>';
echo '</tr>';
}
}
echo '</tr>';
// print_r($x);
}
echo '</tbody>
</table>
<div id="gtotal" style="float: right;margin-right: 200px;">Grand Total :'.$grand.'</div>';
It depends on where you have put your code snippet. Place the code which creates dynamic table at the end,when all the js gets loaded.
I previously found a script while googling and used it for scrapping purpose, my main class
in my amazon.php, I wrote the following script
include('scrape.php');
set_time_limit(0);
$ASIN = 'B000GEM3RI';
$shipArray = shipingPrice($ASIN);
var_dump($shipArray);
print_r($shipArray);
echo $shipArray;
function shipingPrice($city){
$shipArray = array();
$scrape = new Scrape();
$url = 'http://www.amazon.com/gp/offer-listing/'.$city.'/ref=dp_olp_new?ie=UTF8&condition=new';
$scrape->fetch($url);
$data = $scrape->removeNewlines($scrape->result);
$data = $scrape->fetchBetween('<table cellspacing="0" cellpadding="0" width="100%" border="0"> <thead class="columnheader"><tr><th scope="col" class="price">Price + Shipping</th><th scope="col" class="condition">Condition</th><th scope="col" class="seller">Seller Information</th><th scope="col" class="readytobuy">Buying Options</th></tr></thead>','</table>',$data,true);
$rows = $scrape->fetchAllBetween('<tr','</tr>',$data,true);
$i=0;$j=0;
foreach ($rows as $row){
if($i!=0){
if($i!=2){
$record = array();
$cells = $scrape->fetchAllBetween('<td','</td>',$row,true);
$record['price'] = strip_tags($cells[0]);
if(stristr($record['price'],'oz')===False && stristr($record['price'],'/')===False)
{
$listPrice=$scrape->fetchBetween('$',' +',$record['price']);
}else{
$listPrice=$scrape->fetchBetween('$',' (',$record['price']);
}
//print_r($listPrice);
if($listPrice==''){
$listPrice=$scrape->fetchBetween('$',' &',$record['price']);
$shipPrice='0';
}else{
$shipPrice=$scrape->fetchBetween('+ $','s',$record['price']);
}
$shipPrice= floatval($shipPrice);
//####
$sellerIdInfo = $cells[2]; $sellerIdArray=$scrape->fetchAllBetween('&marketplaceSeller=0&seller=','"><b>',$sellerIdInfo);
if(count($sellerIdArray)>1){
$sellerId=$sellerIdArray[0];
}else{
$temp = explode('"id',$sellerIdArray[0]);
$sellerId=$temp[0];
}
//##
$sellerName =$scrape->fetchBetween('Seller:','Seller',$record['price']);
$sellerInfo=$scrape->fetchAllBetween('alt="','"',$cells[2],true);
$sellerName=str_replace(array('alt="','"'),array('',''),$sellerInfo[0]);
if($sellerName!=""){
//
}else{
$sellerName = $scrape->fetchBetween('<span class="sellerHeader">Seller:</span>','</b></a>',$cells[2],true);
$sellerName=str_replace("Seller:","",$sellerName);
$sellerName=$scrape->fetchBetween('<b>','</b>',$sellerName);
}
array_push($shipArray,array('sellerName'=>$sellerName,'sellerId'=>$sellerId,'price'=>$listPrice,'shipPrice'=>$shipPrice));
}
}
$i++;
}
return $shipArray;
}
the url for this scrip is amazon
when I echo it, var_dump it or print_r, an empty array is displayed, I checked the page using firebug and to me, looks like everything is okay in my code
can somebody tell me why I can access anything from the page although my code is okay?
thanks for helping me
EDIT:-
By adding return $this->result = curl_exec($ch); in my scrap class function fetch($url), I have assured that Page is being retrieved successfullly...
EDIT-2:-
after working on the advice as provided in answer, it tried
$shipArray[]=array('sellerName'=>$sellerName,'sellerId'=>$sellerId,'price'=>$listPrice,'shipPrice'=>$shipPrice);
in my function, but still the same empty array
EDIT-3
I changed the following function
function fetchBetween($needle1,$needle2,$haystack,$include=false){
$position = strpos($haystack,$needle1);
if ($position === false) { return ' it was null data'; }
when I echo echo $data; in my script file,
it was null data
is printed, so looks like this line of code $position = strpos($haystack,$needle1); is not working,
am I right?
if yes, what to do now?
Why are you defining a var as the result of a function that hasn't been defined yet?
$shipArray = shipingPrice($ASIN);
var_dump($shipArray);
print_r($shipArray);
echo $shipArray;
ShippingPrice function is lower in the code. IE shipArray will be empty
Gotcha, I was correct, issue was not with my code
on line
$data = $scrape->fetchBetween('<table cellspacing="0" cellpadding="0" width="100%" border="0"> <thead class="columnheader"><tr><th scope="col" class="price">Price + Shipping</th><th scope="col" class="condition">Condition</th><th scope="col" class="seller">Seller Information</th><th scope="col" class="readytobuy">Buying Options</th></tr></thead>','</table>',$data,true);
there was an extra space border="0"> <thead class, that was creating issue, once, I removed this the space from
<table cellspacing="0" cellpadding="0" width="100%" border="0"><thead class="columnheader">
my code became okay..
thanks to everyone