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 } ?>
Related
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>
Im making an overview for users that are administrators on my website.
The problem i am having is that i have no clue how to pass a function like the i want it to.
I've tried searching around using arguments but nothing seemed like it would fix my problem.
The code:
I have 3 scripts (+ stylesheet) that are connected to each other
adminUsers.php
<?php
session_start();
require_once ("../model/handler.php");
require_once ("../model/gui_mod.php");
echo("<link rel='stylesheet' type='text/css' href='../stylesheet/stylesheet.css'>");
$gui_obj = new class_gui();
$gui_obj->admin();
$gui_obj->adminUsers();
handler.php (this page i make the connection to the database with var $conn)
function admins(){
?>
<table>
<?php
$query = "SELECT * FROM admin";
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->fetchall();
foreach($result as $row){
?>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<?php
}
?>
</table>
<?php
}
gui_mod.php - This is where i make the Gui of the page
function adminUsers(){
?>
<html>
<body>
<div class="admin_container_head_bg">
<div class="admin_container_head_text_one">
<header>Administrator</header>
</div>
<div class="admin_container_head_text_two">
<p>Manager</p>
</div>
</div>
<div class="admin_users">
<div class="table_admins">
<?php admins(); ?>
</div>
</div>
</body>
</html>
<?php
}
I had the feeling that the problem is caused because i'm requesting a function inside another function. But i honestly have no clue so if this is false please tell me :#
You have to either declare the connection object global or pass it into the function.
function admins() {
global $conn;
...
Or:
function admins($conn) {
...
}
And then call by passing in the connection, like:
admins($conn);
Otherwise it's not in scope. Keep in mind you'll have to declare the connection object global from the other function or pass it in to then call admins from it, or you'll run into the exact same problem.
I'm trying to practice OOP but with native PHP.
I have my 'controller', My_Controller.php:
session_start();
if (!isset($_SESSION['userId'])) exit('You are not authorized to access this page');
// ... some code ...
if(isset($_GET['action']))
{
switch($_GET['action']) {
case 'getOrder':
if(isset($_GET['id'])) {
$orderDetails = $jobModel->getOrderById($_GET['id']);
header('Location: order-details.php');
}
break;
default:
echo 'Invalid action';
break;
}
}
And this is my 'view', order-details.php:
<?php
require_once './My_Controller.php';
?>
<html>
<head>
<title>Order Details</title>
</head>
<body>
<div>
Back to Order List
</div>
<div>Order Details</div>
<div>
<form id="form-add-job-item" method="post" action="">
<table border="1">
<thead>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php
if(isset($orderDetails) && $orderDetails != 0) {
foreach($orderDetails as $orderItem => $value) {
?>
<tr>
<td><?= $value->name; ?></td>
<td><?= $value->quantity; ?></td>
<td><?= $value->amount; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<button type="submit">Add Item</button>
</form>
<?php
?>
</div>
</body>
</html>
order-details.php is some sort of a template to display the information for every order depending on the contents of $orderDetails.
It is called via separate page containing a table of orders. Each order in the table has a link:
<tr>
<td><?= $value->job_id; ?></td>
<td><?= $value->job_date; ?></td>
<td><?= $value->total_amount; ?></td>
</tr>
This is so it can be dynamic, in that I won't have to code a separate page for each order. This template will just hold variables and those variables will be filled with the relevant information based on the passed order ID, which will depend on what link the user clicked.
WHAT I NEED TO ACCOMPLISH:
I need to access the contents of $orderDetails and show the list of order items in order-details.php but I'm not sure how to do that? With what I have so far, I get a NULL value from the $orderDetails variable when accessing it from order-details.php.
I have checked the results from the database query using var_dump($orderDetails) and it does return the expected results.
UPDATE:
inside My_Controller.php:
case 'getOrder':
if(isset($_GET['id'])) {
// $dba contains the connection to the database
$MyController = new My_Controller($dba);
$MyController->getOrderById($_GET['id']);
}
break;
// ... Some code ...
class My_Controller
{
private $myModel;
public function __construct(Db $db)
{
$this->myModel = new My_Model($db);
}
public function getOrderById($orderId)
{
$orderDetails = $this->myModel->getOrderById($orderId);
include './order-details.php';
}
}
That variable will be accessible without doing anything special because it is in global scope. In other words, you can just access it as $orderDetails.
The trick is that it has to be defined. The way your code in My_Controller.php is set up, $_GET['action'] must be equal to getOrder and $_GET['id'] must be defined, or $orderDetails will not be set.
Here's the catch: this line of code ensures that $orderDetails is never set when you get to your display logic:
header('Location: order-details.php');
This redirect doesn't preserve the $_GET parameters. It triggers a brand new request with no parameters. So, after the redirect, your logic loading the order details never runs.
As for how to solve it: that depends on what you're trying to do, but most likely you shouldn't have that redirect there at all.
Also, you should know that using lots of global variables like this is considered bad practice. You should start breaking your code into small, reusable chunks using functions or objects.
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.
Using CodeIgniter I am trying to create a link that the user can click within a view to show them the details of a record in my database.
In ASP.NET MVC3 with C# I would do it with #Html.ActionLink("Controller", "Action", new { id = item.Id})
This is my session controllers index() function
public function index()
{
$data['sessions'] = $this->session_model->get_sessions();
$this->load->view('_header');
$this->load->view('session/index', $data);
$this->load->view('_footer');
}
This is the index view it loads where I want to be able to click the link to go to enter() function
<table>
<th>Session Name</th>
<th>Description</th>
<th>Host</th>
<th></th>
<?php foreach ($sessions as $session_item): ?>
<tr>
<td> <?php echo $session_item['sessionName'] ?> </td>
<td> <?php echo $session_item['sessionDesc'] ?> </td>
<td> <?php echo $session_item['adminName'] ?> </td>
<td> <a id="enterSession" href=<?php echo site_url("session/enter" + $session_item['id']) ?> >Enter</a></td>
</tr>
<?php endforeach ?>
The enter session points me to the url "http://192.168.1.36/index.php/1" (if the id of my item is 1) whereas I expect "http://192.168.1.36/index.php/session/enter/1"
Any ideas on how I can make it call the enter() function also in the session controller (shown below)
public function enter($id) {
$this->load->view('_header');
$this->load->view('session/enter');
$this->load->view('_footer');
}
There seems to be a typo in the string concatenation in your PHP code. Perhaps it will work to use:
site_url("session/enter" . $session_item['id'])
... rather than a + sign between the two strings.
Regarding the second question - it looks correct as-is. Is it failing to call the session controller's enter() function passing the $id as an argument (assuming the URL is correct)?.