Can't define variable for link to edit page - php

I am building a blog and trying to create a link that goes to an edit page. My database table blog_posts has the following variables: postDate, postID, userId, postDesc. They all display correctly on my render page for each blog record.
I now am trying to create a link to my edit page and having trouble getting my $blog['edit'] variable below to work. I have tried defining it in both the Model and controller - no luck.
Thanks for any help.
CONTROLLER:
public function indexAction() {
$request = $this->getRequest();
$this->view->blogs = Blog_Model_Blog::findAll();
$blogs = Blog_Model_Blog::getAllBlogEntries();
if($blogs) {
foreach($blogs AS $blog) {
$blog['edit'] = WM_Router::create($this->getRequest()->getBaseUrl() . '?module=blog&controller=admin&action=edit&id=' . $blog['postID']);
$this->view->blogs[] = $blog;
}
}
}
MODEL:
public static function getAllBlogEntries() {
$db = JO_Db::getDefaultAdapter();
$query= $db->select ()
-> from ('blog_posts',array('*'))
-> order ('blog_posts.postDate DESC');
return $db->fetchAll($query);
}
public static function findAll($_callbackQuery = null) {
$blog = parent::findAll($_callbackQuery);
return $blog;
}
VIEW:
<?php if ($this->blogs) { ?>
<?php foreach ($this->blogs AS $blog) { ?>
<tr id="<?php echo $blog->postID; ?>">
<td><?php echo $blog->postID; ?></td>
<td><?php echo $blog->userId; ?></td>
<td align="center">
<img title="<?php echo $this->translate('Edit');?>" alt="" class="tooltip" src="cms/admin/images/edit.png">
</td>
</tr>
<?php } ?>
<?php } ?>

Related

How to fetch and display data at the same time from MYSQL using PHP

I am unable to display data from a table from a MYSQL database using PHP OOP. However, I'm not sure if I'm unable to display the data because I'm not actually fetching the data in the first place.
I've tried fetching and displaying the data using only a PHP array and no HTML in my method and I figured this wouldn't be working because I wasn't using HTML list tags to format the data from the database. I've considered using a HTML table but I have seen displays from databases using lists work a few times before and I want to know why this doesn't work how it should.
I've tested for MYSQL connection and it does exist.
* M_PRODUCTS.PHP *
<?php
class Products
{
private $Conn;
private $db_table = "toys";
function __construct() {
// here we're making sure that the connection from $conn in "init.php" is transferred
// into our own private $conn property for usage in this object
global $Conn;
$this->Conn = $Conn;
}
// fetches and displays all products from db
public function fetch_all_products($id = NULL)
{
if ($id == NULL)
{
$data = [];
if ($result = $this->Conn->query("SELECT * FROM " . $this->db_table . " ORDER BY name"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_array())
{
$data = array(
"id" => $row["product_id"],
"name" => $row["name"],
"price" => $row["price"],
"image" => $row["image"]
);
}
return $data;
}
else
{
return "<h1>Oops... Something went wrong!</h1>";
}
}
}
}
}
* INDEX.PHP *
<?php include("init.php");
include("models/m_products.php");
?>
<body>
<div id="whitespace">
<?php
$products = fetch_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" alt="<?php echo $row->name; ?>" width="100" /></td>
</tr>
<?php } ?>
</div>
</body>
I expect the images of my products to be displaying in my index.html file. However, nothing appears.
I also get this error message in the JavaScript console: Failed to load resource: the server responded with a status of 404 (Not Found). This would explain a lot but as I said I tested my database connection and it works. I'm not sure how or why this message is coming from the JavaScript console if I'm not using JavaScript. I thought it would be worth mentioning anyway.
According to your code the function returns some data, but the thing is that you have not printed it, so instead of return in the function you can use echo or just put
echo $Products->fetch_all_products();
Strange code, I would do something like that.
1. First the function find all()
2. index.php echo - output
<?php
$products = find_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" width="200" /></td>
</tr>
<?php } ?>
There are 2 major issues I can see in your code
1) you need to update your comparison operator from
if ($id = NULL)
to
if ($id == NULL)
2) you need to update your code in index.php from
<body>
<div id="whitespace">
<h1><?php echo shop_name ?></h1>
<?php
echo $Products->fetch_all_products();
?>
</div>
</body>
to
<body>
<div id="whitespace">
<?php
$products = find_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" alt="<?php echo $row->name; ?>" width="100" /></td>
</tr>
<?php } ?>
</div>
</body>
I hope it will sort out your issue
Correct your comparison operator it should be.
if ($id == NULL)
instead of
if ($id = NULL)
in your function fetch_all_products().
correct the code in index.php to print an array use print_r() or loop through the result array.

get result by category id in codeigniter

I need to get the the subcategories of its categories in codeigniter.
I am stuck at passing category id to the my model method
my code is below :
this is my view : index.php
<ul class="list-inline">
<?php
if($category->num_rows() > 0)
{
foreach ($category->result() as $row)
{
?>
<li><img class="img-responsive center-block" width="80px" src="<?php echo base_url(); ?>assets/admin/uploads/category/<?php echo $row->cat_home_image; ?>" alt="icon" title="icon" class="img-responsive" /><p style="font-size:16px;"><?php echo $row->category_description; ?> </p></li>
<?php
}
}
?>
</ul>
this is my controller : Main.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public function index()
{
$this->load->model("category_model");
$data["category"] = $this->category_model->fetch_category();
$this->load->model("ads_model");
$data["ads"] = $this->ads_model->fetch_home_ads();
$this->load->view('index',$data);
//$this->load->view('category');
}
public function getsubcategory()
{
$this->load->model("category_model");
$data["subcategory"] = $this->category_model->fetch_subcategory();
$this->load->view('category',$data);
}
}
this is my Model : category_model.php
<?php
class Category_model extends CI_Model
{
function fetch_category()
{
$query = $this->db->query("SELECT * FROM category AS c INNER JOIN category_language AS cl ON c.id=cl.category_id where parent_id IS NULL && lang_id='1' && c.id!='4' ORDER BY category_description");
return $query;
}
function fetch_subcategory()
{
$subcat = $this->db->query("SELECT * FROM category AS c INNER JOIN category_language AS cl ON c.id=cl.category_id where parent_id='1' && lang_id='1' ORDER BY category_description");
return $subcat;
}
}
?>
How to pass the category id to model to get the appropriate subcatory of category_id
Hope this will help you :
Your view should be like this :
<ul class="list-inline">
<?php
if($category->num_rows() > 0)
{
foreach ($category->result() as $row)
{?>
<li>
<a href="<?=site_url('main/getsubcategory/'.$row->id);?>">
<img class="img-responsive center-block" width="80px" src="<?=site_url('assets/admin/uploads/category/'.$row->cat_home_image); ?>" alt="icon" title="icon" class="img-responsive" />
<p style="font-size:16px;"><?php echo $row->category_description; ?> </p>
</a>
</li>
<?php
}
}
?>
</ul>
Your controller's getsubcategory method should be like this :
public function getsubcategory($id)
{
if ($id)
{
$this->load->model("category_model");
$data["subcategory"] = $this->category_model->fetch_subcategory($id);
$this->load->view('category',$data);
}
}
Your model method fetch_subcategory should be like this :
Note : make sure all column name belongs to correct table alias
function fetch_subcategory($id)
{
$this->db->select('*');
$this->db->from('category c');
$this->db->join('category_language cl', 'cl.category_id = c.id');
/* Use $id here like this
$this->db->where('parent_id', $id);
*/
$this->db->where('c.parent_id', '1');
$this->db->where('cl.lang_id', '1');
$this->db->order_by('c.category_description', 'DESC');
$result = $this->db->get()->result();
return $result;
}

echo user information on a product not working in codeigniter

I have been trying to echo user information on a product but its not working. I used to try it with this join function in my model :
public function getdata()
{
$this->db->select('*');
$this->db->from('users');
$this->db->join('products','products.user_id = users.user_id');
$query = $this->db->get();
if($query->num_rows()>0)
{
return $query->result_array();
}
}
It didn't work properly because it echoed for example all the usernames from the database when I tried to echo a username that belongs to the same user_id.
Now I tried to do it like this:
This is my Controller function (AlleCadeausController):
public function index()
{
/** Laad de models **/
$this->load->model('Product_model');
$selectProducts = $this->Product_model->selectProducts();
foreach ($selectProducts as $key => $product)
{
# first name
$user = $this->Product_model->get_user_name($product['user_id']);
#append both NEW VALUES to same array
$data[$key]['voornaam'] = $user[0]['voornaam'];
}
/** Make $data **/
$data['products'] = $this->Product_model->selectProducts();
/** Laad de allecadeaus view en geef $data mee **/
$this->load->view('allecadeaus', $data);
}
My model functions in my Prduct_model.php file:
public function selectProducts()
{
$query= $this->db->query("SELECT * FROM products");
$result = $query->result_array();
return $result;
}
function get_user_name($name)
{
$query= $this->db->query("SELECT voornaam FROM users WHERE user_id = $name ");
$result = $query->result_array();
return $result;
}
And this is how I tried to echo the user information in the product foreach loop in the view:
<?php foreach($products as $product) : ?>
<a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">
<div class="main-products">
<img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">
<div class="product_naam"><?php echo $product["product_naam"]; ?></div>
<div class="ophaal_plaats"><?php echo $product["ophaal_plaats"]; ?></div>
</div>
</a>
<div class="aangeboden_door">
<p>
<tr>
<a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
<td><?php echo $product['voornaam'];?></td>
</tr>
</p>
</div>
<?php endforeach; ?>
at this line :
<td><?php echo $product['voornaam'];?></td>I try to echo the first
name of the user of the product but its not working.
The PHP error that I'm receiving is: undefined index: voornaam , line: 55 which is this line: <td><?php echo
$product['voornaam'];?></td>
Database information of both tables products and users:
Table 1 : products:
product_id
product_naam
product_beschrijving
user_id
ophaal_plaats
product_foto
product_foto_thumb
date_created
date_updated
category_id
table 2 : users:
user_id
email
voornaam
achternaam
beschrijving
profiel_foto
You can use the active records instead of create multiple function:
Your controller:
public function index()
{
$data = array();
$this->load->model('product_model');
$data['products'] = $this->product_model->selectProducts();
$this->load->view('allecadeaus', $data);
}
Your view:
Your view:
<?php foreach($products as $product) : ?>
<a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">
<div class="main-products">
<img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">
<div class="product_naam"><?php echo $product["product_naam"]; ?></div>
<div class="ophaal_plaats"><?php echo $product["ophaal_plaats"]; ?></div>
</div>
</a>
<div class="aangeboden_door">
<p>
<tr>
<?php
//Here is the active record query which is getting the 'voorname' and other data
$userarray = $this->db->get_where('users', array('user_id'=>$product["user_id"]))->row_array();
// you can print_r($userarray); for see the array you get
?>
<a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
<td><?php echo $userarray['voornaam'];?></td>
</tr>
</p>
</div>
<?php endforeach; ?>

Echo user info on another users profile page

I'm trying to make a function in the CodeIgniter framework so users can click on product detail page, and see which user uploaded that certain product and they must be able to click on the product owner to go to his profile page.
Now, I am already able to echo owner information of the product owner on the details page. But the link to the owner profile page is not working some reason and the name isn't echoed anymore since I tried to make it a link.
This is my product details page (details.php) foreach loop function where I'm trying to echo the username of the owner of a product and link it to their profile page:
<?php include_once ('templates/header.php'); ?>
<div class="container">
<h3>Email van de eigenaar:</h4>
<?php
foreach ($userdetail_list as $row) {
?>
<tr>
<td><?php echo $row['email']; ?></td>
</tr>
<?php } ?>
</div>
<div class="container">
<div class="row">
<div class="col-md-4" style="margin-top:24px;">
<img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" class="img-responsive">
</div>
<div class="col-md-5">
<h1> <div class="product_naam"> <?php echo $product['product_naam']; ?> </div> </h1>
<h3>Over dit cadeau</h3>
<div class="product_beschrijving"><?php echo $product['product_beschrijving']; ?> </div>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-default">Cadeau aanvragen</button>
<div class="aangeboden_door"> Aangeboden door: <?php
foreach ($userdetail_list as $row) { ?>
<tr>
<td><?= $row['username']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="container">
<footer>
<p>© kadokado 2017, Inc.</p>
</footer>
<hr>
</div>
<div class="clearfix"></div>
<?php include_once ('templates/footer.php'); ?>
When I load this view file I do see the echoeod email but not the username? And there is also no link to the users profile page..
Here is my controller file (User.php):
<?php
class User extends CI_Controller {
public function index() {
$this->load->view('profile', $data);
}
public function __construct() {
parent::__construct();
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error", "Please login first to view this page!! ");
redirect("auth/login");
}
}
public function userdetails($user_id) {
//load the User_model
$this->load->model('User_model');
//call function getdata in de Product_model
$data['userdata_list'] = $this->User_model->getdata();
//get product details
$data['user'] = $this->User_model->get_user_info($user_id);
//laad view
$data['main_content'] = 'profiel_user';
$this->load->view('profiel_user', $data);
}
public function profile() {
$this->load->model('User_model');
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error", "Please login first to view this page!! ");
redirect("auth/login");
}
$this->load->view('profile');
}
}
?>
And here is my model (User_model.php) :
<?php
public function getdata()
{
$this->db->where('user_id', $id);
$this->db->from('users');
$query = $this->db->get();
if($query->num_rows()>0)
{
return $query->result_array();
}
}
public function getUserInfo($user_id) {
$q = $this->db->get_where('users', array('user_id' => $user_id), 1);
if ($this->db->affected_rows() > 0) {
$row = $q->row();
return $row;
} else {
error_log('no user found getUserInfo(' . $user_id . ')');
return false;
}
}
?>
Database information:
I have 2 tables:
users:
user_id
voornaam
achternaam
email
password
(products:
product_id
product_name
product_description)
I hope someone can help me,
Thanks!
You are concatenating user name in anchor tag herf separate it and write between <a> and </a>
change your code as below:
<tr>
<td><?=$row['username']; ?></td>
<td><?php echo $row['email'];?></td>
</tr>
You can try this solution for your problem.
Please change your view file.
details.php
<tr>
<td><?= $row['username']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
and please changes your controller function:
User.php
<?php
public function profiel_user($user_id) {
$this->load->model('User_model');
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error", "Please login first to view this page!! ");
redirect("auth/login");
}
$data['user_id'] = $user_id; // you can used user id for getting data
$this->load->view('profile');
}
?>
Thanks

How to show table values in php using PDO [duplicate]

This question already has answers here:
PDO get data from database
(3 answers)
Closed 6 years ago.
I'm trying to show table values from database by using PDO but while doing this it shows an error
"Fatal error: Call to undefined method ManageUsers::fetchAll()"
Please provide solution to solve this?
list-seller.php
<?php
include "C:/wamp/www/Super_Admin_MangoAir/classes/class.ManageUsers.php";
$sellers = new ManageUsers();
//$sellers->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
while ($row = $sellers->fetchAll(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['company_name']; ?>
<span class="pull-right-container">
<small class="label pull-center bg-green">Premium Member</small>
</span>
</td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['mobile']; ?></td>
<td><?php echo $row['count_free']; ?></td>
<td><?php echo $row['count_travel']; ?>
<span class="pull-right-container">
<small class="label pull-center bg-green">Paid</small>
</span>
</td>
<td><button type="button" class="btn btn-flat btn-default btn-sm disabled">Already Paid</button></td>
</tr>
<?php } ?>
class.ManageUsers.php
<?php
class ManageUsers{
include "C:/wamp/www/Super_Admin_MangoAir/classes/class.database.php";
public $link;
function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
function seller_list($result){
$result = $this->link->prepare("SELECT company_name,email,phone,count_free,count_travel FROM login");
$result->execute();
}
}
?>
class.database.php
<?php
class dbConnection{
protected $db_conn;
public $db_name='company';
public $db_user='root';
public $db_pass='';
public $db_host='localhost';
function connect (){
try{
$this->db_conn=new PDO("mysql:host=$this->db_host;dbname=$this->db_name",$this->db_user,
$this->db_pass);
return $this->db_conn;
}
catch(PDOException $e){
return $e->getMessage();
echo 'errorrrrrrrr';
}
}
}
?>
Changes
1) Remove include "C:/wamp/www/Super_Admin_MangoAir/classes/class.database.php"; from class ManageUsers (inside) and place it above.
2) Add public before seller_list().
3) call seller_list() in list-seller.php page.
4) Missed return keyword in function seller_list(). Add it.
5) Remove $result from seller_list() function in Class ManageUsers as it is of no use.
Updated Code
list-seller.php
<?php
include "C:/wamp/www/Super_Admin_MangoAir/classes/class.ManageUsers.php";
$sellers = new ManageUsers();
$query = $sellers->seller_list();
foreach($query as $row){
?>
<tr>
<td><?php echo $row['company_name']; ?>
<span class="pull-right-container">
<small class="label pull-center bg-green">Premium Member</small>
</span>
</td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['mobile']; ?></td>
<td><?php echo $row['count_free']; ?></td>
<td><?php echo $row['count_travel']; ?>
<span class="pull-right-container">
<small class="label pull-center bg-green">Paid</small>
</span>
</td>
<td><button type="button" class="btn btn-flat btn-default btn-sm disabled">Already Paid</button></td>
</tr>
<?php } ?>
class.ManageUsers.php
<?php
include "C:/wamp/www/Super_Admin_MangoAir/classes/class.database.php";
class ManageUsers{
public $link;
function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
}
public function getDB(){
return $this->link;
}
public function seller_list(){
$result = $this->getDB()->prepare("SELECT company_name,email,phone,count_free,count_travel FROM login");
$result->execute();
return $result->fetchAll();
}
}
?>
Try to remove return $this->link from your constructor and call fetchAll using $sellers->link->fetchAll(PDO::FETCH_ASSOC)
The constructor of a given class can only return instance of said class, no other return value.
See Constructor returning value?
I'd suggest this instead for your class:
class ManageUsers
{
include "C:/wamp/www/Super_Admin_MangoAir/classes/class.database.php";
private $link;
public function __construct()
{
$db_connection=new dbConnection();
$this->link=$db_connection->connect();
}
public function getLink()
{
return $this->link;
}
And use the last function.
//list-seller.php//
<?php
include "C:/wamp/www/Super_Admin_MangoAir/classes/class.ManageUsers.php";
$manager = new ManageUsers();
$sellers = $manager->getLink();
You need to add a sql query which shows data from table. Try to add these lines in list-seller.php after $sellers = new ManageUsers();:
$sql = 'SHOW TABLES';
$sellers->query($sql);
while ($row = $sellers->fetchAll(PDO::FETCH_ASSOC))
{

Categories