Few weaks ago I started learning PHP and MVC. So I started making simple project and got stuck at pagination problem.. I need help to find the best solution for pagination in my website. In the most pagination examples I have found, pagination is made with SQL SELECT LIMIT, but in my case it seems not very logical.
I have BooksController:
<?php
require 'Database/Connection.php';
require 'Database/QueryBuilder.php';
require 'Database/Book.php';
class BooksController
{
public function index()
{
$config = require 'config.php';
$books = new QueryBuilder(Connection::make($config['database']));
$books = $books->selectAll('books_table');
require 'views/listofbooks.view.php';
}
public function about()
{
$config = require 'config.php';
$books = new QueryBuilder(Connection::make($config['database']));
$bookId = $_REQUEST['id'];
$book = $books->selectByID('books_table', $bookId);
require 'views/aboutbook.view.php';
}
public function search()
{
$config = require 'config.php';
$books = new QueryBuilder(Connection::make($config['database']));
$text = $_REQUEST['search'];
$books = $books->search('books_table', $text);
require 'views/listofbooks.view.php';
}
}
And ListOfBooks View:
<!DOCTYPE html>
<html>
<head>
<title>Books</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<script src="styles/sorttable.js"></script>
<script>sorttable.sort_alpha = function(a,b) { return a[0].localeCompare(b[0], 'lt'); }</script>
</head>
<body>
<form action="/search" name="search" method="GET">
<input type="text" id="textbox" size="30" name="search" placeholder="Text" required />
<input type="submit" id="button">
</form>
<table class="sortable">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Year</th>
<th scope="col">Author</th>
<th scope="col">Genre</th>
</tr>
</thead>
<tbody>
<?php foreach($books as $book) : ?>
<tr>
<td data-label="Title"><?php echo $book->Title; ?></td>
<td data-label="Year"><?php echo $book->Year; ?></td>
<td data-label="Author(s)"><?php echo $book->Author; ?></td>
<td data-label="Genre"><?php echo $book->Genre; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
Should I change my recreate my BooksController or there is any other solution?
As you haven't mentioned that it has to be done in PHP, in my opinion, the easiest solution to your problem is a simple DataTable plugin. It is javascript (jQuery to be exact, but that is a javascript framework) and it will ease the usage of your server (there will not be one query for each of pagination pages, but one query and javascript will take care of pagination), but increase the use of client's PC. Also, you have filtering, search etc. available for dataTables, but here is the easiest to start with: https://datatables.net/examples/basic_init/zero_configuration.html
Related
Since I am completely new in Laravel, I have a problem pretty complicated for me.
I have controller file ApiHandlerController like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use GuzzleHttp\Client;
class ApiHandlerController extends Controller
{
//
public function index()
{
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://jsonplaceholder.typicode.com/todos',
]);
$response = $client->request('GET', '/todos');
//get status code using $response->getStatusCode();
$body = $response->getBody();
$arr_body = json_decode($body);
return view('myview', $arr_body);
}
}
?>
myview.blade.php as a view file:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Todo</title>
<link rel="shortcut icon" type="image/x-icon" href="icon.ico">
<meta name="description" content="HTML, PHP, JSON, REST API">
<style>table, th, td {border: 1px solid black;}</style>
</head>
<body>
<table style="width:100%"; class="data-table">
<tr>
<th>User ID:</th>
<th>ID:</th>
<th>Title:</th>
<th>Completed</th>
</tr>
<?php foreach ($arr_body as $value) { ?>
<tr>
<td><?php echo $value -> userId ?> </td>
<td><?php echo $value -> id ?> </td>
<td><?php echo $value -> title ?> </td>
<td><?php echo $value -> completed ?> </td>
</tr>
<?php } ?>
</table>
And web.php file with route:
Route::get('myview', function () {
return view('myview');
});
My question is:
How to show result of todos from jsonplaceholder.typicode.com in this blade (view) file?
Currently, it's not possible, and every time I try this is an error:
ErrorException
Undefined variable: arr_body (View: C:\xampp\htdocs\TodoList\resources\views\myview.blade.php)
Thank you guys in advance!
To show array type data in blade...
First edit your controller code.
From:
return view('myview', $arr_body);
To:
return view('myview')->with('arr_body', $arr_body);
Below is core php syntex.
<td><?php echo $value['userId'] ?> </td>
Laravel syntex
<td>{{$value['userId']}}</td>
Hope this will be useful.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So i start the language in this summer,and i have problem,i don't know how to make delete button,i looked lot of pages but i can't find how to make with pdo.
countryandcity.php
<?php
require 'pdo.php';
$connect=connect();
?><!DOCTYPE html>
<html>
<head>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="wrapper">
<table class="table" >
<thead>
<tr>
<th>Country</th>
<th>City</th>
<th>Image</th>
</tr>
<form action="deleteall.php" method="POST" >
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
while($result = $sql->fetch(PDO::FETCH_ASSOC)) {
echo"<tr>";
echo"<td>".$result['country']."</td>";
echo"<td>".$result['city']."</td>";
if(!empty($result['image'])){
echo '<td><img src="images/'.$result['image'].'"/></td>';
}
else {
echo"<td>-</td>";
}
echo "<td><a href='edit.php?uid=".$result['country']."'>Edit</a></td>";
echo "<td><a href='deleteall.php?uid=".$result['country']."'>Delete</a></td>";
echo"</tr>";
}
?>
</form>
</thead>
</table>
</div>
</body>
deleteall.php
<?php
require 'pdo.php';
$connect=connect();
if(isset($_POST['delete_btn']))
?><!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<div class="form-group">
<label>Do u want to delete?</label>
</div>
<button>
<input type="submit" value="YES" name="delete_btn">
</button>
<button>
<input type="submit" name="no" value="NO">
</button>
</form>
</body>
</html>
Please help me with the sql query and php code after if(isset), i need help!
I just want to delete on row from the database.
How can I solve this?
Sorry for my bad english.
Thanks!
Here is correction of your firsts page (content in <tbody> instead of <thead>, no <form> needed, ...) countryandcity.php :
<table>
<thead>
<tr>
<th>column name...</th>
</tr>
</thead>
<tbody>
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
if($result = $sql->fetch(PDO::FETCH_ASSOC)) {
foreach($result as $i => $item) {
extract($item);
echo "<tr><td>$country</td>";
echo "<td>$city</td>";
if(!empty($image)) {
echo "<td><img src=\"images/$image\"/></td>";
}
else {
echo "<td>-</td>";
}
echo "<td>Edit</td>";
echo "<td>Delete</td></tr>";
}
}
?>
</tbody>
</table>
</div>
</body>
</html>
And here solution for deleting your record in deleteall.php :
<?php
if(isset($_GET['delete_btn'])) {
$country = addslashes($_GET['delete_btn']);
$q = "DELETE FROM countries WHERE country = '$country'";
require 'pdo.php';
$sql = connect()->prepare($q);
$sql->execute();
}
?>
hope it will help you, you can add delete link then go this page it will delete
Edit
Delete
<?php
require 'pdo.php';
$connect = connect();
?>
<!DOCTYPE html>
<html>
<head>
<link href="style.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<div class="wrapper">
<table class="table">
<thead>
<tr>
<th>Country</th>
<th>City</th>
<th>Image</th>
</tr>
<form action="deleteall.php" method="POST">
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
while ($result = $sql->fetch(PDO::FETCH_ASSOC)) {
if (!empty($result['image'])) {
$content_image = '<td><img src="images/' . $result['image'] . '"/></td>';
} else {
$content_image = '<td>-</td>';
}
?>
<tr>
<td> <?= $result['country'] ?></td>
<td><?= $result['city'] ?></td>
<?= $content_image ?>
<td>Edit</td>
<td>Delete
</td>
</tr>
<?php }
?>
</form>
</thead>
</table>
</div>
</body>
</html>
then this is your deleteall.php
<?php
$uid = trim($_GET['uid']);
if(isset($uid)) {
$sql = "DELETE FROM countries WHERE country = ?";
$q = connect()->prepare($sql);
$response = $q->execute(array($uid));
}
?>
For the form, I'd recommend having a button that acts as the function, that way you don't accidentally lose all your data when the page loads, or anything like that. This is simply three lines of code.
<form action="deleteall.php" method="POST">
<input type="hidden" value="true" name="cameFromForm">
<button type="submit" name="confirmButton">Delete All</button>
</form>
When the button is clicked, then it will trigger the entry point of deleteall.php, which then takes the input and deletes ALL data from the table.
<?php
if(isset($_POST["cameFromForm"]) && $_POST["cameFromForm"] == "true") {
// This makes sure that the form actually sent it.
try {
$tableName = "Insert the name of your table here";
$mysqli = new mysqli(
'databaseHost',
'databaseUser',
'databasePassword',
'databaseName');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("DELETE FROM ?");
$stmt->bind_param('s', $tableName);
$stmt->execute();
$stmt->close();
$mysqli->close();
header('Location: http://afterDeltePage.com');
}
catch (Exception $e) {
print($e);
die();
}
}
else {
header('Location: http://notAuthorisedPage.com');
}
?>
Once you've finished the process, you should send the user to a page with UI. Try to separate the things you need to show the user and your processes. Also, if this is going to be public, you need to make sure that deleteall is not accessible by anyone by URL.
To do that, you need to move your file out of the wwwroot (public_html usually). There are various topics on how to do that.
PHP Forms information and PHP MySQLi information.
How can i run search function? i cant display the any result with this code and i don't know how to handle this class and function.. i'm a newbie with this kind of code..please review my codes....thanks!!!
<?php
$txtsearch = $_POST['txtsearch'];
class BlogController{
public function search($txtsearch){
$mysqli = new mysqli("localhost","root","","sample_db");
$display_query = "SELECT * FROM `tb_blogs` WHERE id='$txtsearch' ";
$result = $mysqli->query($display_query);
}
}
if(isset($_POST["btnsearch"])){
echo BlogController::search();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
Create New Blog<br>
<form action="function.php" method="post">
<input text-align:right type="text" name="txtsearch" placeholder="search">
<input type="submit" name="btnsearch" value="Search">
<table border="1" width="60%" cellpadding="2" cellspacing="0">
<thead>
<tr>
<th width="5%">ID</th>
<th width="20%">Title</th>
<th width="20%">Author</th>
<th width="40%">Content</th>
<th width="15%">Action</th>
</tr>
</thead>
<tbody>
<?php while($blog = $result->fetch_object()): ?>
<tr>
<td><?php echo $blog->id?></td>
<td><?php echo $blog->title?></td>
<td><?php echo $blog->author?></td>
<td><?php echo $blog->content?></td>
<td>
Edit
<a class ="btn_del" href="delete.php?blog_id=<?php echo $blog->id;?>">Delete</a>
</td>
</tr>
<?php endwhile?>
</tbody>
</table>
<script type="text/javascript">
$(function(){
$(".remove-btn").on('click',function(){
var is_confirm = confirm("Do you want to delete record?");
if(is_confirm){
window.location = $(this).attr('href');
}
return false;
});
});
</script>
</form>
</body>
</html>
Try this :
class BlogController{
public $txtsearch;
function __construct($search) {
$this->$txtsearch = $search;
}
public function search(){
$mysqli = new mysqli("localhost","root","","sample_db");
$display_query = "SELECT * FROM `tb_blogs` WHERE id='$this->$txtsearch' ";
$result = $mysqli->query($display_query);
return $result;
}
}
Create an instance and then call the function search
$myclass = new BlogController($_POST['txtsearch']); //pass value to the construct function
print_r($myclass->search()); // will return an array
I want to use AJAX to show a form when a user clicks on record to edit it.
I know and capable of using AJAX.
But now i want to call a method of a class in PHP. And thats where im stuck.
Below some code sample of my controller:
public function start() {
$users = $this->usersmodel->getAllUsers();
$firstRow = new HtmlTableFirstRow();
$table = new HtmlTable($users,$users,$firstRow);
$table->setCss('table1');
echo $table->show();
}
public function editRecord() {
$recordId = $this->getFirstParameter();
$user = $this->usersmodel->getUserById($recordId);
$tableId = $this->fieldModel->getTableIdByName('users');
$inputs = $this->fieldModel->getFields($tableId);
$collection = new Fieldcollection($inputs);
foreach($collection as $inputs) {
for($i = 0; $i < count($inputs); $i++) {
foreach($user as $userInfo) {
$inputs[$i]->setValue($userInfo[$i]);
}
}
}
$form = new Form($collection);
$form->setLabels();
$form->setCss('form1');
echo $form->show();
}
As you can see i have 2 functions, start which shows all the records. And when a user clicks on editrecord a form will show.
I want to show the form in a popup, without a page refresh.
What is the best way to handle this?
You can make a page for manage ajax requests like this:
server.php :
if(isset($_GET['request'])){
switch($_GET['request']){
case 'get-form' :
$userId = $_GET['userId'];
$form = new Form($collection);
$form->setLabels();
$form->setCss('form1');
echo $form->show();
break;
}
}
in client page you can send ajax request & get their result via jquery :
client.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table>
<tr data-userId="1">
<td>User 1</td>
<td><button class="edit">Edit Record</button></td>
</tr>
<tr data-userId="2">
<td>User 2</td>
<td><button class="edit">Edit Record</button></td>
</tr>
<tr data-userId="3">
<td>User 3</td>
<td><button class="edit">Edit Record</button></td>
</tr>
</table>
<div class="popup">
</div>
</body>
<script src="jquery.js"></script>
<script src="ajax.js"></script>
</html>
ajax.js :
(function(){
$('.popup').hide();
$('.edit').on('click',function(){
var userId = $(this).parent().parent().data('userId');
$.get('server.php',{request : 'get-form' , userId : userId},function(form){
$('.popup').empty().append(form).fadeIn();
});
});
})();
I hope this helps you
First of all, I am absolutely new to CodeIgniter.
I'm trying to develop a simple CRUD page using CodeIgniter. So far, I've just created the View page, without any CRUD feature. It's just a normal view page, with a table that contains my model data retrieved from the database.
Here is the code for my view page which works ok, file name - show_users.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CI CRUD</title>
</head>
<body>
<h2> Simple CI CRUD Application </h2>
<table width="600" border="1" cellpadding="5">
<tr>
<th scope="col">Id</th>
<th scope="col">User Name</th>
<th scope="col">Email</th>
<th scope="col">Mobile</th>
<th scope="col">Address</th>
</tr>
<?php foreach ($user_list as $u_key){ ?>
<tr>
<td><?php echo $u_key->id; ?></td>
<td><?php echo $u_key->name; ?></td>
<td><?php echo $u_key->email; ?></td>
<td><?php echo $u_key->address; ?></td>
<td><?php echo $u_key->mobile; ?></td>
</tr>
<?php }?>
</table>
</body>
</html>
My model is - users_model.php
<?php
class Users_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_all_users()
{
$query = $this->db->get('users');
return $query->result();
}
}
?>
My controller is - users.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
function __construct()
{
parent::__construct();
#$this->load->helper('url');
$this->load->model('users_model');
}
public function index()
{
$data['user_list'] = $this->users_model->get_all_users();
$this->load->view('show_users', $data);
}
}
?>
My database server is MySQL, database name ci_test and my table is users:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`address` varchar(255) NOT NULL,
`mobile` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
)
My view page is showing this output:
So far so good. Now, whenever I try to modify my view page show_users.php, the page is loaded, but empty.
Here is the code of my modified view page, for which I encounter the above mentioned problem:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CI CRUD</title>
<script type="text/javascript">
function show_confirm(act,gotoid)
{
if(act=="edit")
var r=confirm("Do you really want to edit?");
else
var r=confirm("Do you really want to delete?");
if (r==true)
{
window.location="<?php echo base_url();?>index.php/users/"+act+"/"+gotoid;
}
}
</script>
</head>
<body>
<h2> Simple CI CRUD Application </h2>
<table width="600" border="1" cellpadding="5">
<tr>
<th scope="col">Id</th>
<th scope="col">User Name</th>
<th scope="col">Email</th>
<th scope="col">Mobile</th>
<th scope="col">Address</th>
<th scope="col" colspan="2">Action</th>
</tr>
<?php foreach ($user_list as $u_key){ ?>
<tr>
<td><?php echo $u_key->id; ?></td>
<td><?php echo $u_key->name; ?></td>
<td><?php echo $u_key->email; ?></td>
<td><?php echo $u_key->address; ?></td>
<td><?php echo $u_key->mobile; ?></td>
<td width="40" align="left" >Edit</td>
<td width="40" align="left" >Delete </td>
</tr>
<?php }?>
<tr>
<td colspan="7" align="right"> Insert New User</td>
</tr>
</table>
</body>
</html>
Note that I haven't changed anything in my model and controller yet.
Can anyone please specify where the problem is? Any convenient and efficient solution to this? I am using Notepad++ for development, no IDE.
EDIT: Although I found a solution to my problem and accepted it as answer, I'm still confused about one issue.
In my model - users_model.php, I have a line:
$this->load->database();
But in the tutorial, it was written like this:
$this->load->database("ci_test");
So basically, I forgot to provide my database name, which is ci_test. I still haven't edited my model code, but my view page is working perfectly now. So what is the significance of it? Is it necessary to mention the database name inside $this->load->database() ? Is this one of the reasons my view page was empty?
This is not the problem with your view page.
go to config folder open autoload.php
$autoload['helper'] = array('url');
Other Way
Uncomment the #$this->load->helper('url'); to $this->load->helper('url');
<?php
class Users_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
public function get_all_users()
{
$query = $this->db->get('users');
return $query->result();
}
}
?>
The answer for your comment : $this->load->database()
There are two ways to connect to a database:
The "auto connect" in application/config/autoload.php
$autoload['libraries'] = array('database');
Manually Connecting
The first parameter of this function can optionally be used to specify a particular database group from your config file, or you can even submit connection values for a database that is not specified in your config file.
$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$this->load->database($config);
Instead of this <?php echo base_url();?>index.php/user/add_form
Use: <?php echo site_url('user/add_form');?>
I think problem is in this line:
window.location="<?php echo base_url();?>index.php/users/"+act+"/"+gotoid;
maybe you have forgot load helper url?