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

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))
{

Related

Unable to insert checked value into database

Currently I have a permissions table where the user can use a checkbox to give access or revert access for a URL link to a user with a particular role. So for this I've made it so that when a checkbox is pressed, the id of that checkbox and the role of the user are inserted in my database, but I'm unable to insert it in the database for some reason. I've tried the following code:
Controller Class:
public function permission()
{
if ($this->form_validation->run() == FALSE)
{
$main['permissions']=$this->users_model->get_permission_array();
$main['roles']=$this->users_model->get_roles_array();
foreach($main['roles'] as $key => $val):
$main['access'][$val['roles_id']]=$this->users_model->get_access_array(array('roles_id'=>$val['roles_id']));
endforeach;
$main['page'] = 'crm/users/permission';
$this->load->view('crm/index', $main);
}
if($this->input->post())
{
$loginid=false;
foreach($main['roles'] as $key => $val):
if(isset($_POST['roleid'.$val['roles_id']])){
$this->users_model->clear_access(array('roles_id'=>$val['roles_id']));
foreach($_POST['roleid'.$val['roles_id']] as $id => $access):
$data=array('roles_id'=>$val['roles_id'],'permissions_id'=>$access);
$loginid=$this->users_model->permission_access($data);
endforeach;
}
endforeach;
if($loginid){
$this->session->set_flashdata('message', '<p>Permission updated Successfully.</p>');
redirect('users/permission');
} else {
$this->session->set_flashdata('message', '<p>Error!! - Permission not updated.</p>');
redirect('users/permission');
}
}
}
Model Class:
function get_permission_array()
{
$query = $this->db->get("crm_client_permissions");
return $query->result_array();
}
function get_access_array($cond)
{
$this->db->select("permissions_id");
$this->db->where($cond);
$query = $this->db->get("crm_client_role_access");
return $query->result_array();
}
function clear_access($cond)
{
return $this->db->delete("crm_clients_access",$cond);
}
function permission_access($data)
{
return $this->db->insert("crm_clients_access",$data);
}
function get_roles_array($cond='')
{
if($cond !='') $this->db->where($cond);
$query = $this->db->get("crm_client_roles");
return $query->result_array();
}
View Class:
<div <?php echo form_open_multipart('users/permission'); ?>>
<table>
<?php if($permissions) $i=0;foreach($permissions as $key => $permission): ?>
<tr>
<td class="align-center"><?php echo ++$i; ?></td>
<td><?php echo $permission['page']; ?></td>
<td><?php echo $permission['url']; ?></td>
<?php foreach($roles as $rolekey => $role):
if($role['roles_id'] == 1)$checked = 'checked';
if(in_array($permission['permissions_id'],array_map('current',$access[$role['roles_id']])))
$checked = 'checked';
else
$checked = ''; ?>
<td align="center"><div class="checkbox checkbox-success m-t-0"><input type="checkbox" class="accessbox"
id="role<?php echo $rolekey ?>-<?php echo $key ?>" name="roleid<?php echo $role['roles_id']; ?>[]"
<?php echo $checked?> <?php echo ($role['roles_id'] == 1) ? 'disabled="disabled"' : '' ?> value="<?php echo $permission['permissions_id']; ?>" />
<label for="role<?php echo $rolekey ?>-<?php echo $key ?>"></label></div></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
<div class="text-center">
<button type="submit" class="btn btn-info">Save Permission</button> Cancel
</div>
<?php echo form_close(); ?> </div>
But here I always get Error!! - Permission not updated. in my view class which means it jumps to the else part of my controller. I'm not sure where I'm going wrong here
It seems problem is here $loginid=$this->users_model->permission_access($data); and here return $this->db->insert("crm_clients_access",$data);.
My advise is to:
use XDebug to debug your code and see what insert function returns and why.
Also you may look for php log to see if there is any database errors. To use error logs you need to find php.ini config file and enable line 'error_log = /path/to/fige.log'.
Also you may to lookup the database data to determine if insert function makes new row in table crm_clients_access, if it doesn't? you need to check your connection config to database host:port, so database process must be available at theese host:port.

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.

Fatal error: Uncaught ArgumentCountError: Too few arguments to function Admincategory::deletecategory(),

I know there were some questions related to this, but there are c ++ or other languages. I get this error and I'm not sure what's wrong with my function.
This is my Error
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Admincategory::deletecategory(), 0 passed in F:\xampp\htdocs\digikalamvc\core\app.php on line 34 and exactly 1 expected in F:\xampp\htdocs\digikalamvc\controllers\admincategory.php:50 Stack trace: #0 F:\xampp\htdocs\digikalamvc\core\app.php(34): Admincategory->deletecategory() #1 F:\xampp\htdocs\digikalamvc\index.php(6): App->__construct() #2 {main} thrown in F:\xampp\htdocs\digikalamvc\controllers\admincategory.php on line 50
And my function is:
<?php
class Admincategory extends Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$category = $this->model->getChildren(0);
$data = ['category' => $category];
$this->view('admin/category/index', $data);
}
function showchildren($idcategory)
{
$categoryInfo = $this->model->categoryInfo($idcategory);
$children = $this->model->getChildren($idcategory);
$parents = $this->model->getParents($idcategory);
$data = ['categoryInfo' => $categoryInfo, 'category' => $children, 'parents' => $parents];
$this->view('admin/category/index', $data);
}
function addcategory($categoryId = 0, $edit = '')
{
if (isset($_POST['title'])) {
$title = $_POST['title'];
$parent = $_POST['parent'];
$this->model->addCategory($title, $parent, $edit, $categoryId);
}
$category = $this->model->getCategory();
$categoryInfo = $this->model->categoryInfo($categoryId);
$data = ['category' => $category, 'parentId' => $categoryId, 'edit' => $edit, 'categoryInfo' => $categoryInfo];
$this->view('admin/category/addcategory', $data);
}
function deletecategory($parentId)
{
$ids = $_POST['id'];
$this->model->deletecategory($ids);
header('location:'.URL.'admincategory/showchildren/'.$parentId);
}
}
?>
app.php file
<?php
class App
{
public $controller = 'index';
public $method = 'index';
public $params = [];
function __construct()
{
if (isset($_GET['url'])){
$url = $_GET['url'];
$url = $this->parseUrl($url);
$this->controller = $url[0];
unset($url[0]);
if (isset($url[1])){
$this->method = $url[1];
unset($url[1]);
}
$this->params = array_values($url);
}
$controllerUrl = 'controllers/' . $this->controller . '.php';
if (file_exists($controllerUrl)) {
require($controllerUrl);
$object = new $this->controller;
$object->model($this->controller);
if (method_exists($object, $this->method)) {
call_user_func_array([$object, $this->method], $this->params);
}
}
}
function parseUrl($url)
{
$url = filter_var($url, FILTER_SANITIZE_URL);
$url=rtrim($url,'/');
$url = explode('/', $url);
return $url;
}
}
?>
and index.php
<?php
require('views/admin/layout.php');
$category = $data['category'];
$categoryInfo = [];
if (isset($data['categoryInfo'])) {
$categoryInfo = $data['categoryInfo'];
}
$parents = [];
if (isset($data['parents'])) {
$parents = $data['parents'];
$parents = array_reverse($parents);
}
?>
<style>
.w400 {
width: 600px;
}
</style>
<div class="left">
<p class="title">
مدیریت دسته ها
(
<?php foreach ($parents as $row) { ?>
<a href="admincategory/showchildren/<?= $row['id']; ?>">
<?= $row['title']; ?>
</a>
-
<?php } ?>
<a href="admincategory/<?php if (isset($categoryInfo['id'])) {
echo 'showchildren/' . $categoryInfo['id'];
} else {
echo 'index';
} ?>">
<?php
if (isset($categoryInfo['title'])) {
echo $categoryInfo['title'];
} else {
echo 'دسته های اصلی';
}
?>
</a>
)
</p>
<a class="btn_green_small" href="admincategory/addcategory/<?= #$categoryInfo['id']; ?>">
افزودن
</a>
<a class="btn_red_small" onclick="submitForm();">
حذف
</a>
<form action="admincategory/deletecategory/<?= #$categoryInfo['id']; ?>" method="post">
<table class="list" cellspacing="0">
<tr>
<td>
ردیف
</td>
<td>
عنوان دسته
</td>
<td>
مشاهده زیر دسته ها
</td>
<td>
ویرایش
</td>
<td>
انتخاب
</td>
</tr>
<?php
foreach ($category as $row) {
?>
<tr>
<td>
<?= $row['id']; ?>
</td>
<td class="w400">
<?= $row['title']; ?>
</td>
<td>
<a href="admincategory/showchildren/<?= $row['id']; ?>">
<img src="public/images/view_icon.png" class="view">
</a>
</td>
<td>
<a href="admincategory/addcategory/<?= $row['id']; ?>/edit">
<img src="public/images/edit_icon.ico" class="view">
</a>
</td>
<td>
<input type="checkbox" name="id[]" value="<?= $row['id']; ?>">
</td>
</tr>
<?php } ?>
</table>
</form>
</div>
</div>
============
Thank you for trying to help!
Sometimes it happen that AdminCategory::deletecategory($parentId) is called without a parameter but prototype do not have a default value for it and therefore exception is thrown. Since you get data from a post request and there is always a possibility that a category do not have a parent you can refactor your method to looks like:
function deletecategory($parentId = null)
{
$ids = $_POST['id'];
$this->model->deletecategory($ids);
if (null !== $parentId) {
header('location:'.URL.'admincategory/showchildren/'.$parentId);
}
// PUT MORE OF YOUR LOGIC HERE, I DO NOT KNOW WHAT SHOULD HAPPEN
}
If you are using typing hints more appropriate would be to make method looks like
function deletecategory(string $parentId = ''): void //void is for php7.1
{
$ids = $_POST['id'];
$this->model->deletecategory($ids);
if ('' !== $parentId) {
header('location:'.URL.'admincategory/showchildren/'.$parentId);
}
// AGAIN LOGIC HERE
}
If you REALLY expect that parentId MUST be passed then instead wrap method caller with try catch
if (method_exists($object, $this->method)) {
try {
call_user_func_array([$object, $this->method], $this->params);
} catch (\Exception $ex) {
// HANDLE EXCEPTION HERE
}
}

Can't define variable for link to edit page

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 } ?>

How to returning mysql_fetch_array in function

I have some question about MySQL in PHP.
This is my config code:
<?php
class Core{
public $connect;
public function __construct(){
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'fix';
$this->connect = new mysqli($host,$user,$password,$database);
if(!$this->connect) echo mysql_error();
}
public function siteTitle(){
$title = "title";
$tagline = "tagline";
return $title. " - ".$tagline;
}
public function load($file,$data){
extract($data);
require "$file.php";
}
public function searchResult(){
$query = $this->connect->query("SELECT * FROM `location`");
if($query->num_rows > 0){
$columns = $query->fetch_assoc();
return $columns;
}
}
public function locationStatus($id){
$location = $this->searchResult();
$locationId = $location['id'];
if($locationId == 1){
echo "Available <i class='ui icon circle green'></i>";
}elseif($locationId == 2){
echo "Under Counstruction <i class='ui icon circle orange'></i>";
}else{
echo "Unavailable <i class='ui icon circle red'></i>";
}
}
}
?>
I will display a result from searchResult() function in searchResult.php file:
<div style='border:1px solid #ccc; padding:3px;'>
<img src="asset/images/<?php echo "$data[image].jpg"; ?>" class='ui image medium' style='padding-right:10px;float:left' />
<h2 style='font-family:nexa;color:rgb(36,162,217);line-height:0;'><?php echo $data['title']; ?></h2>
<h4><span style='color:orange;'>Location Address: </span><?php echo $data['subtitle']; ?></h4>
<p><?php echo $data['description']; ?></p>
<br />
<p>
<i class='ui icon marker big orange'></i>Checkin: <?php echo $data['checkin']; ?> <i class='ui icon clock big orange'></i>Published at: <?php echo $data['published']; ?> Status: <?php echo $this->locationStatus($data['id']); ?>
</p>
<a style='' href='location/<?php echo $data['slug']; ?>' class='ui button blue'>READ MORE</a>
</div>
And the searchResult.php, i call it in Index.php with code:
<?php echo $this->load('templates/searchResult', $this->searchResult()); ?>
My question is:
Why the result from my sql query is not a looping? Although, I was looping it with a while loop?
Thanks. Sorry if my language is bad.
If you want to call your View like this
<?php
echo $this->load('templates/searchResult', $this->searchResult());
?>
You will have to put the loop in the searchResult() method, so that this one call will return all the rows.
public function searchResult(){
$query = $this->connect->query("SELECT * FROM `location`");
$rows = array();
if($query->num_rows > 0){
while ( $row = $query->fetch_assoc() ) {
$rows[] = $row;
}
}
return $rows;
}
Then in your View, loop over $data
public function searchResult(){
$query = $this->connect->query("SELECT * FROM `location`");
if($query->num_rows > 0){
while ($columns = $query->fetch_assoc())
{
$data[] = $columns;
}
}
return $data;
}
You need the while loop in the searchResult function.

Categories