how can I show all the users in the users table in the database in a html table?
I have to show all the users in a html table and each user can be selected using a check box. The selected users are then deleted from the database.
I am using the technique mvc and I have a page "DeleteUser" that contains only the html, a controller and a public file.
View/DeleteUser.php contains:
<form method="post" action="../public/deleteUser.php">
<table>
<tr>
<td>#</td>
<td>Username</td>
<td>First name</td>
<td>Last name</td>
<td>City</td>
<td>Gender</td>
<td>E-mail</td>
<td>Check</td>
</tr>
<tr>
<td><input type="submit" name="submit-deleteuser" value="Delete user"/></td>
</tr>
</table>
</form>
public/deleteUser.php contains:
$controller = new DeleteUserController();
$view = $controller->invoke();
$view->render();
The invoke() method in Controller/DeleteUserController.php contains:
class DeleteUserController {
public $user;
public $users;
public $userRepository;
public $view;
public function __construct() {
$username = $_SESSION['username'];
$this->userRepository = new UserRepository();
$this->user = $this->userRepository->findByUsername($username);
$this->users = array();
$this->view = new View('DeleteUser');
$db = Database::getInstance();
}
public function listUsers() {
$this->users = $this->userRepository->fetchAll();
foreach($this->users as $u) {
$str = "<tr>
<td><?php $u->getId() ?></td>
</tr>";
}
}
public function deleteUsers() {
if(isset($_POST['submit-deleteuser'])) {
$del_id = $_POST['users'];
foreach($del_id as $value) {
$value->delete();
}
}
}
public function work() {
$this->listUsers();
$this->deleteUsers();
}
public function invoke() {
$this->work();
$this->view->setData('user', $this->user);
return $this->view;
}
If I had not had to use mvc I would have done so:
<table>
<tr>
<td>#</td>
<td>Username</td>
<td>Fisrt name</td>
<td>Last name</td>
<td>City</td>
<td>Gender</td>
<td>E-mail</td>
<td>Check</td>
</tr>
<?php
$utente = $_SESSION['username'];
$query = "SELECT * FROM users ORDER BY id";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo "<tr>
<td>$row[id]</td>
<td>$row[username]</td>
<td>$row[fisrt_name]</td>
<td>$row[last_name]</td>
<td>$row[city]</td>
<td>$row[gender]</td>
<td>$row[email]</td>
<td><input type=\"checkbox\" name=\"users[]\" value=\"" .$row['id']. "\"></td>
</tr>";
}
}
?>
<tr>
<td colspan="9"><input type="submit" name="submit-deleteuser" value="Delete users"/></td>
</tr>
</table>
But now I do not know how to do. The two methods listUsers() and deleteUsers() are wrong and do not know how to complete them or correct them.
First it was simple, I put the php code that showed users in the html tag that I wanted (<table>...</table>) but now?
I do not know how to handle this thing.
Give me advice? Thank you :)
fetchAll() is:
public function fetchAll(){
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM `users`");
$stmt->execute();
$users = array();
while($result = $stmt->fetch()) {
$users[] = User::load($result);
}
return $users;
}
The attempt to use the MVC pattern is admirable, but a little bit off in this case :). What is missing, is the concept of controller actions.
Maybe try to restructure your code something like this:
Directory Structure
controllers/
UsersController.php
models/
UsersModel.php
core
View.php
views/
header.tpl.php
footer.tpl.php
users/
list.tpl.php
delete.tpl.php
users.php
1. Start with a users model that interacts with the database
class UsersModel {
public function fetchAll() {
$result = array();
// Build SELECT query, fetch all users from db., and store in $result
// ...
return $result;
}
public function deleteMany(array $ids) {
$result = array();
// Build DELETE query, execute it, and store the number of affected records in $result
// ...
return $result;
}
}
2. Make a UsersController instead of a DeleteUserController. Create two methods: listUsersAction and deleteUsersAction.
class UsersController {
public function listUsersAction() {
$model = new UsersModel();
$data = $model->fetchAll();
return new View(
'users/list',
$data
);
}
public function deleteUsersAction() {
// This is simplistic, but the idea is to get the required input from the request (and actually validate it!)
// Also see the users/list template further down
$ids = $_POST['user_ids'];
$model = new UsersModel();
$numRecords = $model->deleteMany($ids);
return new View(
'users/delete',
array('deleted_records' => $numRecords)
);
}
}
3. Our View class should store the template name and the view data, and be able to render the template
class View {
public static $viewDirectory;
public $template;
public $data = array();
public function __construct($template, $data) {
if (!View::$viewDirectory) {
View::$viewDirectory = dirname(__FILE__) . '/views/';
}
$this->template = $template;
$this->data = $data;
}
public function render() {
// Make the data available in the template
$data = $this->data;
// Include the template.
require(realpath(View::$viewDirectory . $this->template . '.tpl.php'));
}
}
4. The users/list template could then look something like this
// views/users/list.tpl.php
<form action="/users.php?action=delete" method="post">
<?php foreach ($data as $user): ?>
<div>
<input type="checkbox" name="user_ids[<?= $user['id'] ?>]" value="1"/>
<?= $user['username'] ?>
</div>
<?php endforeach; ?>
</form>
5. Tie everything together in users.php
<?php
// users.php
// (include all previously defined classes here)
// We'll want to include a HTML header of some sort:
include("views/header.tpl.php");
/**********
* Poor man's routing; valid urls:
* /users.php?action=listUsers
* /users.php?action=deleteUsers with POST data
*/
// Determine the action from the GET parameter. If no action is set, the default action is listUsers
//$action = (array_key_exists('action', $_GET) ? $_GET['action'] : 'listUsers');
// Equivalent of:
if (array_key_exists('action', $_GET)) {
$action = $_GET['action'];
} else {
$action = 'listUsers';
}
//--
$actionMethod = $action . 'Action';
$controller = new UsersController();
if (method_exists($controller, $actionMethod)) {
$view = $controller->$actionMethod();
$view->render();
} else {
echo "<div class='error'>The action '$action' is invalid for the Users controller.'</div>";
}
// We'll want to include a footer as well:
include("views/footer.tpl.php");
?>
Related
How i can use a sql-query code that i already have on Zend-Framework using Model and Controller?
I'm tried of many ways and i can't solve this.
This is a example of "common sql-query code" to test:
"SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 100"
*My original code it's a big query and it's terrible transform to a zend-select()
This is my Model:
class PedidosInscricoesModel extends Zend_Db_Table_Abstract{
protected $_name = 'sa_arquivos_retorno';
public function getPedidosInscricoes(array $params) {
$this->_db = Zend_Registry::get('db2');
$session = new Zend_Session_Namespace('autenticacao');
$query = $this->query("SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 100");
$retorno = $this->fetchAll($query)->toArray();
return $retorno;
}}
And That's my Controller:
public function indexAction()
{
$PedidosInscricoesModel = new PedidosInscricoesModel();
$this->view->id_arquivos_retorno = $_REQUEST['id_arquivos_retorno'];
$params = $this->_request->getParams();
$data = $PedidosInscricoesModel->getPedidosInscricoes($params);
$this->view->data = $retorno;
}
My index view:
<?php
foreach($this->data as $dados) {
?>
<tr>
<td><?php echo $dados["id_arquivos_retorno"]; ?></td>
</tr>
<?php
}
?>
-Sorry for bad english guys
I got it!
Just modifying the Model using "zend_db_statement" in this way:
class PedidosInscricoesModel extends Zend_Db_Table_Abstract{
public function getPedidosInscricoes()
{
$db = Zend_Registry::get('db2');
$sql = "SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 20";
$stmt = $db->query($sql);
$retorno = $stmt->fetchAll();
return $retorno;
}
}
I want to create a loop for my database result. But I can't make it work on my VIEW file.
So here's my model:
<?php class Dash_model extends CI_Model {
public function __construct()
{
parent::__construct();
// Loading second db and running query.
$CI = &get_instance();
//setting the second parameter to TRUE (Boolean) the function will return the database object.
$this->db2 = $CI->load->database('db2', TRUE);
}
public function query0()
{
$query = $this->db2->query("SELECT name FROM table1 ORDER BY date");
return ($query->result());
}
public function query1()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query2()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query3()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query4()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
}
Let's say that my query works ok, I've tested it on my SQL Server. And then here's my CONTROLLER:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dash_control extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('dash_model');
$this->load->library('table');
}
public function index()
{
$tmpl = array (
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
);
$this->table->set_template($tmpl);
$data['result0'] = $this->dash_model->query0();
$data['result1'] = $this->dash_model->query1();
$data['result2'] = $this->dash_model->query2();
$data['result3'] = $this->dash_model->query3();
$data['result4'] = $this->dash_model->query4();
$this->load->view('dashboard',$data);
}
}
So i have 5 function in my model, the result was supposed to be a LOOP data. After I put the model inside my CONTROLLER, I pass it to my VIEW file like this:
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Transaction Success</th>
<th>Transaction Failure</th>
<th>Total Visit</th>
<th>Total Item</th>
</tr>
</thead>
<tbody>
<?php foreach (array_combine($result0, $result1, $result2, $result3, $result4) as $row)
{ ?>
<tr>
<td><?php echo $row->queryalias0; ?></td>
<td><?php echo $row->queryalias1; ?></td>
<td><?php echo $row->queryalias2; ?></td>
<td><?php echo $row->queryalias3; ?></td>
<td><?php echo $row->queryalias4; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
The error I got was:
Message: array_combine(): Both parameters should have an equal number of elements
And:
Message: Invalid argument supplied for foreach()
The result that I would like to achieve should be like this:
Thank you guys, for all your help...
From php.net
array_combine — Creates an array by using one array for keys and
another for its values
array array_combine ( array $keys , array $values )
You using wrong way array_combine function. You can try array_merge instead
foreach (array_merge($result0, $result1, $result2, $result3, $result4) as $row)
I use a data base ( created with phpmyadmin) in a function for my future website. The query worked but the result is strange : null .
This is my code :
public function select_toutcompetences($requete){
$query = "SELECT niv , nom FROM competences WHERE element = '$requete' ";
$result = $this->_db->query($query);
$tableau = array();
if ($result->rowCount() == 0){
return $tableau;
} else {
while($row = $result->fetch()) {
$tableau[] = new Competence($row->niv,$row->nom);
}
return $tableau;
}
}
In my view :
<?php if (!empty($table)) {?>
<table>
<caption>Les compétences</caption>
<tr>
<th>Niveau</th>
<th>Nom</th>
<tr>
<?php foreach ($table as $i=> $element) { ?>
<tr>
<td><?php echo $element->niveau()?></td>
<td><?php echo $element->nom()?></td>
</tr>
<?php } ?>
</table>
<?php }?>
With a var_dump , I got this :
object(Competence)[5]
private '_niveau' => null
private '_nom' => null
null
My class :
<?php
class Competence {
private $_niveau;
private $_nom;
public function Livre($niveau,$nom) {
$this->_niveau = $niveau;
$this->_nom = $nom;
}
public function niveau() {
return $this->_niveau;
}
public function nom() {
return $this->_nom;
}
}
?>
Thanks you for your help. I searched but I didn't understand why it doesn't work.
PS : I know my query isn't securized. I would it to work first.
Edit : the sql data base : comptences.sql
It is because your class does not have constructor. Method Livre is not called when object is initiating $tableau[] = new Competence($row->niv,$row->nom);. Try this (I have replaced Livre with __construct):
<?php
class Competence {
private $_niveau;
private $_nom;
public function _contruct($niveau,$nom) {
$this->_niveau = $niveau;
$this->_nom = $nom;
}
public function niveau() {
return $this->_niveau;
}
public function nom() {
return $this->_nom;
}
}
Also be sure you have same values in database result.
Try making the variables in your class public as well.
public $_niveau;
public $_nom;
So the ultimate goal is to print out products as objects in a table using functions from these classes, but the output is a table with the correct amount of rows/columns but they are blank. I've spent 3 hours trying to figure this out and I'm stumped. There's three files
Product.php
<?php
class Product
{
protected $product_id;
protected $product_name;
protected $product_price;
public function __construct($product_id,$product_name, $product_price = '')
{
$this->setProductID($product_id);
$this->setProductName($product_name);
$this->setProductPrice($product_price);
}
public function getProductID() {
return $this->product_id;
}
public function getProductName() {
return $this->product_name;
}
public function getProductPrice() {
return $this->product_price;
}
public function setProductID($product_id)
{
$this->product_id = $product_id;
}
public function setProductName($product_name)
{
$this->product_name= $product_name;
}
public function setProductPrice($product_price)
{
$this->product_price= $product_price;
}
}
ProductMapper.php
<?php
class ProductMapper
{
public function getProducts()
{
$dbConn = getDbConnection();
$stmt = $dbConn->prepare("SELECT * FROM product");
$stmt->execute();
$outArray = array();
while ($row = $stmt->fetch()) {
$outArray[] = new Product($row['product_id'], $row['product_name'], $row['product_cost']);
}
return $outArray;
}
}
and Index.php which is where it is outputted.
<?php
require('classes/functions.php');
require('classes/Product.php');
require('classes/ProductMapper.php');
$productMapper = new ProductMapper();
$rows = $productMapper->getProducts();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Product</title>
</head>
<body>
<tbody>
<?php
foreach ($rows as $row) {
echo "<tr>";
echo "<td>{$row->getProductID($this)}</td>";
echo "<td>{$row->getProductName($id)}</td>";
echo "<td>{$row->getProductPrice($id)}</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
There are a few minor issues with the code that you provide which prevent it working. Do you have 'error_reporting' set error-reporting?
index.php :
The 'getProduct' methods do not accept any parameters. So you should not call them with any parameters.
ProductMapper.php :
for consistancy i renamed the 'product_cost' column to 'product_price'.
i injected the database connection in the constructor and made it a property. Makes available the connection for any future method.
Some example output:
pid01 name-pid01 23.34
pid02 name-pid02 101.67
Here are the new scripts...
index.php
require('classes/functions.php');
require('classes/Product.php');
require('classes/ProductMapper.php');
$productMapper = new ProductMapper(getDbConnecton());
$rows = $productMapper->getProducts();
// note: the 'getProductID', 'getProductName' and 'getProductPrice' methods
// do not accept or need, any parameters.
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Product</title>
</head>
<body>
<table>
<tbody>
<?php
foreach ($rows as $row) {
echo "<tr>";
echo "<td>{$row->getProductID()}</td>";
echo "<td>{$row->getProductName()}</td>";
echo "<td>{$row->getProductPrice()}</td>";
echo "</tr>";
}
?>
</tbody>
</table>
// ProductMapper.php
class ProductMapper
{
/**
* #var PDO
*/
private $dbConn = null;
public function __construct(PDO $pdo)
{
$this->dbConn = $pdo;
}
public function getProducts()
{
$dbConn = $this->dbConn;
$stmt = $dbConn->prepare("SELECT * FROM product");
$stmt->execute();
$outArray = array();
while ($row = $stmt->fetch()) {
$outArray[] = new Product($row['product_id'], $row['product_name'], $row['product_price']);
}
return $outArray;
}
}
I have MVC on CI that not show error but cant get the result.
This the Script
Controller
customer.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Customer extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->view('customer_view');
}
function tampil_customer()
{
$this->load->model('customer_model');
$data = array('tests' => $this->customer_model->tampil_data_customer());
$this->load->view('customer_view', $data);
}//end fucnntion
}//end class
?>
Model
customer_model.php
<?php
class Customer_model extends CI_Models
{
public function tampil_data_customer()
{
$results = array();
$this->db->select('*');
$this->db->from('customer');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$results = $query->result();
}
return $results;
}
}
?>
View
customer_view.php
<table border="1" align="center" widht="900">
<tr>
<td colspan="5" align="center"><h2>Data Customer</h2></td>
</tr>
<tr>
<th>Nama</th>
<th>Company</th>
<th>Alamat</th>
<th>Telepon</th>
<th>HP</th>
</tr>
<?php
//$result = $this->result();
if( !empty($results) )
{
foreach($results as $isi)
{
echo "<tr>";
echo "<td>$isi->nama</td>";
echo "<td>$isi->company</td>";
echo "<td>$isi->alamat</td>";
echo "<td>$isi->telepon</td>";
echo "<td>$isi->hp</td>";
//echo anchor('customer/edit_customer/'.$isi->ID, 'Edit')."|";
//echo anchor('customer/hapus_customer/'.$isi->ID, 'Hapus')."|";
echo "</tr>";
}
}
?>
</table>
the Result only show the HTML like this
Can Anyone Help me to Fix this Problem?
Im very new Using CodeIgniter. I never use Framework before.
Im very appreciated your Answer.
Thanks
You are storing the result from database to array tests here
$data['tests'] = $this->customer_model->tampil_data_customer();
and trying to call it in view with an undefined array $results.
Try with this.
if(!empty($tests->result())){
foreach($tests->result() as $isi)
{
echo "<tr>";
echo "<td>".$isi->nama."</td>";
echo "<td>".$isi->company."</td>";
echo "<td>".$isi->alamat."</td>";
echo "<td>".$isi->telepon."</td>";
echo "<td>".$isi->hp."</td>";
echo "</tr>";
}
}
In model can you make it simple like this,
public function tampil_data_customer()
{
$query=$this->db->query('select * from customer');
$results = $query->result();
return $results;
}
when you pass in arguments using $this->load->view() function,you are using the view() function with the instance of Loader load,it's in /system/core/Loader.php. As the block comments say
An associative array of data to be extracted for use in the view.
if you pass in an object,you can get the public properties by simply using the property name,you can't get the protected and private property.
if you pass in an Multi-dimensional Array,you can get the value by using key/keys in the Multi-dimensional Array.
By the way,you must pass in an array or object other a variable.
sample below
model.php(application\models\test)
class model extends CI_Model {
public $ss=1;
protected $bb=1;
private $vv=3;
}
controller.php(application\controllers)
class Hello extends CI_Controller
public function __construct() {
parent::__construct ();
}
public function index() {
$this->load->model('test/model');
$model=new model();
$this->load->view ( 'test/view', $model );
}
view.php(application\views\test)
echo $ss;
then you get the value of object.