Very slow when getting data from class - php

I have created a class, it store the data from mySQL database into class.
The performance is really slow when outputting to the browser, I have to wait like 10 seconds and this is not acceptable. How to solve this problem?
In the controller file:
$modelCategory = new modelCategory();
$categories = $modelCategory->findAll('takeawayID = :id', array('id' => $takeawayID));
if ($categories === false) {
echo "Query failed";
return;
}
$data['categories'] = $categories;
View File:
<?php foreach ($categories as $category): ?>
<div class="menu-container">
<h2><?php echo $category->name; ?></h2>
<ul class="menu-list">
<?php foreach ($category->item as $item): ?>
<li class="<?php echo $class; ?>">
<div class="menu-holder">
<div class="text-block">
<div class="text-holder">
<?php if ($item->optionsTotal == 1): ?>
<?php foreach($item->options as $option): ?>
<?php $price = $option->price; ?>
<?php $optionvalue = $option->optionValue; ?>
<?php endforeach; ?>
<?php endif; ?>
<h3>
<?php echo $item->name; ?>
<?php if ($item->optionsTotal == 1 && $optionvalue != "Regular"): ?>
(<?php echo $optionvalue; ?>)
<?php endif; ?>
</h3>
<?php if ($item->desc != ""): ?>
<p> <?php echo $item->desc; ?> </p>
<?php endif; ?>
</div>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
model Category class file:
<?
class modelCategory extends Model {
public $id;
public $desc;
public $name;
public $items = null;
public function findAll($condition, $parameters) {
$query = "SELECT * FROM categories WHERE " . $condition;
$statement = self::getDb()->prepare($query);
if (!$statement->execute($parameters))
return false;
return self::createModels($statement->fetchAll());
}
public static function createModels($dataAr) {
$models = array();
foreach ($dataAr as $data) {
$category = new modelCategory;
$category->id = $data['id'];
$category->desc = $data['description'];
$category->name = ucwords(strtolower($data['name']));
$models[] = $category;
}
return $models;
}
public function getItems() {
if ($this->items === null)
$this->items = modelItem::find('category_id = :category_id', array('category_id' => $this->id));
return $this->items;
}
public function __get($key) {
switch ($key) {
case 'item':
return $this->getItems();
}
}
}
?>
modelItem:: class is very similar to model Category class.

one problem that I see is that you take the result and build a class to contain the data you could use PDO::FETCH_CLASS that does the same but in a more optimize way.
But like Michael J.V. said you should do some monitoring of your application to detect the exact cause of the problem (there might be multiple and not easy to catch with the eyes)

Related

Why can't I found the page of the post ine a blog?

I have a problem with my code. I'am trying to realize a simple blog. Displaying the list of all the posts works. But when I click on a specific post the page of this post doesn't work.
This is the structure of my folder
Here is my index.php
<?php
require_once('controleurs/Controleur.php');
require_once('modeles/Modele.php');
require_once('modeles/Photo.php');
require_once('modeles/Photos.php');
$controleur = new Controleur();
if (isset($_GET['page']) && 'photo' === $_GET['page']) {
$controleur->afficherPhoto();
} else {
$controleur->listerPhotos();
}
Here is my Controleur.php :
class Controleur
{
public function listerPhotos()
{
$photos = new Photos();
$photos = $photos->listerPhotos();
require_once('vues/liste-photos.php');
}
public function afficherPhoto()
{
$photo = new Photo();
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$photo = $photo->afficherPhoto($_GET['id']);
}
require_once('vues/affiche-photo.php');
}
}
Here is class Photo.php
class Photo
{
use Modele;
private $id;
private $fichier;
private $titre;
public function afficherPhoto($id)
{
if (!is_null($this->pdo)) {
$stmt = $this->pdo->prepare('SELECT * FROM photo WHERE id = ?');
}
$photo = null;
if ($stmt->execute([$id])) {
$photo = $stmt->fetchObject('Photo');
if(!is_object($photo)) {
$photo = null;
}
}
return $photo;
}
public function getId()
{
return $this->id;
}
public function getFichier()
{
return $this->fichier;
}
public function getTitre()
{
return $this->titre;
}
}
Here is my liste-photos.php (it works!)
<?php
$titre = 'Mon book';
ob_start();
?>
<article>
<?php foreach ($photos as $photo): ?>
<a href="photo.php?id=<?= $photo->getId() ?>">
<img src="photos/<?= $photo->getFichier() ?>" width="250"/>
</a>
<h2><?= $photo->getTitre() ?></h2>
<?php endforeach; ?>
</article>
<?php
$contenu = ob_get_clean();
require_once('layout.php');
Here is my affiche-photo.php (it doesn't works!) :
$titre = 'Une photo de mon book';
if (is_null($photo)):
$contenu = "Cette photo n'existe pas.";
else:
ob_start();
?>
<article>
<img src="photos/<?php $photo->getFichier(); ?>" width="500" />
<h2><?php $photo->getTitre(); ?></h2>
</article>
<?php
$contenu = ob_get_clean();
endif;
require_once('layout.php');
Thank you if you can help!!!
The main reason why you didn't see the result is because you didn't print the values. You've used <?php $value ?> instead of <?php echo $value; ?>.
Also, according to the official documentation within fetchObject
class Photo
{
use Modele;
private $id, $fichier, $titre;
private function __construct () {}
public function afficherPhoto($id)
{
if (!is_null($this->pdo)) {
$stmt = $this->pdo->prepare('SELECT * FROM photo WHERE id = ?');
if ($stmt->execute([$id])) {
return $stmt->fetchObject(__CLASS__);
}
}
return null;
}
}
In Controller method:
public function afficherPhoto()
{
$photo_cl = new Photo();
$photo = null;
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$photo = $photo_cl->afficherPhoto((int)$_GET['id']);
}
require_once('vues/affiche-photo.php');
}
In the view file affiche-photo.php (fichier and titre must correspond to the DB table field names):
<article>
<img src="photos/<?= $photo->fichier; ?>" width="500" />
<h2><?= $photo->titre; ?></h2>
</article>
Thanks
The problem was indeed with the echo. I finally just change my affiche-photo.php :
<?php
$titre = 'Une photo de mon book';
if (is_null($photo)):
$contenu = "Cette photo n'existe pas.";
else:
ob_start();
?>
<article>
<img src="photos/<?php echo $photo->getFichier(); ?>" width="500" />
<h2><?php echo $photo->getTitre(); ?></h2>
</article>
<?php
$contenu = ob_get_clean();
endif;
require_once('layout.php');
and my liste-photos.php where I changed the path in the href :
<?php
$titre = 'Mon book';
ob_start();
?>
<article>
<?php foreach ($photos as $photo): ?>
<a href="?id=<?= $photo->getId() ?>">
<img src="photos/<?= $photo->getFichier() ?>" width="250"/>
</a>
<h2><?= $photo->getTitre() ?></h2>
<?php endforeach; ?>
</article>
<?php
$contenu = ob_get_clean();
require_once('layout.php');

Codeigniter foreach whithout $id

how i can sort some informations without $id? My problem is, that i ca read all teams and users. but how i can sort this?
So that i get a team and the players from this team in one box. WIth my code i have all users in all boxes.
Can i foreach in a foreach?
view what i try:
<?php foreach ($teams as $item): ?>
<div class="col-xs-12">
<?php echo $item->teamname ?>
</div>
<?php foreach ($users as $item): ?>
<div class="col-xs-12">
<?php echo $item->username ?>
</div>
<?php endforeach ?>
<?php endforeach ?>
This is my database
table users
user_id username team_id
1 paul 1
2 tom 2
3 brad 1
4 pim 2
table team
team_id teamname
1 team1
2 team1
Now i have a subside like domaincom/teams
And i want on this side
team 1 : paul, brad
team 2 : tom, pim
controller:
<?php
class Teams extends CI_Controller {
public $layout = 'full';
public $module = 'teams';
public $model = 'Teams_model';
public function __construct() {
parent::__construct();
$this->load->model($this->model);
$this->_primary_key = $this->{$this->model}->_primary_keys[0];
}
public function index()
{
$data['teams'] = $this->{$this->model}->get_teams();
$data['users'] = $this->{$this->model}->get_users();
$data['teamsWithUsers'] = $this->{$this->model}->get_users_by_team();
$data['items'] = $this->{$this->model}->get();
$this->load->view($this->module, $data);
}
}
this is my model
<?php
class Teams_model extends CI_model
{
public $_table = 'teams';
public $_primary_keys = array('teams_id');
function get_teams()
{
return $this->db->get('teams')->result();
}
function get_users()
{
return $this->db->get('users')->result();
}
function get_users_by_team($teamID = null)
{
$this->db->select('u.user_id, u.username, u.team_id, t.teamname');
$this->db->from('users AS u');
$this->db->join('teams AS t', 't.team_id = u.team_id');
if ($teamID != '') {
$this->db->where('t.team_id', $teamID);
}
$this->db->order_by('t.teamname', 'ASC');
$this->db->order_by('u.username', 'ASC');
$query = $this->db->get();
return $query->result();
}
}
What i looking for is this view sample
what about that?
your controller
public function index()
{
$data['teams'] = $this->{$this->model}->get_teams();
$data['users'] = $this->{$this->model}->get_users();
$arrUsersPerTeam = [];
foreach($data['users'] AS $objUser)
{
$arrUsersPerTeam[$objUser->team_id][] = $objUser;
}
$data['arrUsersPerTeam'] = $arrUsersPerTeam;
$data['items'] = $this->{$this->model}->get();
$this->load->view($this->module, $data);
}
and your view
<?php
foreach ($teams as $item):
?>
<div class="col-xs-12">
<?php echo $item->teamname ?>
</div>
<?php
if (isset($arrUsersPerTeam[$item->team_id])) :
foreach ($arrUsersPerTeam[$item->team_id] as $objUser):
?>
<div class="col-xs-12">
<?php echo $objUser->username ?>
</div>
<?php
endforeach;
endif;
endforeach;
You should use a single join query to get your results make sure results are ordered by team
/**model*/
function some func(){
$this->db->select( 'u.username, t.team_id, t.teamname' );
$this->db->from( 'team AS t' );
$this->db->join( 'users AS u', 't.team_id = u.team_id' );
$this->db->order_by( 't.team_id', 'ASC' );
$query = $this->db->get();
return $query->result();
}
In your controller collect results returned by above method defined in your model and pass it to view.
In view there is no need for nested loop only single loop will do the job here like $results contains all the records then in view you can display your records as
/* view */
$parent = false;
$index = 1;
<div class="col-xs-12">
<?php foreach ($results as $result){ ?>
<?php if($parent !=$item->teamname ){ ?>
<?php if($index !=1 ){ ?>
</div>
<?php } ?>
<div class="col-xs-12">
<h2><?php echo $result->teamname ?></h2>
<?php } ?>
<p><?php echo $result->username ?></p>
<?php
$parent =$result->teamname;
$index++;
} ?>
</div> // To close the opened div
2 things: you can pick out key from the foreach, that you can use later, second the "$item" is used 2 places where you might overwrite it by accident.
<?php foreach ($teams as $key => $team_item ): ?>
<div class="col-xs-12">
<?php echo $team_item->teamname ?>
</div>
<?php foreach ($users as $user_item): ?>
<?php if($item->team_id == $key): ?>
<div class="col-xs-12">
<?php echo $user_item->username ?>
</div>
<?php endif ?>
<?php endforeach ?>
<?php endforeach ?>
I'm not really sure if thats what you are trying to achieve

Warning: Invalid argument supplied for foreach()

I have an error in the product detail, I do not know what else to change where again. when I change $detail into $categories succeed but is the same as function submenu. It was not according to my wishes
My View
<!-- navbar -->
<div class="row">
<?php foreach ($categories as $row) : ?>
<div class="col-sm-3">
<h5><?php echo $row->categoriesName; ?></h5>
<ul><li><a href="<?php echo base_url();?>member/detail">
<?php echo $row->productName; ?></a> </li></ul>
</div>
<?php endforeach; ?>
</div>
<!-- product detail -->
<?php foreach ($detail as $details_new) : ?>
<div class="box">
<h1 class="text-center"><?php echo $details_new->productName;?></h1>
<p class="price"><?php echo $details_new->price;?></p>
</div>
<?php endforeach; ?>
My Controller
public function home() {
$data=array('title'=>'Pasar Online | Ayo Belanja Sekarang',
'username'=> $this->session->userdata('username'),
'product' => $this->product_model->all(),
'categories' => $this->categories_model->get_main(),
'isi' =>'member/index');
$this->load->view('template_home/wrapper',$data);
}
public function detail() {
$data['username'] = $this->session->userdata('username');
$data['categories'] = $this->categories_model->get_main();
$data['detail'] = $this->categories_model->get_details();
$this->load->view('member/coba',$data);
}
My Model
public function get_main(){
$this->db->select('product.*,categories.*');
$this->db->from('product');
$this->db->join('categories','product.categoriesID=categories.categoriesID');
$this->db->limit(5);
$query = $this->db->get();
if($query->num_rows() > 0) {
$results = $query->result();
} return $results;
}
public function get_details() {
$query = $this->db->query("SELECT * FROM product WHERE productID");
$row = $query->row();
}
still can not display a single product
I do not know where my mistake... please help me, thanks
you are iterating details array in wrong format.
public function get_details() {
$query = $this->db->query("SELECT * FROM product WHERE productID");
$row = $query->row();
return $row;
}
This will return only single row without any indexing like - 0,1,2...
and on view page you are using foreach loop and foreach loop use indexing to iterate value you can iterate like that --
<div class="box">
<h1 class="text-center"><?php echo $detail->productName; ?></h1>
<p class="price"><?php echo $detail->price; ?></p>
</div>
please use this way hope it will work..
In codeigniter row() selects only first row of your result in object format.So no need to use foreach loop.Just try like this...
<div class="box">
<h1 class="text-center"><?php echo $detail->productName;?></h1>
<p class="price"><?php echo $detail->price;?></p>
</div>
And
In model
public function get_details() {
$query = $this->db->query("SELECT * FROM product WHERE productID");
$row = $query->row();
return $row;
}
it is because of $detail variable is empty, no data available in this variable, always check for data in variable before looping
<?php if(!empty($detail)){
foreach ($detail as $details_new) : ?>
<div class="box">
<h1 class="text-center"><?php echo $details_new->productName;?></h1>
<p class="price"><?php echo $details_new->price;?></p>
</div>
<?php endforeach; } ?>

my query in codeigniter cannot produce result

i've been debbuging it many times based on my knowledge, i am new to codeigniter, any solution idea would be much appreciated... ty
here's my code
MODEL:
function userdisplay_info($id){
$result = $this->db->query("SELECT uid FROM user WHERE userIdentificationNumber LIKE '$id'");
//if($result->num_rows() > 0){
$info_data = $result->result();
$row = $info_data[0];
$result->free_result();
}
CONTROLLER:
function r_book(){
$data = array();
$bid = $this->input->post('bid');
$u_id = $this->input->post('userinputid');
$data = array(
'book_reserved' => 1
);
if($this->module2->reserved_book($bid,$data))
{
$data['info'] = $this->module2->userdisplay_info($u_id);
$this->load->view('User/template/header');
$this->load->view('User/template/navigator');
$this->load->view('User/landingpage',$data);
$this->load->view('User/template/footer');
return true;
}else
{
$this->load->view('User/template/header');
$this->load->view('User/template/navigator');
$this->load->view('User/landingpagefail');
$this->load->view('User/template/footer');
return false;
}
}
VIEW:
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body">
<?php if($info) : foreach($info as $u_info) : ?>
<ul class="list-unstyled">
<li>Last Name : <?php echo $u_info->uid; ?></li>
<li>First Name : <?php echo $u_info->userFirstname; ?></li></li>
<li>Middle Name : <?php echo $u_info->userMiddlename; ?></li></li>
<li>Course : <?php echo $u_info->userCourse; ?></li></li>
</ul>
<?php endforeach; ?>
<?php else :?>
<h4> No Record Found</h4>
<?php endif; ?>
</div>
</div>
</div>
Rewrite your model function as
function userdisplay_info($id){
$this->db->select('uid');
$this->db->like('userIdentificationNumber', $id);
$query = $this->db->get('user');
return $query->result_array();
}

query result using codeIgniter

It is the first time for me to use codeIgniter, I tried to build a simple DB driven application.
First the model:
class News_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_news()
{
$query = $this->db->get('news');
return $query->result_array();
}
}
second the controller
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
The view "index":
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p>View article</p>
<?php endforeach ?>
When I run the code it displays the header and the footer, but no database record is displayed.
If I put a print statement in the view outside the foreach it works, but not inside the foreach.
I use if($news) to find out if the query retrieved any result, but there is no result retrieved.
How can I know why there is no result retrieved from the DB?
You need to call another foreach inside your foreach. example:
foreach ($result as $row) {
foreach ($row as $key => $val) {
if ($key === "reservation_info") {
$data['decoded'] = json_decode($val);
} else {
$data[$key] = $val;
}
}
}
and i would use the '$val' values in the view. just by calling them as variables, like so
//in the view
echo $decoded
echo $firtname
... and so on
to check if new is empty or not, just
print_r($news);
or you can modify your view :
<?php if(!empty($new)): ?>
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p>View article</p>
<?php endforeach ?>
<?php else: ?>
Empty news
<?php endif; ?>

Categories