It's my index.php:
<?php
$maxlinks = 4;
$paginaAtual = (isset($_GET['paginaAtual'])) ? (int)$_GET['paginaAtual'] : 1;
$maximo = 5;
$inicio = (($maximo * $paginaAtual) - $maximo);
$publicacoesUN = DBRead('publicacao', "ORDER BY id DESC LIMIT $inicio, $maximo");
$post = empty($_GET['post']) ? '' : $_GET['post'];
$pagina = empty($_GET['p']) ? 'home' : $_GET['p'];
if ($post != '' || ($post == '' && $pagina != '')) {
switch ($pagina):
case 'home':
$titulo = '';
$shareTitulo = '';
$descricao = '';
$shareDescricao = '';
$shareImg = '';
$keywords = '';
$ogUrl = '';
$urlCanonico = '';
break;
case 'ultimasnoticias':
$titulo = '';
$shareTitulo = '';
$descricao = '';
$shareDescricao = '';
$shareImg = '';
$keywords = '';
$ogUrl = '';
$urlCanonico = '';
break;
default:
$titulo = 'Home';
$pagina = 'home';
endswitch;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<nav>
<ul>
<li>
Página Inicial
</li>
<li>
Últimas Notícias
</li>
</ul>
</nav>
<?php
if (empty($post)) {
require_once 'page_' . $pagina . '.php';
} else {
require_once 'posts/' . $post . '.php';
}
?>
</body>
</html>
And my ultimasnoticias.php:
<div class="container my-3">
<div class="row">
<?php foreach ($publicacoesUN as $UN): ?>
<div class="col-12 col-md-6 col-lg-3 mb-3 mb-md-3">
<div class="card">
<div class="img-container">
<img src="<?php echo $UN['capa']?>" alt="<?php echo $UN['alt']?>" class="card-img-top" id="imgUNcover">
</div>
<div class="card-body">
<h1 class="cardTitleUN"><?php echo $UN['title']?></h1>
<p class="card-text text-muted"><?php echo $UN['text']?></p>
Continue Lendo
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=publicacoes', 'root', '');
$seleciona_2 = $pdo->prepare("SELECT * FROM `bn_publicacao`");
$seleciona_2->execute();
$total = $seleciona_2->rowCount();
$total_paginas = ceil($total/$maximo);
if($total > $maximo){
echo 'First page';
for ($i = $paginaAtual - $maxlinks; $i <= $paginaAtual -1; $i++) {
if ($i >= 1) {
echo ''.$i.'';
}
}
echo '<span>'.$paginaAtual.'</span>';
for ($i= $paginaAtual +1; $i <= $paginaAtual + $maxlinks; $i++) {
if ($i <= $total_paginas) {
echo ''.$i.'';
}
}
echo 'Last page';
}
?>
When i click on the link of the pagination like 1, 2, first page, last page...etc, it redirects to the home page. If i put the whole script from the file ultimasnoticias.php into the file index.php the pagination works.
This pagination script works for a static website, but it's not working on a server-side. How can i solve this?
I recommend you use this class! It's excellent. It does it all for you!
https://github.com/daveismyname/pagination
An example of its use (MVC format):
$pages = new Paginator('10','p');
$pages->set_total( $this->support->countAllFaq() );
$getAllFaq = $this->support->getAllFaq($pages->get_limit());
if($getAllFaq == false) { $count = 0; } else { $count = count($getAllFaq); }
$pageLinks = $pages->page_links();
The database queries:
public function countAllFaq()
{
$sql = 'SELECT f.name, f.content, f.date, f.status, f.cat_id, c.id, c.name AS catname FROM chewi_support_faq f LEFT JOIN chewi_support_categories c ON f.cat_id = c.id WHERE f.status = 1';
$results = $this->db->selectExtended($sql);
$totalRows = count($results);
if($results === FALSE){ $totalRows = '0'; }
return $totalRows;
}
public function getAllFaq($limit)
{
$sql = 'SELECT f.id, f.name, f.content, f.date, f.status, f.cat_id, c.id AS cat_id, c.name AS catname FROM chewi_support_faq f LEFT JOIN chewi_support_categories c ON f.cat_id = c.id WHERE f.status = 1 ORDER BY f.cat_id DESC '.$limit;
$results = $this->db->selectExtended($sql);
return $results;
}
Related
I need to change the div's class name based on if condition below it.
i have tried as <div class="<?php echo $class_name; ?>">
I want the class name to be "class name 1" or "class name 2" based on a if condition like if submitted and correct answer are same, i want the class name to be class_name1 or else it should be class_name2. The code is as follows:
<element class="col-sm-6 col-aligncenter">
<!--<div class="pipeline white lined-success"> -->
<div class="<?php echo $class_name; ?>">
<div class="pipeline-header">
<h5>
<b><?php echo $count++;?>. <?php echo $question_type == 'fill_in_the_blanks' ? str_replace('^', '__________', $question_title) : $question_title;?></b>
</h5>
<span><?php echo get_phrase('mark');?>: <?php echo $mark;?></span>
</div>
<?php if ($question_type == 'multiple_choice'):
$options_json = $this->crud_model->get_question_details_by_id($row['question_bank_id'], 'options');
$number_of_options = $this->crud_model->get_question_details_by_id($row['question_bank_id'], 'number_of_options');
if($options_json != '' || $options_json != null)
$options = json_decode($options_json);
else $options = array();
?>
<ul>
<?php for ($i = 0; $i < $number_of_options; $i++): ?>
<li><?php echo $options[$i];?></li>
<?php endfor; ?>
</ul>
<?php
if ($row['submitted_answer'] != "" || $row['submitted_answer'] != null)
{
$submitted_answer = json_decode($row['submitted_answer']);
$r = '';
for ($i = 0; $i < count($submitted_answer); $i++)
{
$x = $submitted_answer[$i];
$r .= $options[$x-1].',';
}
} else {
$submitted_answer = array();
$r = get_phrase('no_reply');
}
?>
<i><strong>[<?php echo get_phrase('answer');?> - <?php echo rtrim(trim($r), ',');?>]</strong></i>
<br>
<?php
if ($row['correct_answers'] != "" || $row['correct_answers'] != null) {
$correct_options = json_decode($row['correct_answers']);
$r = '';
for ($i = 0; $i < count($correct_options); $i++) {
$x = $correct_options[$i];
$r .= $options[$x-1].',';
}
} else {
$correct_options = array();
$r = get_phrase('none_of_them.');
}
?>
<i><strong>[<?php echo get_phrase('correct_answer');?> - <?php echo rtrim(trim($r), ',');?>]</strong></i>
<?php elseif($question_type == 'true_false'):
if ($row['submitted_answer'] != "") {
$submitted_answer = get_phrase($row['submitted_answer']);
}
else{
$submitted_answer = get_phrase('no_reply');
}
?>
<i><strong>[<?php echo get_phrase('answer');?> - <?php echo get_phrase($submitted_answer);?>]</strong></i><br>
<i><strong>[<?php echo get_phrase('correct_answer');?> - <?php echo get_phrase($row['correct_answers']);?>]</strong></i>
**div's class should change based on if answer and correct answer are equal**
There are two types of questions (multiple choice and true or false). It should behave same for both type of questions.
I am trying to do pagination in my php file fetch_data.php which is called from a ajax function in index.php but it is not showing the required result
Here is my code from fetch_data.php
<?php
require 'dbserver.inc.php';
$query = "
SELECT * FROM detail WHERE status = '1'
";
$result = mysqli_query($conn,$query);
$number = mysqli_num_rows($result);
$results_per_page = 1;
$number_of_pages = ceil($number/$results_per_page);
if (!isset($_GET['page'])) {
$page = 1;
echo"1";
} else {
echo"2";
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
if(isset($_POST["action"]))
{
$query = "
SELECT * FROM detail WHERE status = '1'
AND LIMIT" . $this_page_first_result . ',' . $results_per_page ;
if(isset($_POST["jobtype"]))
{
$jobtype_filter = implode("','", $_POST["jobtype"]);
$query .= "
AND Job IN('".$jobtype_filter."')";
}
if(isset($_POST["salary"]))
{
$salary_filter = implode("','", $_POST["salary"]);
$query .= "
AND Salary IN('".$salary_filter."')";
}
if(isset($_POST["category"]))
{
if($_POST["category"] == 'Choose Category')
{
$query .= "";
}
else
{
$category = $_POST["category"];
$query .= "
AND JobCat like('".$category."')";
}}
if(isset($_POST["location"]))
{
if($_POST["location"] == 'Choose Location')
{
$query .= "";
}
else
{
$location = $_POST["location"];
$query .= "
AND City like('".$location."')";
}}
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_assoc($result)){
echo'
<!-- Single Employers List -->
<div class="candidate-list-layout" >
<div class="cll-wrap">
<div class="cll-thumb">
<a href="company-detail.html">';?>
<img class="img_responsive" alt="" src="data:image/jpg;charset=utf8;base64,<?php echo base64_encode($row['Logo']); ?>" /> <?php echo'</a>
</div>
<div class="cll-caption">
<h4>'.$row['Name'].'<span><i class="ti-briefcase"></i>'.$row['Title'].'</span></h4>
<ul>
<li><i class="ti-location-pin cl-danger"></i>'.$row['City'].' fetch ,'.$row['Country'].'</li>
<li><i class="ti-medall cl-success"></i>Established: 1984</li>
</ul>
</div>
</div>
';}
echo'<div class="row mrg-0">
<ul class="pagination">';
for($page = 1 ; $page<=$number_of_pages;$page++){
echo'
<li class="active">'.$page.'</li>
';}
echo' <li><i class="fa fa-ellipsis-h"></i></li>
</ul>
</div>';
}
?>
i want to filter the data a also due to which i have to include these other lines of codes and it is also not redirercting to other page except the one it is currently in and when included these filter code it is showing boolean error on mysqli_query too.
i have 3 table T1, T2, T3,
so, in T1 i want to select 1st row and select from T2 the rows related to the row selected in T1, and select from T3 rows related to T2 how have relation with row selected in T1 and print all this in one continer withe php while loop function
see the images for more descriptions
Base on what I understand with your question. This could be the answer
<?php
$db = new PDO("mysql:host=localhost", "username", "password");
$q1 = $db->prepare("SELECT * FROM T1");
$q1->execute();
$f1 = $q1->fetchAll(PDO::FETCH_ASSOC);
foreach ($f1 as $f1_items) {
echo "<tr><td>".$f1['id_cat']."</td></tr>";
$q2 = $db->prepare("SELECT * FROM T2 WHERE id_cat = ".$f1['id_cat'].";");
$q2->execute();
$f2 = $q2->fetchAll(PDO::FETCH_ASSOC);
foreach ($f2 as $f2_items) {
echo "<tr><td>\t".$f2['id_tr']."</td></tr>";
$q3 = $db->prepare("SELECT * FROM T3 WHERE id_tr = ".$f2['id_cus'].";");
$q3->execute();
$f3 = $q3->fetchAll(PDO::FETCH_ASSOC);
foreach ($f3 as $f3_items) {
echo "<tr><td>\t\t".$f2['id_cus']."</td></tr>";
}
}
}
?>
Solved and this is the code i am happy :)
$ReqFindRows = "SELECT * FROM commandes WHERE commande_status = 0 AND date(commande_le) = CURDATE()";
$STMTFindRows = $connect->stmt_init();
if(!$STMTFindRows->prepare($ReqFindRows)){
echo "No Results";
}
else {
$STMTFindRows->execute();
$ResultsFindRows = $STMTFindRows->get_result();
$x = 0;
while($ArrayCat = $ResultsFindRows->fetch_assoc()){
switch($ArrayCat['commande_importance']){
case 0 :
$importance = 'Normal';
$bgclas = "bg-blue";
break;
case 1 :
$importance = 'Urgent';
$bgclas = "bg-yellow";
break;
case 2 :
$importance = 'Immediat';
$bgclas = "bg-red";
break;
};
$prods = array();
$GetProductsInCommandeQuery = "SELECT * FROM commandes_produits WHERE commande_id = ?";
$GetProductsInCommandeSTMT = $connect->stmt_init();
if(!$GetProductsInCommandeSTMT->prepare($GetProductsInCommandeQuery)){
echo $connect->error;
}
else {
$id_toserch = $ArrayCat["commande_id"];
$GetProductsInCommandeSTMT->bind_param("s", $id_toserch );
$GetProductsInCommandeSTMT->execute();
$GetProductsInCommandeResults = $GetProductsInCommandeSTMT->get_result();
$Prodss = "";
while($GetProductsInCommandeArray = $GetProductsInCommandeResults->fetch_array()){
$prods = $GetProductsInCommandeArray["recette_id"];
$GetSupQuery = "SELECT * FROM commandes_supp WHERE tr_number = ? AND commande_id = ?";
$GetSupSTMT = $connect->stmt_init();
if(!$GetSupSTMT->prepare($GetSupQuery)){
echo $connect->error;
}
else {
$trNumber = $GetProductsInCommandeArray["tr_number"];
$GetSupSTMT->bind_param("ss", $trNumber, $id_toserch );
$GetSupSTMT->execute();
$GetSupResults = $GetSupSTMT->get_result();
$Supp = "";
while($GetSupArray = $GetSupResults->fetch_array()){
$Suppss = $GetSupArray["supp_id"];
$Supp .= '<p style="color:#F00">'.$Suppss.' </p>';
}
}
$Prodss .=
'<tr>
<td>
'.$prods.'
'.$Supp.'
</td>
<td>
A table
</td>
<td>
<button type="button" class="btn btn-sm">Servis</button>
</td>
</tr> ';
}
}
?>
<div class="col-xs-6 col-md-4" style="margin-bottom:10px;">
<div class="tiket">
<div class="tikeheader <?php echo $bgclas ?>">
<span class="commandenumber">
<i class="fa fa-star iconheader">
</i>
<?php echo $ArrayCat["commande_id"] ?> A Table
</span>
<span class="importance">
<?php echo $importance?>
</span>
</div>
<div class="tiketbody">
<table class="tiketbodytable">
<tbody>
<?php echo $Prodss ?>
</tbody>
</table>
</div>
</div>
</div>
<?php
}
}
?>
</div>
</div>
</div>
</div>
<?php
}
?>
I have a function called getNews().
I call getNews() like this:
<div class="wrapper" id="blog">
<div class="blogPosts">
<?PHP getNews($postPerPage, 0, $theme_link, $pageNum); ?>
</div>
</div>
The function works until it tries to get the article text from wordpress using get_post_field().
function getNews($numPosts, $offset, $theme_link, $pageNum) {
$offset = $numPosts * $pageNum;
$recent_args = array('numberposts' => $numPosts, 'offset' => $offset,);
$articles = wp_get_recent_posts($recent_args);
foreach($articles as $article){
$article_id = $article['ID'];
...
echo $article_text = get_post_field('post_content', $article_id);
...
}
}
When I run this, I get the error saying Fatal error: Cannot redeclare getNews() (previously declared in /homepages/30/d545089862/htdocs/VintageTroubleMusic/wp-content/plugins/enhanced-text-widget/enhanced-text-widget.php(57)
For some reason, it's running my loop twice.
Any advice?
EDIT
I'm including the full code here: This is written inside of an "Enhanced Text widget" inside of a page.
<?PHP
$theme_link = "/wp-content/themes/thestory-child/";
$pageNum = $_GET['pa'];
$postPerPage = 27;
$qry_numPosts = mysql_query("SELECT * FROM Ykcfdlqhposts WHERE post_status = 'publish' AND post_type = 'post'") or die(mysql_error());
$numPosts = mysql_num_rows($qry_numPosts);
$numPages = ceil($numPosts/$postPerPage) . " pages";
if(!$pageNum){
$pageNum = 0;
}
?>
<!-- START OF THE BODY HERE -->
<h3 class="widget-title" style="float:left;">Headlines</h3>
<div class="wrapper" id="paginate1">
<?PHP paginate($numPosts, $numPages); ?>
</div>
<div class="wrapper" id="blog">
<div class="blogPosts">
<?PHP getNews($postPerPage, 0, $theme_link, $pageNum); ?>
</div>
</div>
<div class="wrapper" id="paginate2">
<?PHP paginate($numPosts, $numPages); ?>
</div>
And inside of the functions.php page
function getNews($numPosts, $offset, $theme_link, $pageNum) {
$offset = $numPosts * $pageNum;
$recent_args = array('numberposts' => $numPosts, 'offset' => $offset,);
$articles = wp_get_recent_posts($recent_args);
foreach($articles as $article){
$article_id = $article['ID'];
$article_link = get_permalink($article_id);
$article_length = 350;
$article_background = get_the_post_thumbnail($article_id);
$article_title = get_post_meta( $article_id, 'short_title', true );
$article_text = "test";
$article_text = get_post_field('post_content', $article_id);
//$article_text = get_post_field('post_content', $article_id);
//$article_text = strip_tags($article_text);
//$article_text_length = strlen($article_text);
/*
if($article_text_length >= $article_length) {
$article_text_pos = strpos($article_text, " ", $article_length);
$article_text = substr($article_text, 0, $article_text_pos)."... ";
}
*/
?>
<div class="article">
<?PHP //Get the article image
if (!$article_background) {
$rand = rand(1, 5);
$img = $theme_link . "images/img" . $rand . ".jpg";
} else {
$img = explode('src="', $article_background);
$img = explode(".jpg", $img[1]);
$img = $img[0] . ".jpg";
}?>
<a href="<?= $article_link; ?>">
<div class="article__image" style="background-image: url('<?= $img; ?>');"></div>
<div class="article__title"><?= $article_title; ?></div>
</a>
<div class="article__details">
<div class="article-text">
<?= $article_text; ?>
</div>
READ MORE
</div>
</div>
<? }
}
function paginate($numPosts, $numPages) {
?>
<div class="page">
<span>Page:</span><?PHP
$i = 0;
while($i < $numPages){
$i++;
if($i == $pageNum){
echo '<span style="background-color:transparent; text-decoration:underline; color:white; cursor:default;">'.$i.'</span>';
} else {
echo "<a href='?pa=".$i."'><span>".$i."</span></a>";
}
}
?>
</div>
<?
}
I currently pull through data from a soap feed using this PHP, is there anyway for me to have the results ordered from high to low using the data from $weekrent?
Any help would be great! Here is my PHP code:
<?php
$wsdl = "http://portal.letmc.com/PropertySearchService.asmx?WSDL";
$client = new SoapClient($wsdl, array ("trace"=>1, "exceptions"=>0));
$strClientID = "{0050-e58a-cd32-3771}";
$strBranchID = "{0004-e58a-cd32-399e}";
$strAreaID = $_GET['area'];
$nMaxResults = $_GET['perpage'];
$nRentMinimum = $_GET['minrent'];
$nRentMaximum = $_GET['maxrent'];
$nMaximumTenants = $_GET['numtennants'];
$parameters = array( "strClientID"=>$strClientID,
"strBranchID"=>$strBranchID,
"strAreaID"=>$strAreaID,
"nMaxResults"=>$nMaxResults,
"nRentMinimum"=>$nRentMinimum,
"nRentMaximum"=>$nRentMaximum,
"nMaximumTenants"=>$nMaximumTenants
);
$values = $client->SearchProperties($parameters);
if(!is_array($values->SearchPropertiesResult->PropertyInfo))
{
$values->SearchPropertiesResult->PropertyInfo = array($values->SearchPropertiesResult->PropertyInfo);
}
if($values != '')
{
foreach ($values->SearchPropertiesResult->PropertyInfo as $message)
{
$uglyid = $message->ID;
$id = $message->FriendlyID;
$mainphoto = $message->MainPhoto->PhotoUrl;
$furnished = $message->Furnished;
$addressline1 = $message->Address1;
$rooms = $message->MaxTenants;
$rent = $message->Rent;
$description = $message->Description;
$isletagreed = $message->IsLetAgreed;
$facilities = $message->Facilities->FacilityInfo;
$photos = $message->Photos->PhotoInfo;
$roomsinfo = $message->Rooms->RoomInfo;
$facilitiesstring = serialize($facilities);
$extractnumbers = ereg_replace("[^0-9]", "", $rent);
$monthrent = ($extractnumbers) / $rooms;
$monthrentrounded = number_format(($monthrent/100),2);
$weekrent = ($monthrentrounded) * 12 / 52;
$weekrentrounded = floor($weekrent * 100) / 100;
$roomsinfojson = json_encode($roomsinfo);
$facilitiesjson = json_encode($facilities);
$roomsinfodouble = (substr_count(strip_tags($roomsinfojson),"Double"));
$roomsinfosingle = (substr_count(strip_tags($roomsinfojson),"Single"));
$roomsinfobathroom = (substr_count(strip_tags($roomsinfojson),"Bathroom"));
$roomsinfoshower = (substr_count(strip_tags($roomsinfojson),"Shower"));
$facilitiesparking = (substr_count(strip_tags($facilitiesjson),"Parking"));
$facilitiesgarden = (substr_count(strip_tags($facilitiesjson),"Garden"));
$totalbathrooms = $roomsinfobathroom + $roomsinfoshower;
$totalimages = count($photos);
echo '
<div class="col-property-box col-property-box-1-3">
<div class="owl-property-box">';
$i=0; foreach ($photos as $data) { if($i==4) break; echo '<div class="property-grid-box-picture" style="background: url('. $data->PhotoUrl .') center center;"></div>'; $i++; };
echo '</div>
<div class="property-grid-box">
'. $addressline1 .'
<p class="property-grid-box-text">'. limit_words($description,19) .'...</p>
<div class="property-grid-box-price">
<div class="section group">
<div class="col col-property-box-1-2 property-grid-box-price-border-right">
<div class="property-grid-box-price-top">£'. $weekrentrounded.'pp</div> <div class="property-grid-box-price-under">Weekly</div>
</div>
<div class="col col-property-box-1-2">
<div class="property-grid-box-price-top">£'. $monthrentrounded .'pp</div> <div class="property-grid-box-price-under">Monthly</div>
</div>
</div>
</div>
<div class="property-grid-box-icon-box">
<div class="section group">
<div class="col col-1-3-border no-left-border">
<span class="property-grid-box-number-icon"><center><i class="fa fa-bed"></i></center><div class="property-grid-box-number-text">'. $rooms .'</div></span>
</div>
<div class="col col-1-3-border">
<span class="property-grid-box-number-icon"><center><i class="flaticon-shower5"></i></center><div class="property-grid-box-number-text">'. $totalbathrooms .'</div></span>
</div>
<div class="col col-1-3-border">
<span class="property-grid-box-number-icon"><center><i class="flaticon-beds12"></i></center><div class="property-grid-box-number-text">'. $totalimages .'</div></span>
</div>
</div>
</div>
</div>
</div>
';
}
}
function limit_words($string, $word_limit)
{
$words = explode(" ",$string);
return implode(" ",array_splice($words,0,$word_limit));
}
?>
you can use usort function .. so you get the sorted result
Read more on php
You can put your messages data to temporary array along with calculated weekrent and then sort desc by weekrent value with usort
if($values != '')
{
$arrayForSort = array();
foreach ($values->SearchPropertiesResult->PropertyInfo as $message) {
$rent = $message->Rent;
$rooms = $message->MaxTenants;
$extractnumbers = ereg_replace("[^0-9]", "", $rent);
$monthrent = ($extractnumbers) / $rooms;
$monthrentrounded = number_format(($monthrent/100),2);
$weekrent = ($monthrentrounded) * 12 / 52;
$arrayForSort[] = array('weekrent' => $weekrent, 'message' => $message);
}
usort($arrayForSort, function($a, $b) {
if ($a['weekrent'] == $b['weekrent']) {
return 0;
}
return ($a['weekrent'] > $b['weekrent']) ? -1 : 1;
});
foreach ($arrayForSort as $item)
{
$message = $item['message'];
// Your code here to proper process the message ...