Variable contains data but it is not printed out - php

I am fetching data from database and trying to display it in a view but it does not work. However, print_r outputs the data successfully.
Model:
<?php
class Usermodel Extends CI_model{
public function getUserdata()
{
$this->load->database();
// $q=$this->db->select('name');
$q=$this->db->get('user');
return $q->result_array();
}
}
?>
Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends CI_controller{
public function User(){
$this->load->model('Usermodel');
$data['users']=$this->Usermodel->getUserdata();
$this->load->view('Users/userlist',$data);
}
}
?>
View:
<!DOCTYPE html>
<html lang="en">
<head>
<title>User Details</title>
</head>
<body>
<br>
<?php print_r($users); ?>
<h1>User Account Details</h1>
<tr>
<td>First Name</td>
<td>Account No</td>
</tr>
<?php foreach($users as $users): ?>
<tr>
<td><?php $users['name']; ?></td>
<td><?php $users['accountnumber']; ?></td>
</tr>
<?php endforeach ?>
</body>
</html>

You must use either echo construct or short echo tag in your view. Short echo tag is more preferred as it is more concise. For example: <?= $users['name'] ?>
In your code you just return the value of variables to nowhere instead of printing it out so the result is not showing.

You should use echo .
For your code example write <td><?php echo $users['name']; ?></td>

Related

How can I check if a variable is set and is the same value as another one which comes from a loop?

The thing is that I want to check if user's super variable is same as a value that I have on another variable that contains an array of values.
The problem is that the array is on 2 dimentions, so I need to loop the array before checking if it matches with the variable I am getting from the URL.
I don't want to do it with a function, but the best way of accomplishing it.
Here's the code:
<?php
$detalles = [
array("nombre"=>"Manzana", "precio"=>45.95, "color"=>"Rojo"),
array("nombre"=>"Pera", "precio"=>40.36, "color"=>"Verde"),
array("nombre"=>"Uva", "precio"=>95.21, "color"=>"Purpura"),
array("nombre"=>"Naranja", "precio"=>15.60, "color"=>"Naranja"),
array("nombre"=>"Mango", "precio"=>10.80, "color"=>"Amarillo")
];
?>
<!DOCTYPE html>
<html>
<head>
<title>Results of $_GET variable</title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div style="margin-top: 20px" class="container">
<table class="table table-striped">
<tr>
<td colspan="2">Product details</td>
</tr>
<?php foreach($detalles as $producto):
if(!isset($_GET['producto']) || $producto["nombre"] != $_GET['producto']){
header('Location: index.php');
}
if($producto["nombre"] == $_GET['producto']): ?>
<tr>
<td>Nombre:</td>
<td>{ <?php echo $producto["nombre"]; ?> }</td>
</tr>
<tr>
<td>Precio:</td>
<td>{ <?php echo $producto["precio"]; ?> }</td>
</tr>
<tr>
<td>Color:</td>
<td>{ <?php echo $producto["color"]; ?> }</td>
</tr>
<?php endif;
break;
endforeach; ?>
</table>
</div>
</body>
</html>
This is the details.php file, there's a file that is previous of this one which has a form with a get method and an action so everything works fine, my logic is what is not right.
Thank you in advance.
Blessings
You check in every loop if $_GET['producto'] is set. You have to check it once before the loop.
Don't print the details in your loop. First you have to find the product, and then show the details.
<?php
if( !isset($_GET['producto']) ) header("Location: index.php");
$found = null;
foreach($detalles as $producto){
if( $producto["nombre"] == $_GET['producto']){
$found = $producto;
break;
}
}
?>
<tr>
<td>Nombre:</td>
<td>{ <?php echo $found["nombre"]; ?> }</td>
</tr>
...

Array gets emptied when i try to add new stuff to it (PHP)

I am trying to add stuff into an array after every click a user makes on a category but for some reason it keeps replacing everything in the array. I can't figure out where I am going wrong. I've tried 'googling' it and every example i find looks similar to what i have written. Please Help!
these functions are store in core.php
function getStoreBacktrace($cat) {
include("config.php");
$backtrace = array();
if ($cat != 0) {
array_push($backtrace, $cat);
}
if (count($backtrace != 0)) {
foreach($backtrace as $c){
echo getBackCatName($c);
}
}
print_r($backtrace); // Put this to see what output is
}
function getBackCatName($c) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `id`="'.$c.'"';
$r_query = mysql_query($query);
$result = mysql_fetch_array($r_query);
echo ' > '.$result['name'].'';
}
this function prints out a list of links the user can click on
function getStoreCat($cat) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `main`="'.$cat.'" ORDER BY `name` ASC';
$r_query = mysql_query($query);
echo '<ul>';
while ($result = mysql_fetch_array($r_query)) {
echo '<li>';
echo ''.$result['name'].'';
echo '</li>';
}
echo '</ul>';
}
and it gets called in store.php
<?php
include("config.php");
include("core.php");
$backtrace = array();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title><?php echo getSiteTitle().' :: '.getSiteSlogan(); ?></title>
</head>
<body>
<table width="100%">
<tr>
<td colspan="2">
<!-- Backtrace -->
Home
<?php echo getStoreBacktrace($cat, $backtrace); ?>
</td>
</tr>
<tr>
<td>
<!-- Categories -->
<table>
<tr>
<td><?php echo getStoreCat($cat); ?></td>
</tr>
</table>
</td>
<td>
<!-- Products -->
<table>
<tr>
<?php echo getStoreProducts($cat); ?>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
now everytime a user clicks on a link that is made from the function getStoreCat($cat) it refreshes the page with new links to click on and new products to show depending on what $cat they chose. i want to push the $cat to the $backtrace array.
Right here:
$backtrace = array();
You are effectively resetting the array for each call to getStoreBacktrace().
EDIT:
Thanks for fixing your question. Now it's clear that the issue is you need to make $backtrace persistent through multiple page views. Do this using sessions:
Page template
<?php
session_start(); // enable sessions
include("config.php");
include("core.php");
?>
<!DOCTYPE html>
etc...
Function definition
<?php
function getStoreBacktrace($cat) {
include_once("config.php"); // use include_once() to prevent possible errors
if (!isset($_SESSION['backtrace']))
$_SESSION['backtrace']= array();
if ($cat != 0) {
array_push($_SESSION['backtrace'], $cat);
}
...
Everytime you call getStoreBacktrace you instantiate a brand new array in $backtrace.

Retrieving data in codeigniter: passing variables but not identified

I am new to PHP and codeigniter and I've been encountering a lot of PHP errors, such as Invalid argument supplied for foreach() and Undefined variable: row and query. In my views i tried to foreach it as (query->results() as $row) and the errors lesson to 1 which is an undefined varaiable: query
I'm not really sure which part I am missing, I already have declared query in my model, It seems that the controller was not able to receive the passed variable. Can anyone correct my mistake? and would give an explanation to avoid such mistakes in the future. Thanks!
Model function:
function getStudentInfo()
{
$this->db->select("firstname,middlename,lastname");
$this->db->from('studentinfo');
$query = $this->db->get();
return $query->result();
}
Controller function:
public function index()
{
$this->data['query'] = $this->m_login->getStudentInfo(); //i passed the query to the data variable
$this->load->view('v_home', $this->data);
}
Views:
<!DOCTYPE html>
<head>
<title>Simple Login with CodeIgniter - Private Area</title>
</head>
<body>
<h1>Home</h1>
<h2>Welcome <?php echo $studentid; ?>!</h2>
Logout
<h4>Display Records From Database Using Codeigniter</h4>
<table>
<tr>
<td><strong>First Name</strong></td>
<td><strong>Last Name</strong></td>
</tr>
<?php foreach($query as $row){?>
<tr>
<td><?php echo $row->firstname;?></td>
<td><?php echo $row->lastname;?></td>
</tr>
<?php }?>
</table>
</body>
</html>
Your procedure seems ok.
You made following error.
<?php foreach($query as $row);?>//your foreach ends here for this comma
//those lines are out of foreach
<?php echo $row->firstname;?>//$row is undefined and $row->firstname is invalid property
<?php echo $row->lastname;?>//same for lastname
<?php ?>
use this way.
<?php foreach($query as $row){?>
<?php echo $row->firstname;?>
<?php echo $row->lastname;?>
<?php } ?>

CakePHP: Error: The view for TasksController::index() was not found

I use CakePHP 2.5.5 . My project in this directory: C:\xampp\htdocs\vy\cakephp-2.5.5 . My project directory layout:
I have been created file C:\xampp\htdocs\vy\cakephp-2.5.5\app\Model\task.php (Model)with content:
<?php
class Task extends AppModel
{
var $name = 'Task';
}
?>
I have been created file C:\xampp\htdocs\vy\cakephp-2.5.5\app\Controller\TasksController.php (Controller) with content:
<?php
class TasksController extends AppController
{
var $name = 'Tasks';
function index()
{
$this->set('tasks', $this->Task->find('all'));
}
}
?>
I have been created file C:\xampp\htdocs\vy\cakephp-2.5.5\app\View\Task\index.ctp (View) with content:
<h2>Tasks</h2>
<?php if (empty($tasks)): ?>
There are no tasks in this list
<?php else : ?>
<table>
<tr>
<th>Title</th>
<th>Status</th>
<th>Created</th>
<th>Modified</th>
<th>Actions</th>
</tr>
<?php foreach ($tasks as $task): ?>
<tr>
<td>
<?php echo $task['Task']['title'] ?>
</td>
<td>
<?php
if ($task['Task']['done']) echo "Done";
else echo "Pending";
?>
</td>
<td>
<?php echo $task['Task']['created'] ?>
</td>
<td>
<?php if ($task['Task']['modified']) ?>
</td>
<td>
<!-- actions on tasks will be added later -->
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
When run program, error:
Missing View
Error: The view for TasksController::index() was not found.
Error: Confirm you have created the file: C:\xampp\htdocs\vy\cakephp-2.5.5\app\View\Tasks\index.ctp
Notice: If you want to customize this error message, create app\View\Errors\missing_view.ctp
How to repair above application? Thank you!
All you have to do is read the error message carefully :)
The view folder should be View\Tasks (plural) instead of View\Task as you currently have.
Also your model file name should be Task.php not task.php. Be carefully of case sensitivity in file names. While things will work on windows if you move files to a linux server you will get errors as it has case sensitive filesystem.

PHP HTML Template with Loop capabilities

I would like to ask some help and ideas on how to implement a loop inside the template. I can do foearch below but how can i include it to the template and show it in the results.
foreach($results as $row) {
$name = $row['name'];
$address = $row['address'];
}
What i want to achieve the results is something like below and how do I put the $template->publish(); in a variable so I can use it to store that data to the DB. thanks a lot.
<html>
<head>
<title>My Template Class</title>
</head>
<body>
<table><tr>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
</tr>
</table>
</body>
</html>
The template class
<?
class Template {
public $template;
function load($filepath) {
$this->template = file_get_contents($filepath);
}
function replace($var, $content) {
$this->template = str_replace("#$var#", $content, $this->template);
}
function publish() {
eval("?>".$this->template."<?");
}
}
?>
The template design.html
<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
</body>
</html>
the index.php
<?
include "template.class.php";
$template = new Template;
$template->load("design.html");
$template->replace("title", "My Template Class");
$template->replace("name", "William");
$template->replace("datetime", date("m/d/y"));
$template->publish();
?>
PHP itself is as good at templates as any other engine.
No need anything else
$pagetitle = "My Template Class";
foreach($results as $row) {
$row['date'] = date("m/d/y");
$data[] = $row;
}
$data = chunk_split($data,3);
Then in template
<html>
<head>
<title><?=$pagetitle?></title>
</head>
<body>
<table>
<?php foreach ($data as $chunk): ?>
<tr>
<?php foreach ($chunk as $row): ?>
<td>
<h3>Hello <?=$name?>!</h3>
<p>The time is: <?=$date?></p>
<p>Embedded PHP works in the template</p>
<p><b>But embed PHP in the data is a VERY BAD IDEA</b></p>
<p><?=$address?></p>
</td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
</body>
</html>
I made your example a bit more complicated yet closer to the real life.
It will print your table in the rows by 3 columns in each
Just don't re-invent the wheel, PHP works wonderfully as a templating language:
The template class
<?
class Template
{
private $template;
private $vars;
function load($filepath) {
$this->template = $filepath;
}
function replace($var, $content)
{
$this->vars[$var] = $content;
}
function publish()
{
extract($this->vars);
include($this->template);
}
}
?>
The template design.phtml
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<?php foreach($rows as $row) { extract($row); ?>
<h3>Hello <?php echo $name; ?></h3>
<p>The time is: <?php echo $datetime; ?></p>
<?php echo "<p>Embedded PHP works too!</p>"; ?>
<?php } ?>
</body>
</html>
The use is pretty much the same, just assign more than one row to make use of it:
<?
include "template.class.php";
$template = new Template;
$template->load("design.phtml");
$template->replace("title", "My Template Class");
$rows = array();
$rows[] = array(
"name" => "William",
"datetime" => date("m/d/y"),
);
$template->replace("rows", $rows);
$template->publish();
?>
Hope this is helpful.
Your PHP code:
$htmldata ="";
($results as $row) {
$name = $row['name'];
$address = $row['address'];
$htmldata .="
<tr><td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>".$name."</p>
<p>".$address." </p>
</td>
</tr>
";
}
Then in your template design.html, you will pass the $htmltable variable and embedd there:
<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
<table>
<?php echo $htmltable; ?>
</table>
</body>
</html>

Categories