PHP - Show results, conditional based on link - php

Looking for some help with the code below. I think there may be an issue with the way I've organized the php call and function calls. I'm a beginner and am trying to allow users to display results from different tables, depending on what link they click.
I get this error:
Parse error: syntax error, unexpected '{' in /home/content/c/e/l/celebrything/html/wp-content/themes/celebrything/sidebar.php on line 16
Any help in correcting the issue here would be amazing. Here's the code:
<div id="sidebar">
<div class="post">
<h2>
<font color="#333333">Most Popular Celebrities</font><br>
<font color="#333333">in last 24 hours</font>
<br>
<br>
Today
Week
Month
<?php
if (!in_array($table, array('today', 'week', 'month')) {
return false;
}
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_' . $table);
foreach($result as $row) {
echo '<a href="http://www.celebrything.com/?s=' .
urlencode($row->name) . '&search=Search">' . $row->name .
'</a> - ' . $row->count . ' Posts<br/>';
}
}
?>
showTable($_GET['table']);
</h2>
</div>
</div>
<div class="clear"></div>
UPDATED CODE----------------
<div id="sidebar">
<div class="post">
<h2>
<font color="#333333">Most Popular Celebrities</font><br>
<font color="#333333">in last 24 hours</font>
<br>
<br>
Today
Week
Month
<?php
if (!in_array($table, array('today', 'week', 'month'))) {
return false;
}
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_' . $table);
foreach($result as $row) {
echo '<a href="http://www.celebrything.com/?s=' .
urlencode($row->name) . '&search=Search">' . $row->name .
'</a> - ' . $row->count . ' Posts<br/>';
}
if (!empty($_GET['table'])) {
showTable($_GET['table']);
} else { showTable('today'); }
?>
</h2>
</div>
</div>
<div class="clear"></div>

1. Missing a ) on the first if block
if (!in_array($table, array('today', 'week', 'month'))) {
return false;
}
2. There is an extra } right before the closing ?>
}
}
?>
3. You need to put the showTable function before the closing ?> like:
showTable($_GET['table']);
?>
In Summary:
Get a code editor that supports syntax highlighting. You will love it.

Looks to me like you're referencing a function -- showTable() -- but you haven't set up your logic inside function (unless you're leaving something out of the code sample). Should be:
<?
//----------------------
//Create the showTable() function, which won't do anything until it's called. It can
//reside anywhere on the page, really. It's here just because this is where I put it.
function showTable($table) {
if (!in_array($table, array('today', 'week', 'month'))) {
return false;
}
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_' . $table);
foreach($result as $row) {
echo(''.$row->name.' - '.$row->count.' Posts<br/>');
}
}
//----------------------
//Here is where you actually call the function, to display some stuff on the page
if (!empty($_GET['table'])) {
showTable($_GET['table']);
} else {
showTable('today');
}
?>
The code above assumes that you're using proper/working functions built into Wordpress (I don't know Wordpress very well). But the syntax above should clear up any function syntax related issues, which I think is your main issue.

Related

PHP function called on link click not giving any results

I'm trying to solve this for some time. I have PHP function that is called on link click. When I click on link it's directing me to this function but it's not giving any results.
Here is how I call function.
foreach ($bandsN as $aa) {
$str = explode(',', $aa);
$next = $str[1];
?>
<?php echo $str[0]?> </div> <?php
if (isset($_GET['other'])) {other($next);}
}
In this function it's called mysql stored procedure with parameter of php function.
function other($var)
{
echo $var;
if (!$mysqli->multi_query("CALL p($var)")) {
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do{
if($resul = $mysqli->store_result()){
$bands = array();
while($ro = $resul->fetch_row())
{
$bands[] = implode(',', $ro);
}
foreach ($bands as $aa) { ?>
<p > <?php echo $aa?> </p> </div><?php
}
$resul->free();
unset($bands);
}}
while($mysqli->more_results() && $mysqli->next_result());
}
I don't know which is the problem. This code inside function is working because I already have it in other part of app.
If somebody can see what is wrong I would be very grateful.

Using same php files with include erease the main page

everyone. The deal is I'm trying to do an overflow-x=scroll show for products in a company and show productos there using a database with php. Everything was fine, I pack the code of it in an eternal php file and try to use it twice with include. The main idea is to only chance the sql of the second include and respective querySelect file to avoid writing the code twice. The PROBLEM is that when I include the 2 files the first one content doesnt show neither the second one and everything that's after it. The code is something like:
<div>Div with some content<div>
<?php require ("productos.php"); ?>
<div>Div with some content<div>
<?php require ("productos1.php"); ?>/*This file will be the same as the other but with different sql*/
<div>Guest what? More divs<div>
What does the php file has? Well it's:
<?php
require "querySelect.php";
$productos = new columnas();
$array_productos = $productos->get_items();
foreach ($array_productos as $value) {
echo
'<div class="card">
<img data-toggle="modal" data-target="#exampleModal" data-nombre="' . $value["NOMBRE"] . '" data-imagen="' . $value["IMAGEN"] . '" data-color="' . $value["COLOR"] . '" data-peso="' . $value["PESO"] . '" data-tiempo="' . $value["TIEMPO"] . '" data-observaciones="' . $value["OBSERVACIONES"] . '" class="card-img-top" src="' . $value["IMAGEN"] . '" alt="Card image cap">
<div class="card-block p-3">
<h4 class="card-title">' . $value["NOMBRE"] . '</h4>
<p class="card-text">' . $value["DESCRIPCION"] . '</p>
<!-- Go somewhere -->
</div>
</div>';
}
?>
The querySelect.php is:
<?php
require "conexion.php";
class columnas extends conexion {
public function columnas() {
parent::__construct();
}
public function get_items() {
$sql = "SELECT * FROM primaproductos";
$sentencia = $this->conexion_db->prepare($sql);
$sentencia->execute(array());
$resultados = $sentencia->fetchAll(PDO::FETCH_ASSOC);
$sentencia->closeCursor();
return $resultados;
$this->conexion_db = null;
/*$resultados = $this->conexion_db->query('SELECT * FROM post');
$productos = $resultados->fetch_all(MYSQLI_ASSOC);
return $resultados;*/
}
}
?>
Last file:
<?php
require "config.php";
class conexion {
protected $conexion_db;
public function conexion() {
//--------------PDO-------------------------------------------------------------------
try {
$this->conexion_db = new PDO('mysql:host=###; dbname=###', '###', '###');
$this->conexion_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conexion_db->exec("SET CHARACTER SET utf8");
return $this->conexion_db;
} catch (Exception $e) {
echo "La linea de error es: " . $e->getLine();
}
}
?>
Files : [ Conexion.php , ( querySelect.php check the return statement.. ) ] i suppose are okay.
I think you're using bootstrap 4, so you should have a good structure before, i mean..
<div class="container-fluid">
<div class="row no-gutters">
<!-- HERE THE CARD ELEMENT, so
http://php.net/manual/en/function.require-once.php
-->
<?php require_once('productos.php'); ?>
<!-- And div with class col-12 or whatever you want per item -->
</div>
</div>
Productos.php
I think your mistake gonna be here too i mean..
Check elements before..
if ( !empty($array_productos) ) {
//The foreach
foreach ($array_productos as $value) {
echo '<div class="col-12">'.$value["nombre"].PHP_EOL.'</div>';
}
};
I hope this help to you =)

join query with bonfire (codeigniter)

I'm trying to do a join query in bonfire (which is great for the beginner i am btw)
I first tried to set a public function in the method, but after a while, i though it would be better to put it in the controller (maybe i'm wrong...?)
However, i guess my join request is valid, but i can't get it in my view...
Here is my controller:
class Patient extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('post_model');
Template::set_block('search/search', 'search/search');
//Template::set('toolbar_title', 'Manage Your Blog');
Template::set_theme('custom', 'default');
Template::set_block('nav', 'nav');
}
public function detail($id = null) {
$this->load->helper('typography');
$this->load->model('operation_model');
$this->db->select('*');
//$this->db->from ('operation AS ope');
$this->db->from('operation');
$this->db->join('patient', "patient.zkp_pat = operation.zkf_pat ");
$query = $this->db->get();
$post = $this->post_model->find($id);
//Template::set('post', $query);
Template::set('post', $post);
Template::set_view('detail');
Template::render();
}
}
And my view file:
<code>
<div class="post">
<?php
echo ($post->nom . ' ');
echo ($post->prenom . ' ');
echo ($post->zkp_pat . ' ');
echo ($post->dob);
foreach ($query as $row) :
echo ($row->zkf_pat . ' ' );
echo "titre de l'opération: " . ($row->titre);
endforeach;
?>
</div>
</code>
Thanks for your advices and help !
I asked for help on the BF forum too, and somebody gave me the solution=>hopefully this will help somebody else. The issue was with the $query , which is a DB_result object.
http://www.codeigniter.com/user_guide/database/query_builder.html#selecting-data
to solve the problem i had to doo: $query->result()
Final code:
Controller:
public function detail ($id = null){
$this->load->helper('typography');
$this->db->from ('operation as ope');
$this->db->join ('patient',
"patient.zkp_pat = ope.zkf_pat " );
$this->db->where ('patient.zkp_pat', $id);
$query = $this->db->get();
$post = $this->post_model->find($id);
Template::set('query', $query);
Template::set('post', $post);
Template::set_view('detail');
Template::render()
}
And view file:
<div class="post">
<h2><?php e($post->nom); ?></h2>
<?php
echo ($post->nom . ' '); echo ($post->prenom . ' ');
echo($post->zkp_pat . ' ');
echo ($post->dob);
foreach ($query->result() as $row) :
echo '<div>'
echo " \n";
echo ($row->zkf_pat . ' ');
echo "titre de l'opération: " . ($row->titre);
?>
</div>
<?php
endforeach;
?>
</div>
$query->get()->result() returns an object with all fetched data,
whereas $query->get()->row()returns only a single result row, if the result has one row, it returns only the first one. The result is given as an object...
If you like my edit, please upvote, that would be very helpful !

Magento - How do you return results of unlimited CMS Static blocks (with certain "Identifier") to a CMS Page

Quick Overview: I am trying to return results from a specific set of static blocks to a phtml file (which is then called on from a cms page) in Magento.
Note: I've been searching all over google and some answers get me closer than others but nothing I've tried seems to work 100%?
Details:
I already have a set of specific static blocks that all start with an identifier of testimonial-. For example, each static block is like this: testimonial-1, testimonial-2, testimonial-3 and so on. I have a total of 5 on my dev site (more on live site but that is no consequence here).
I have a CMS Page with code pulling in the name.phtml file (location of my phtml file is here: app/design/frontend/[package]/[template]/template/page/):
{{block type="core/template" template="page/name.phtml" title="Others Say:" identifier="testimonial-"}}
Here is my code for the .phtml file:
<?php
// add the collection with filters
$collection = Mage::getModel('cms/block')->getCollection()
->addFieldToFilter('identifier', array('like'=>'testimonial'.'%'))
->addFieldToFilter('is_active', 1);
// get the count
$blockCount = $collection->count();
echo 'Block Count: ' . $blockCount . '<br />'; // just for testing
$blockNum = 1;
foreach($collection as $key => $value){
$_blockId = $this->getIdentifier();
$block_ID = $_blockId . $blockNum;
echo "Key: " . $key . " - " . "Block ID: " . $block_ID . "<br />";
$blockNum++;
}
$_block = $this->getLayout()->createBlock('cms/block')->setBlockId($block_ID);
if ($_block) :
?>
<div class="block block-testimonial">
<div class="block-title">
<strong><?php echo $this->getTitle(); ?></strong>
</div>
<div class="block-content">
<?php echo $_block->toHtml(); ?>
</div>
The loop foreach($collection as $key => $value) prints out this:
Key: 27 - Block ID: testimonial-1
Key: 28 - Block ID: testimonial-2
Key: 29 - Block ID: testimonial-3
Key: 30 - Block ID: testimonial-4
Key: 31 - Block ID: testimonial-5
Which is good.
However, the only block that is echoed is the last block (testimonial-5). Since I'm trying to list out all the testimonial blocks, how can I echo out each block id to the page?
Go easy on me, I'm a beginner at php.
You are not printing block inside foreach loop.
Solution: move } parenthesis to the end of pasted code
$blockNum = 1;
foreach($collection as $key => $value){
$_blockId = $this->getIdentifier();
$block_ID = $_blockId . $blockNum;
echo "Key: " . $key . " - " . "Block ID: " . $block_ID . "<br />";
$blockNum++;
$_block = $this->getLayout()->createBlock('cms/block')->setBlockId($block_ID);
if ($_block) : ?>
<div class="block block-testimonial">
<div class="block-title">
<strong><?php echo $this->getTitle(); ?></strong>
</div>
<div class="block-content">
<?php echo $_block->toHtml(); ?>
</div>
<?php
endif;
}
I think that on Magento Connect are some Testimonial Modules, that are doing job you want.
On the other hand, if you are looking for 'simple' solution or if you are trying to play with Magento, is this approach ok.

on click change questions displayed

I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.

Categories