creating dynamic navigation in zend framework 3 - php

Currently, I am working on a project using Zend framework 3. In this I have to create dynamic navigation means getting navigation menu(data) from the database. I have already created the static navigation as described in
https://docs.zendframework.com/tutorials/navigation/#setting-up-zend-navigation
but not able created this dynamically.

You could have the controller read the values from your database and then pass them on to the viewmodel. Something like this:
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\ResultSet;
function indexAction() {
$statement = $driver->createStatement('SELECT menu FROM database');
$statement->prepare();
$result = $statement->execute($parameters);
if ($result instanceof ResultInterface && $result->isQueryResult()) {
$resultSet = new ResultSet;
$resultSet->initialize($result);
}
return new ViewModel(array('entries' => $resultSet));
}
Then you can get at the entries in your view .phtml
<?php foreach($this->entries as $entry) {
echo $entry . PHP_EOL;
}?>

Related

Smarty get the while template from the class

I'm totally new to smarty... and it's creeping me out :)
I got the following class in /inc/class/search.php:
Class search
{
function __construct($request) {
global $dbconn;
$request = htmlspecialchars($request);
$sql = "SELECT * FROM table WHERE id LIKE '%{$request}%'";
$res = $dbconn->Query($sql);
$entity = $res->fetchArray();
return $entity;
}
}
I have this in php_head.php:
if (isset($_REQUEST['search']) && !empty($_REQUEST['search'])) {
$is = new search($_REQUEST['search']);
$smarty->assign("searchValues", $is);
}
This code in php_head is designed to be called by ajax later on. But when I run index.php?search=string I get the whole smarty template. Please help.
What you need to do is displaying only some part of output when search is in URL.
So you could modify your code this way:
if (isset($_REQUEST['search']) && !empty($_REQUEST['search'])) {
$is = new search($_REQUEST['search']);
$smarty->assign("searchValues", $is);
$smarty->display('searchvalues.tpl'); // custom base template
exit; // stop execution of later code
}
And you should create searchvalues.tpl template and display here only this part that you want to display and not the whole base template.
You need to clear template that you need for ajax, and if you want to include it in some other template
{include file="path_to_template.tpl"}
And when you need only the result from this template use
echo $smarty->fetch('path_to_template.tpl');
For example you have :
$smarty->display('index.tpl');// this will return index.tpl
And in index.tpl :
<div id="result_ajax">
{include file="ajax_template.tpl"}
</div>
And in ajax.php :
//Do some stuff
echo $smarty->fetch('ajax_template.tpl');

Check if category has parent

i'm in mid of creating my own cms . And now i want to show which one of the category has parent but i don't know how, so please help me.
my category table
idkategori | namakategori | parentid
1 Programming 0
2 PHP 1
Or i need relationship table for my categories?
My Controller so far.
function tampilmenu()
{
$sql = "select * from fc_kategori";
$data['kategori'] = $this->bymodel->tampildata($sql);
$sql1 = "select parentid from fc_kategori";
$data['parent'] = $this->bymodel->tampildata($sql1);
$id=array();
foreach ($data['parent'] as $paren)
{
$id[]=$paren->parentid;
}
foreach ($data['kategori'] as $cat)
if(in_array($cat->parentid,$id))
{
$have ='Yes';
}
else
{
$have ='No';
}
echo $cat->idkategori.$have;
}
}
my model
function tampildata ($sql)
{
$query = $this->db->query($sql);
return $query->result();
}
Please don't laugh on me.
Kindly follow:
1) Since you are using a MVC framework, never write queries inside the controller (queries should always be written in models).
2) Never use raw queries, since CI provides you what is called as Active Record.
3) Also never pass direct queries anywhere you'll possibly code in whichever language. Always pass data and make do that function to compute and query process.
4) Remember, in CI Models are only used for database functionalities, Views are only used for your HTML markups and Controllers acts as the mediator between models and views.
Your code:
Controller -
public function tampilmenu()
{
$categories = $this->bymodel->get_category_having_parent();
echo "<pre>"; print_r($categories);
// this will return object having all categories that are parents
}
Model -
public function get_category_having_parent()
{
$parent_ids = array();
$ps = $this->get("parentid");
foreach($ps as $p)
{
$parent_ids[] = $p->parentid;
}
$this->db->where_in("id", $parent_ids);
$query = $this->db->get("fc_kategori");
return $query->result();
}
public function get($column="*")
{
$this->db->select($column);
$query = $this->db->get("fc_kategori");
return $query->result();
}

ZF2 Executing DB query from Controller

Hi i am new to ZF2 and not familiar with some of the changes in ZF2. I would like to know how can i execute SQL query directly from Controller.
I have the following code:
public function indexAction()
{
$db = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$sql = "SELECT * FROM books";
$statement = $db->query($sql);
$res = $statement->execute();
if($res instanceof ResultInterface && $res->isQueryResult()){
$resultSet = new ResultSet;
$resultSet->initialize($res);
foreach($resultSet as $row){
echo $row->title . PHP_EOL;
}
}
exit;
/*
return new ViewModel(array(
'books' => $this->getBooksTable()->fetchAll(),
));
*/
}
When the controller above is opened in web browser, it does not show anything. If i echo "Blahh.." before the if statement, it displays the "Blahh.." text correctly.
Does anyone know why it does not display the query result properly? Thx.
try to add this in the top of your controller :
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\ResultSet;

php pdo in class + best method to display return array

I have the following class:
<?php
class photos_profile {
// Display UnApproved Profile Photos
public $unapprovedProfilePhotosArray = array();
public function displayUnapprovedProfilePhotos() {
$users = new database('users');
$sql='SELECT userid,profile_domainname,photo_name FROM login WHERE photo_verified=0 AND photo_name IS NOT NULL LIMIT 100;';
$pds=$users->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
$unapprovedProfilePhotosArray = $rows;
echo 'inside the class now....';
foreach($rows as $row) {
echo $row['userid'];
}
}
}
I can display the data successfully from the foreach loop.
This is a class that is called as follows and want to be able to use the array in the display/view code. This why I added the "$unapprovedProfilePhotosArray = $rows;" but it doesn't work.
$photos_profile = new photos_profile;
$photos_profile->displayUnapprovedProfilePhotos();
<?php
foreach($photos_profile->unapprovedProfilePhotosArray as $row) {
//print_r($photos_profile->unapprovedProfilePhotosArray);
echo $row['userid'];
}
?>
What is the best way for me to take the PHP PDO return array and use it in a view (return from class object). I could loop through all the values and populate a new array but this seems excessive.
Let me know if I should explain this better.
thx
I think you're missing the $this-> part. So basically you're creating a local variable inside the method named unapprovedProfilePhotosArray which disappears when the method finishes. If you want that array to stay in the property, then you should use $this->, which is the proper way to access that property.
...
$pds=$users->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
$this->unapprovedProfilePhotosArray = $rows;
...

Most efficient way to have a page that has a vast amount of results depending on request

The best example i can think of is a hall of fame page for sports.
You can then have a navigation that can limit the results depending on the user's requests, Past 3 Months and boxing for example.
What would be the best way to display multiple kind of result layouts, for example,
The swimming results have a different layout to football, football differs to boxing and then add a time limiter by timestamp.
These are the options i have thought of so far and would like your opinion on.
Simple PHP
if($_GET['sport'] = "boxing"){
if(isset($_GET['timescale'])){
$start = 1334752108;
$end = 1334759108;
$query = "SELECT athlete_name, athlete_age, athlete_desc FROM `athletes` WHERE `timestamp` BETWEEN '".$start."' AND '".$end."' AND `sport` = 'boxing' LIMIT 30";
} else {
$query = "SELECT athlete_name, athlete_age, athlete_desc FROM `athletes` WHERE `sport` = 'boxing' LIMIT 30";
}
while($row = mysql_fetch_array(mysql_query($query))){
echo "<div class='boxing'>";
//show results
echo "</div>";
}
}
if($_GET['sport'] = "swimming"){
//repeated
}
if($_GET['sport'] = "football"){
//repeated
}
Ajax
Have either one page that will handle all the requests (ajax_request_hof.php) that contains similar code to the PHP above.
EDIT
skafandri suggested a Data Mapping Class, would anyone else advise this or is able to show me an example?
Any ideas on how i can improve this are greatly welcomed and needed.
You mentioned in SO chat that you didn't have any experience with frameworks so here's a suggestion without one.
I know I'm probably going to be flamed for this, but knowing that it's an organizational structure issue you can steal some concepts of MVC and use them until you can port it to a more proper structure to at least make it a little cleaner and a lot easier to manage.
Disclaimer: In no way is this a good structure but for your problem, considering you told me you didn't have any background on OOP and or patterns, but it's "good enough" as a temporary solution.
If you order it like this you can insert it into almost any framework without doing a lot of work.
Here's one way you can do it.
With the following classes:
<?php
class BasketballPage
{
protected $mapper;
public construct ( $mapper )
{
$this->mapper = $mapper;
}
public function display_player_info( $playerid, $sportid )
{
$basketball_player = $this->mapper->get_sports_player( $playerid, $sportid )
echo '<p>Basketball player name ' . $basketball_player['name'];
echo '<p>Some other HTML, etc</p>';
}
public function display_match_data($matchid, $sportid)
{
//Same as above but would call to $this_mapper->get_match_data(); And display relevant HTML.
}
public function display_player_info_AJAX( $playerid, $sportid )
{
$player = $this->mapper->get_sports_player();
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode( $player );
exit();
}
}
class BoxingPage
{
protected $mapper;
public function display_player_info( $playerid, $sportid)
{
$boxing_person = $this->mapper->get_sports_player( $playerid, $sportid)
echo '<p>Person\'s boxing name ' . $boxing_person['name'];
echo '<p>Some other HTML, etc</p>';
}
}
class Mapper
{
protected $connection;
public function __construct ( $connection )
{
$this->connection = $connection;
}
public function get_sports_player($id, $sportid)
{
$query = $this->connection->prepare( 'SELECT * FROM players WHERE id = :player_id AND sport_id' );
$query->bindValue(':player_id', $id, PDO::PARAM_INT);
$query->bindValue(':sport_id', $sport_id, PDO::PARAM_INT);
$query->execute();
return $query->fetchAll( PDO::FETCH_ASSOC );
}
public function get_match_data($matchid, $sportid)
{
//some query here that returns match data.
}
}
?>
You'd have a single php page for each of these classes, since they can grow big.
I.e:
Basketballpage.php
Boxingpage.php
Mapper.php
Then include these files into your index.php. and your index could look something like this:
index.php?playerid=1&sportid=2
<?php
//Instantiate the classes first.
$connection = new PDO($dsn,$username,$password); //your database credentials
$mapper = new Mapper( $connection );
$basketballpage = new BasketballPage( $mapper );
$boxingpage = new BoxingPage( $mapper );
if( $_GET['page'] == 2]) //lets say basketball is id 2 in your database
{
$basketballpage->display_player_info( $_GET['playerid'], $_GET['sportid'] );
}
//In this same page you'd also add this other line, but lets say they visit the bottom link instead: index.php?playerid=1&sportid=3
if( $_GET['page'] == 3]) //lets say boxing is 3 in your database
{
$boxing->display_player_info( $_GET['playerid'], $_GET['sportid'] );
}
//THEN lets say someone visits a different link like: index.php?index.php?matchid=1&sportid=2&page=2
if( $_GET['page'] == 2] && $_GET['matchid'])
{
$boxingpage->display_match_data( $_GET['playerid'] );
}
//On the above you can use that same category, but a different function will display a different page!
//Bonus example, you can use it for AJAX easily. Lets say they visit the url index.php?playerid=1&sportid=2&AJAX=1
if( $_GET['page'] == 2 && GET['AJAX'] == 1)
{
$basketballpage->display_player_info_AJAX( $_GET['playerid'], $_GET['sportid'] );
}
?>
It seems complicated but once you see how it's all connected, notice how your index page is only around 30-40 lines! It can make things really neat and you can just concentrate on routing your requests on index.php while the other files take care of the rest.
EAV is a great solution to handle different data models, you can also write a data mapping class, although I recommend you to use a PHP framework, why not ZEND?
The basic ideas to solving this well are:
Split your data retrieval from your display.
class Model { public function getData() {} }
class View { public function write() {} }
$model = new Model();
$view = new View();
$view->write($model->getData());
Implement Model::getData:
Loop to build the sports that you are interested in so that you can OR them in a query.
Get all of the results.
Use PHP to order the array into sports.
Implement View::write:
Loop over each sport, displaying it correctly.

Categories