Deleting a Post/Entry by User in PHP - php

I am designing a simple book application. I have the user login, sell or buy books and they have a few account settings too, including Manage Posts where the user can delete the book they added into the system.
I am needing help on how to do this. When the user presses the Manage Posts button, I would like an input field that the user can type the Book_ID in and a "Delete" button where they can click it to delete the book out of the system.
Now, I wasn't able to set it up to where when you add a book, it links it to that specific user that logs in (no idea how to do that), so the user will be able to delete any book. I ran out of time on this project so I won't worry about that now. I just need the user to be able to see all the books in the database by the fields on a table: Book_ID, ISBN, Title, Author - and then the user inputs the Book_ID into the input field, clicks "Delete" button and the book is deleted from the database by the user.
database name: nextbook
table: books
fields: book_ID, ISBN, Author, Title (want these viewed)
The following is a template of code I have from another page that I think would be similar. Except, I need the Delete SQL put somewhere :
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM books";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM books";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "Admin", "Password", "nextbook");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!--Html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://ie7-js.googlecode.com/svn/version2.1(beta4)/IE9.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<style>
table {
border-collapse: collapse;
width: 30%;
}
th, td {
text-align: left;
padding: 5px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #007d5f;
color: white;
}
</style>
<link rel="stylesheet" href="NextBook1.css"/>
</head>
<body>
<div data-role="page" id="Manage_Posts">
<div data-role="header" data-theme="b">
<h1>NextBook</h1>
Sign Out
</div>
<br>
<div class="logo" align="center">
<img src="Images/image1%20-%20Copy.PNG" width="100" height="100" ">
</div>
<div data-role="content" align="center">
<!--<form action="View_Search_Results_Table.php" method="post" align="center"> -->
<input type="text" name="deletepost" placeholder="Enter ISBN you want to delete">
<input type="submit" name="delete" value="Delete Post"><br><br>
<div style="overflow-x:auto;">
<table border="1px solid black;" align="center">
<tr>
<th>Book ID</th>
<th>ISBN</th>
<th>Title</th>
<th>Author</th>
</tr>
</div>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['Book_id'];?></td>
<td><?php echo $row['ISBN'];?></td>
<td><?php echo $row['Title'];?></td>
<td><?php echo $row['Author'];?></td>
</tr>
<?php endwhile;?>
</table>
<div data-role="footer" data-position="fixed" data-id="nav" data-theme="b">
<div data-role="navbar">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</body>
</html>

<form method="post" action="delete.php">
<input type="text" placeholder="Enter the book ID to delete" name="getdeleteid">
<button type="submit" value="Delete book">
</form>
PHP:
<?php
$getdelete = $_POST['getdeleteid'];
$pdo = new PDO('mysql:host=yourhost;dbname=nextbook ','user','password');
$statement = $pdo->prepare("DELETE FROM books WHERE book_ID = ".$getdelete."");
$statement->execute(array(1));
?>

You should be breaking your script down into multiple parts to make the view easier to work with. Also you should have all the classes in their own pages and use an autoloader (spl_autoload_register() or similar) to autoload classes. I have put everything on to one page which looks more complex than it really is. Finally it is helpful to use action words in forms to tell your program you aret trying to do something:
<?php
/*
** #description It's helpful to have a class that just does some general "stuff"
** that all classes could potentially use
*/
class App
{
protected static $singleton;
public function __construct()
{
if(!(self::$singleton instanceof \App))
self::$singleton = $this;
return self::$singleton;
}
# Retrieve the $_POST array or a key from it
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
}
/*
** #description It's helpful to have a database class for consistent database retrieval and querying
*/
class Database extends \App
{
protected static $con;
protected $query;
# Create and retrieve database connection
public function getConnection()
{
# Create connection if not already set
if(!(self::$con instanceof \PDO))
self::$con = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
# Return the connection
return self::$con;
}
# Query database
public function query($sql,$bind=false)
{
# Bind parameters for public requests
if(!empty($bind)) {
foreach($bind as $key=>$value) {
$bKey = ":{$key}";
$bArray[$bKey] = $value;
}
}
# Prepare sql
if(!empty($bArray)) {
$this->query = $this->getConnection()->prepare($sql);
$this->query->execute($bArray);
}
else
# Do a straight query
$this->query = $this->getConnection()->query($sql);
# Send back the object for chaining
return $this;
}
# Use with the query to retrieve database results
public function getResults()
{
while($row = $this->query->fetch(\PDO::FETCH_ASSOC)) {
$new[] = $row;
}
return (!empty($new))? $new : false;
}
}
/*
** #description Because you are wanting to get database info, may as well extend the Database class
** and use it's querying features
*/
class Books extends Database
{
# Retrieve one or more books
public function getBook($id = false,$type='Book_id')
{
$id = trim($id);
$sql = "SELECT * FROM `books`";
if(!empty($id)) {
$sql .= " WHERE `{$type}` = :0";
$results = $this->getConnection()->query($sql,array($id))->getResults();
return (is_array($results) && count($results) == 1)? $results[0] : $results;
}
return $this->getConnection()->query($sql)->getResults();
}
# Delete book
public function deleteBook($id,$type='ISBN')
{
$this->getConnection()->query("DELETE FROM books WHERE `{$type}` = :0",array($id));
}
}
class View extends Database
{
public static function createSrc($path,$type='js')
{
if($type == 'js')
return '<script type="text/javascript" src="'.$path.'"></script>';
elseif($type == 'css')
return '<link rel="stylesheet" href="'.$path.'" />';
}
}
# Should put these defines into a config.php file that you load at the top of every page
define('DB_HOST','localhost');
define('DB_NAME','nextbook');
define('DB_USER','root');
define('DB_PASS','');
session_start();
# Create instance of Books
$App = new Books();
# Creaet the book list (could be based on the search)
$search = $App->getBook($App->getPost('search'));
# Check if the user is trying to delete a book
if($App->getPost('action') == 'delete_isbn') {
$App->deleteBook($App->getPost('deletepost'));
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<?php echo View::createSrc('http://html5shiv.googlecode.com/svn/trunk/html5.js') ?>
<?php echo View::createSrc('http://ie7-js.googlecode.com/svn/version2.1(beta4)/IE9.js') ?>
<?php echo View::createSrc('http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css','css') ?>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<?php echo View::createSrc('http://code.jquery.com/jquery-1.11.1.min.js') ?>
<?php echo View::createSrc('http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js') ?>
<style>
table {
border-collapse: collapse;
width: 30%;
}
th, td {
text-align: left;
padding: 5px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #007d5f;
color: white;
}
</style>
<link rel="stylesheet" href="NextBook1.css"/>
</head>
<body>
<div data-role="page" id="Manage_Posts">
<div data-role="header" data-theme="b">
<h1>NextBook</h1>
Sign Out
</div><br>
<div class="logo" align="center">
<img src="Images/image1%20-%20Copy.PNG" width="100" height="100" />
</div>
<div data-role="content" align="center">
<form action="" method="post" align="center">
<input type="hidden" name="action" value="delete_isbn" />
<input type="text" name="deletepost" placeholder="Enter ISBN you want to delete">
<input type="submit" name="delete" value="Delete Post">
</form>
<br /><br />
<table border="1px solid black;" align="center">
<tr>
<th>Book ID</th>
<th>ISBN</th>
<th>Title</th>
<th>Author</th>
</tr>
<!-- populate table from mysql database -->
<?php foreach($search as $row) { ?>
<tr>
<td><?php echo $row['Book_id'];?></td>
<td><?php echo $row['ISBN'];?></td>
<td><?php echo $row['Title'];?></td>
<td><?php echo $row['Author'];?></td>
</tr>
<?php } ?>
</table>
<div data-role="footer" data-position="fixed" data-id="nav" data-theme="b">
<div data-role="navbar">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>

Related

mySQL auto-increment + auto adjust id by dynamicly deleting table content via PHP?

I am currently trying to build a "ToDo-App" which lets me INSERT text into a database, which will then be displayed. There is a "feature" to delete content based on their ID.
If I input two tasks into my application, I get two table records with ID 1 and 2. When I delete record 1, the record with ID 2 still exists. Thus, the record with ID 2 is listed as the first item in the to-do list.
I have to enter "2" in the "delete input field" to delete the first item from the list! How can I get this to be in sync? Is the ID field appropriate for maintaining the logical / application level order of the tasks?
<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
</head>
<?php
$con = mysqli_connect("","root","","todo");
$sql = "SELECT text FROM work";
$res = mysqli_query($con, $sql);
if(isset($_POST["text"]))
{
$eingabe = $_POST["text"];
$query = "INSERT INTO work(text) VALUES('$eingabe')";
mysqli_query($con, $query);
header("Refresh:0");
}
else
{
echo "";
}
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
else
{
echo "";
}
?>
<body>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<form action="index.php" method="post">
<input class="lil-input" name="text" type="text">
<input type="submit" class="lil-button-green" value="Hinzufügen">
</form>
<ol id="liste" class="lil-list">
<?php
while($dsatz = mysqli_fetch_assoc($res))
{
echo "<li>" .$dsatz["text"] ."</li>";
}
?>
</ol>
<form id="form" action="index.php" method="post">
<input class="lil-input" name="del" type="text">
<input type="submit" class="lil-button-red lil-button-small" value=" Löschen ">
</form>
</div>
</div>
</div>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
var anzahl = $("#liste li").length;
if(anzahl < 1)
{
$("#form").hide();
}
else
{
$("form").show();
}
</script>
</body>
</html>
The pictures:
HTML Output
MySQL Dashboard
As discussed in the comment, you can have multiple checkboxes forming an array parameter: <input name="theName[1]"> with explicit key and name="theName[]" with implicit keys.
Further more, you should use prepared statements to prevent SQL injection attacks. Imagine an attacker sends a request with a single quote ' in the field, i.e. he terminates the SQL string delimiter, and adds arbitrary SQL code. Prepared statements use placeholders and the parameters are sent separately.
You should also handle errors. In the code below errors are output as HTML, however, you should define your own logger function rather than just echo into the stream. This can output HTML on development servers but log to disk on production servers.
This is a working example tested on PHP7.3 with MariaDB 10:
<!DOCTYPE HTML>
<html lang="de">
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
<style>
#frm-tasks button
{
padding: 0 18px;
}
</style>
</head>
<body>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$con = new mysqli('localhost', 'testuser', 'testpasswd', 'testdb');
$action = $_POST['action'] ?? 'list';
if(!empty($_POST["text"]))
{
$eingabe = $_POST["text"];
try
{
$stmt = $con->prepare('INSERT INTO work(text) VALUES(?)');
$stmt->bind_param('s', $_POST["text"]);
$stmt->execute();
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
if('del' === $action && isset($_POST['rows']) && is_array($_POST['rows']))
{
try{
$stmt = $con->prepare('DELETE FROM `work` WHERE `work`.`id` = ?');
$stmt->bind_param('i', $row);
foreach ($_POST['rows'] as $row)
{
$stmt->execute();
if($e = $stmt->error)
echo "<div>DB Error: $e</div>";
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
?>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<!--form action="index.php" method="post"-->
<form id="frm-tasks" action="" method="post">
<input class="lil-input" name="text" type="text">
<button type="submit" class="lil-button-green" name="action" value="add">Hinzufügen</button>
<?php
try
{
$res = $con->query('SELECT id, text FROM work');
if(0 < $res->num_rows)
{
?>
<table>
<thead>
<tr>
<th></th><th>ID</th> <th>Aufgabe</th>
</tr>
</thead>
<tbody>
<?php
while($dsatz = mysqli_fetch_object($res))
{
?>
<tr>
<td><input type="checkbox" name="rows[]" value="<?php echo $dsatz->id;?>"></td><td><?php echo $dsatz->id;?></td> <td><?php echo $dsatz->text;?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<button type="submit" class="lil-button-red lil-button-small" name="action" value="del">Löschen</button>
<?php
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $e->msg;</div>";
}
?>
</form>
</div>
</div>
</div>
<!-- not needed atm script src="js/jquery-3.3.1.min.js"></script-->
<h2>POST</h2>
<?php
var_dump($_POST);
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error connecting DB: $msg;</div>";
}
?>
</body>
</html>
The key of the list is the 'th' in the database so just fixing limits
Replace
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
With
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` LIMIT 1 OFFSET ".array_search($del, mysqli_fetch_assoc($res));
mysqli_query($con, $sql2);
header("Refresh:0");
}

adding to mysql and deleting on the same page

there is my script
require('dbcon2.php');
if(isset($_GET['submit1'])) {
if(isset($_POST['post_autor']) && isset($_POST['post_tresc'])) {
mysqli_query($connect,"INSERT INTO news (tresc, autor) VALUES ('$_POST[post_tresc]', '$_POST[post_autor]')");
}
} elseif(isset($_GET['submit2'])) {
if(isset($_POST['post_id_news2'])) {
$usun = $_POST['post_id_news2'];
mysqli_query($connect,"DELETE FROM news WHERE id_news = ".$usun."");
} else {
echo 'Proba usunieca postu o pustym id.';
}
}
I wanted to do this on one page, before adding deleting (hehe) it was ok, but I wanted to do delete option and nothing works, zero errors I just press inputs and nothing happends.
HTML:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pl" lang="pl">
<head>
<meta charset="utf-8">
<style type="text/css">
.cztery {
background: pink;
height:705px;
width:40%;
float:right;
}
.czteryipol {
background: red;
height:705px;
width:40%;
float:right;
}
</style>
</head>
<body>
<div class="cztery">
<h1 align="center">
<a href="html/news_podg.php" target="_blink">
PODGLĄD
</a>
</h1>
<table border="5" bordercolor="#a64dff" align="center" style="max-width:20px;">
<?php
$result = mysqli_query($connect,"SELECT autor,id_news FROM news GROUP BY id_news");
while($row = mysqli_fetch_array($result))
{
echo '<tr><td>'.$row['id_news'].'</td><td>'.$row['autor'].'</td></tr>';
}
?>
</table>
</div>
<div class="czteryipol">
<h1 align="center">
EDYCJA
</h1>
<form action="kwadrat.php?go=czesc" method="post" id="usrform" align="center">
<h2>
Autor<br> <input type="text" size="20" name="post_autor"/>
</h2>
<h2>
Dodaj artykuł:
</h2>
<textarea name="post_tresc" align="center" form="usrform"></textarea><br>
<input name="submit1" type="submit" value="OK"/><br>
</form>
<form action="kwadrat.php?go=czesc" method="post" id="usrform" align="center">
<h1 align="center">
Usuń artykuł
</h1>
<h2>
Numer artykułu<br> <input type="text" size="5" name="post_id_news2"/>
</h2>
<input name="submit2" value="OK" type="submit"/><br>
</form>
</div>
</body>
</html>
If someone can tell me where is my mistake I will be very grateful
FINAL EDIT:
Thanks for help, I fixed that:
instead of this
($_GET['submit1'])
do
($_POST['submit1'])
Probably .....
Instead of if(isset($_GET['submit1']))
Use if(isset($_POST['submit1']))
if(isset($_POST['post_id_news2'])) { //<- Here is your culprit I think
$usun = $_POST['post_id_news'];
You are checking for post_id_news2 (note 2 at the end) parameter and then trying to use post_id_news parameter.
I don't know which one you actually use, but in your case they should be the same.
Also I suggest you read this:
Escaping parameters for MySQL queries
Here is some debugging stuff: 1. Check to make sure the second submit is actually called #debug1. 2. Next check for MySQL errors #debug2 for the delete statement.
require('dbcon2.php');
if(isset($_GET['submit1'])) {
echo 'submit1: was called'; #debug1
if(isset($_POST['post_autor']) && isset($_POST['post_tresc'])) {
mysqli_query($connect,"INSERT INTO news (tresc, autor) VALUES ('$_POST[post_tresc]', '$_POST[post_autor]')");
}
}
elseif(isset($_GET['submit2'])) {
echo 'submit2: was called'; #debug1
if(isset($_POST['post_id_news2'])) {
$usun = $_POST['post_id_news'];
#debug2
if(!mysqli_query($connect,"DELETE FROM news WHERE id_news = ".$usun."")) {
echo 'MySQL error: ' . mysqli_error($connect);
}
}
else {
echo 'Proba usunieca postu o pustym id.';
}
}

How to keep current page on ajax pagination after editting a row?

The header.php has a <div id="content"></div> and then will load the page user.php
Q1: Is javascript coding on the header.php can not interact with the loaded content?
Therefore I put the js code on the loaded page, but i found a little bit strange.
Q2:
The paging function is working, suppose it is on page 4.
After I editting one of the row, the page go back to first page. I want to keep it on page 4.
< 1 2 3 4 5 6>
I want to store the current link as a text within a after i click the paging, however the link is stored first and then page will refresh and clear the data.
The href of the paging links will look like
localhost://blog/index.php/admin/users/show/10
localhost://blog/index.php/admin/users/show/20
localhost://blog/index.php/admin/users/show/30
Please point out the solution or suggest another better solution
$("input[name=submit]").click(function() {
$(this).parents('.alert-box').hide();
$form = $(this).parent('form');
$.post(
$form.attr('action'),
$form.find(':input').serializeArray(),
function(data) {
$("#content").html(data);
}
);
});
View:header.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?= $css; ?>bootstrap.css" rel="stylesheet" type="text/css">
<link href="<?= $css; ?>basic/basic.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<?= $js; ?>jquery.js"></script>
<script type="text/javascript" src="<?= $js; ?>jquery_validate.js"></script>
<script type="text/javascript" src="<?= $js; ?>form_control.js"></script>
<script type="text/javascript" src="<?= $js; ?>additional-methods.min.js"></script>
</head>
<body>
<style>
#content{
background-color: #D0D0D0;
float:left;
width:80%;
}
#main-frame{
width:100%;
}
#list{
width:18%;
float:left;
}
#delete-alert-box{
background-color: #269abc;
position: absolute;
z-index: 99999;
display: none;
}
#edit-alert-box{
background-color: #269abc;
position: absolute;
z-index: 99999;
display: none;
}
body{
font-size:2em;
}
</style>
<script language="javascript">
$(document).ready(function() {
init();
$('.open').click(function(e) {
e.preventDefault();
$.post($(this).attr('href'), function(data) {
$('#content').html(data);
});
});
});
function init() {
$.post(
"<?php echo site_url("admin/users/show");?>", function(data) {
$("#content").html(data);
}
);
}
</script>
<div id="header">
<div id="logo">
</div>
<?php if ($this->AuthModel->check_admin_log()) { ?>
Logout
<?php }
?>
</div>
<ul id="list">
<li>
Users Manage
</li>
<li>
Group Manage
</li>
<li>
Post Mange
</li>
<li>
System Setting
</li>
<li>
<a href="<?php echo site_url('logout/admin') ?>" >Logout</a>
</li>
</ul>
<div id="content" class="box"></div>
view:users.php
<table border="1">
<tr><th>User Id</th><th>User Name</th><th>Email</th><th>Registeration Date</th><th>Group</th><th>State</th><th>Operation</th></tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?= $user->id; ?></td>
<td><?= $user->username; ?></td>
<td><?= $user->email; ?></td>
<td><?= mdate('%Y-%m-%d', $user->registeration_time); ?></td>
<td><?= $user->user_type; ?></td>
<td><?= $user->account_status; ?></td>
<td>
<button type="button" value="<?php echo $user->id; ?>" name="delete">X</button>
<button type="button" value="<?php echo $user->id; ?>" name="edit">edit</button>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $links ?>
<div id="delete-alert-box" class="alert-box">
<div class="cancel">X</div>
<h3>Are you sure to delete the account?</h3>
<form action="<?php echo site_url('admin/users/delete') ?>" id="deleteForm">
<input type="hidden" value="" name="user_id">
<input type="button" value="Yes" name="submit">
<input type="button" value="No" name="cancel">
</form>
</div>
<div id="edit-alert-box" class="alert-box">
<div class="cancel">X</div>
<h3>Edit User:<span id="username"></span></h3>
<form action="<?php echo site_url('admin/users/edit') ?>" id="editForm">
<table>
<tr>
<td>Group</td>
<td>
<select name="group" id="group">
<option value="1">Nomal User</option>
<option value="2">Amin</option>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="1">Activated</option>
<option value="2">Non-Activated</option>
<option value="3">Blocked</option>
</select>
</td>
</tr>
</table>
<input type="hidden" value="" name="user_id">
<input type="button" value="Yes" name="submit">
<input type="button" value="No" name="cancel">
</form>
</div>
<script>
$(document).ready(function() {
$(".cancel").click(function() {
$(this).parent('.alert-box').hide();
});
$("input[name=cancel]").click(function() {
$(this).parents('.alert-box').hide();
});
$("button[name=delete]").click(function() {
var $user_id = $(this).attr('value');
if ($user_id !=<?php echo $this->session->userdata('user_id') ?>) {
$("#delete-alert-box").show();
$('#delete-alert-box').find('input[type=hidden]').attr('value', $user_id);
}
});
$("button[name=edit]").click(function() {
var $user_id = $(this).attr('value');
if ($user_id !=<?php echo $this->session->userdata('user_id') ?>) {
$("#edit-alert-box").show();
var $tr = $(this).parents('tr');
var $tds = $tr.find('td');
$('#edit-alert-box').find('input[type=hidden]').attr('value', $user_id);
$('#group').find('option').each(function(index) {
$(this).removeAttr('selected');
});
$('#group').find("option[value=" + get_group_code($($tds[4]).html()) + "]").attr('selected', 'selected');
$('#state').find("option[value=" + get_account_code($($tds[5]).html()) + "]").attr('selected', 'selected');
}
});
$("input[name=submit]").click(function() {
$(this).parents('.alert-box').hide();
$form = $(this).parent('form');
$.post(
$form.attr('action'),
$form.find(':input').serializeArray(),
function(data) {
$("#content").html(data);
}
);
});
$('.paging a').click(function(e) {
e.preventDefault();
$.post($(this).attr("href"), function(data) {
$("#content").html(data);
});
});
});
function get_group_code(name) {
switch (name) {
case "Normal User":
return 1;
case "Admin":
return 2;
}
}
function get_account_code(name) {
switch (name) {
case "Activated":
return 1;
case "Non-Activated":
return 2;
case "Blocked":
return 3;
}
}
</script>
Controller: admin/users.php
function pagination() {
$this->load->library('pagination');
$config['base_url'] = site_url('admin/users/show');
$config['total_rows'] = $this->UsersModel->get_num_rows();
$config['per_page'] = '10';
$config['uri_segment'] = 4;
$config['full_tag_open'] = '<p class="paging">';
$config['full_tag_close'] = '</p>';
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
public function show() {
$data['users'] = $this->UsersModel->get_users(10, $this->uri->segment(4, 0));
$data['links'] = $this->pagination();
$this->load->view('admin/users', $data);
}
public function delete() {
$user_id = $this->input->post('user_id');
if (!$this->UsersModel->delete_user($user_id)) {
echo "Unknown error";
}
$this->show();
}
public function edit() {
$user_id = $this->input->post('user_id');
$state = $this->input->post('state');
$group = $this->input->post('group');
$data = array(
'id' => $user_id,
'account_status_code' => $state,
'group_status_code' => $group
);
if (!$this->UsersModel->edit_user($data)) {
echo "Unknown error";
}
$this->show();
}
The paging function is working, suppose it is on page 4. After I
editting one of the row, the page go back to first page. I want to
keep it on page 4.
When opening that 4-th page in a browser, you can save its number in session and then after editing you can read that value you stored in session i.e - 4.
#session_start();
function indexAction()
{
$_SESSION['curr_page'] = 4; // or take it from $_GET
}
function saveAction(){
// .... do stuff....
header('location: page.php?page=' . $_SESSION['curr_page']);
}
first the best way to do paging is via get, to get the url friendly and rotating the User in case it needs to pass it on.
you need set data in console.log(), for view if data this value,
if the expected values ​​are coming up to the date, try switching by append html:
example.
$ ("# content") html ('.');
$ ("# content") append (date).;

Not able to load mysql query data in JEasyUI Grid

I am new to PHP and JEasy UI.
I am actually running the demo application of JEasy UI Grid.
Whereas I am not getting the data from Php file to Grid.
Any Idea or suggestion please...!!
Below is My Code:
index.php
<html>
<head>
<meta charset="UTF-8">
<title>Basic CRUD Application - jQuery EasyUI CRUD Demo</title>
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body>
<div class="demo-info" style="margin-bottom:10px">
<div class="demo-tip icon-tip"> </div>
</div>
<table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
url="http://www.jeasyui.com/tutorial/app/crud/get_users.php"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="firstname" width="50">First Name</th>
<th field="lastname" width="50">Last Name</th>
<th field="phone" width="50">Phone</th>
<th field="email" width="50">Email</th>
</tr>
</thead>
</table>
<div id="toolbar">
New User
Edit User
Remove User
</div>
<div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
closed="true" buttons="#dlg-buttons">
<div class="ftitle">User Information</div>
<form id="fm" method="post" novalidate>
<div class="fitem">
<label>First Name:</label>
<input name="firstname" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>Last Name:</label>
<input name="lastname" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>Phone:</label>
<input name="phone">
</div>
<div class="fitem">
<label>Email:</label>
<input name="email" class="easyui-validatebox" validType="email">
</div>
</form>
</div>
<div id="dlg-buttons">
Save
Cancel
</div>
<script type="text/javascript">
var url;
function newUser(){
$('#dlg').dialog('open').dialog('setTitle','New User');
$('#fm').form('clear');
url = 'save_user.php';
}
function editUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$('#dlg').dialog('open').dialog('setTitle','Edit User');
$('#fm').form('load',row);
url = 'update_user.php?id='+row.id;
}
}
function saveUser(){
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errorMsg){
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
function destroyUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$.messager.confirm('Confirm','Are you sure you want to destroy this user?',function(r){
if (r){
$.post('destroy_user.php',{id:row.id},function(result){
if (result.success){
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.errorMsg
});
}
},'json');
}
});
}
}
</script>
<style type="text/css">
#fm{
margin:0;
padding:10px 30px;
}
.ftitle{
font-size:14px;
font-weight:bold;
padding:5px 0;
margin-bottom:10px;
border-bottom:1px solid #ccc;
}
.fitem{
margin-bottom:5px;
}
.fitem label{
display:inline-block;
width:80px;
}
</style>
</body>
</html>
PHP Code URL
http://www.jeasyui.com/tutorial/app/crud/get_users.php
to get the data from datagrid you need to code like this
public function get_user(){
/*Default request pager params from jeasyUI*/
$offset = isset($_POST['page']) ? intval($_POST['page']) : 1;
$limit = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$search = isset($_POST['search']) ? $_POST['itemid'] : '';
$offset = ($offset-1)*$limit;
//change this line to yours
$data = $this->user_model->get_user($offset,$limit,$search);
$i = 0;
$rows = array();
foreach ($data ['data'] as $r) {
$rows[$i]['first_name'] = $r->first_name;
$rows[$i]['last_name'] = $r->last_name;
$rows[$i]['phone'] = $r->phone;
$rows[$i]['email'] = $r->email;
$i++;
}
//keys total & rows is required on jEasyUI
$result = array('total'=>$data['count'],'rows'=>$rows);
echo json_encode($result);
}
more complete example here

CKEditor and CkFinder work fine in PHP but don't show images, flash etc

I'm using a CKEditor along with a CKFinder. Both work fine. When I browse (or copy directly) an image (or flash) to CKEditor, it's displayed within it and inserted into the MySql database.
Aafter inserting it into MySql database, I'm trying to display it in an HTML table where it isn't displayed and the alternate text is displayed.
The image path after browsing an image through the CKFinder is something like the following.
<img alt="" src="/ckfinder/userfiles/images/1243_SS_2502.jpg" style="width: 490px; height: 618px;" />
The contents inserted into the database is as follows.
<img alt="\&quot;\&quot;" data-cke-saved-src="\"
src="\&quot;/ckfinder/userfiles/images/1243_SS_2502.jpg\&quot;" st yle=&
quot;\&quot;width:" 490px;="" height:="" 618px;\"= quot;">
Tried with htmlentities() still it doesn't work. While dealing the same with JSP using JSTL/EL, I had to do the following.
<c:out value="${str}" default="No content found." escapeXml="false"/>
escapeXml="false", where str written in EL was a java.lang.String holding the Oracle clob data after conversion.
What is the way to get around the situation in PHP? Both CKEditor and CKFinder work fine for me.
$ckeditor = new CKEditor();
$ckeditor->basePath = 'ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = 'ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = 'ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = 'ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('description', $ed_about_us);
Edit:
<?php include_once("Lock.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>Wagafashion</title>
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css"/>
<link rel="stylesheet" href="css/template.css" type="text/css"/>
<!--<script type="text/javascript" language="javascript" src="ckeditor/ckeditor.js"></script>-->
<script src="js/jquery-1.6.min.js" type="text/javascript"></script>
<script src="js/languages/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script><script>
jQuery(document).ready(function(){
// binds form submission and fields to the validation engine
jQuery("#dataForm").validationEngine();
});
</script>
<script language="javascript" type="text/javascript">
function deleteSingle(id)
{
var delId=confirm("About us with the id "+id+" is about to be deleted permanently.\n\nAttention : This action will never be undone!\n\nAre you sure...???");
return(delId==true?true:false);
}
</script>
</head>
<body>
<?php
include_once("Connection.php");
include_once("ckeditor/ckeditor.php");
$con=new Connection();
$con->get_connection();
$ed_about_us="";
$flag=-1;
$msg="";
if(isset($_POST['btnSubmit']))
{
$act=trim($_POST['param_action']);
$about_us=$_POST['cms_description'];
if($act=="add")
{
$res=$con->get_data("select count(*) as cnt from cms");
$cnt_cmt=mysql_result($res, 'cnt');
if($cnt_cmt==0)
{
$flag=$con->iud("insert into cms (about_us)values('".mysql_real_escape_string(urlencode($about_us))."')");
}
else
{
$flag=$con->iud("update cms set about_us='".mysql_real_escape_string(urlencode($about_us))."'");
}
if($flag==1)
{
$msg="Insertion done successfully.";
}
else if($flag==0)
{
$msg="Insertion failed - reason : ".mysql_errno()." : ".mysql_error();
}
}
else if($act=="edit")
{
$cms_id=$_POST['cms_id'];
$flag=$con->iud("update cms set about_us='".mysql_real_escape_string(urlencode($about_us))."' where id=".$cms_id."");
if($flag==1)
{
$msg="About us has been updated successfully.";
}
else if($flag==0)
{
$msg="Updation failed - reason : ".mysql_errno()." : ".mysql_error();
}
}
}
else if(isset($_GET['ed_id']))
{
$ed_res=$con->get_data("select about_us from cms where id=".$_GET['ed_id']."");
while($row=mysql_fetch_assoc($ed_res))
{
$ed_about_us=$row['about_us'];
}
}
else if(isset($_GET['del_id']))
{
$flag=$con->iud("update cms set about_us='' where id=".$_GET['del_id']);
if($flag==1)
{
$msg="About us been deleted successfully.";
}
else if($flag==0)
{
$msg="Can not delete - reason : ".mysql_errno()." : ".mysql_error();
}
}
else if(isset($_POST['btnDelete']))
{
$set_del=$_POST['setDel'];
$flag=$con->iud("update cms set about_us='' where id in($set_del)");
$size=sizeof(split(",", $set_del));
if($flag==1)
{
if($size==1)
{
$msg="1 row deleted.";
}
else
{
$msg=$size." rows deleted.";
}
}
else if($flag==0)
{
$msg="Can not perform deletion - reason : ".mysql_errno()." : ".mysql_error();
}
}
?>
<?php include("tamplate/Template1.php");?>
<h2>About Us</h2>
<?php include("tamplate/NewTemplate.php");?>
<?php
if($flag==1)
{
echo "<p>";
?>
<!--[if !IE]>start system messages<![endif]-->
<ul class="system_messages">
<li class="green"><span class="ico"></span><strong class="system_title"><?php echo $msg; ?></strong></li>
</ul>
<!--[if !IE]>end system messages<![endif]-->
<?php
echo "</p>";
}
else if($flag==0)
{
echo "<p>";
?>
<!--[if !IE]>start system messages<![endif]-->
<ul class="system_messages">
<li class="red"><span class="ico"></span><strong class="system_title"><?php echo $msg; ?></strong></li>
</ul>
<!--[if !IE]>end system messages<![endif]-->
<?php
echo "</p>";
}
?>
<img alt=\"\" src="/ckfinder/userfiles/images/1243_SS_2502.jpg" style=\"width: 490px; height: 618px;\" />
<!--[if !IE]>start forms<![endif]-->
<form action="<?php $_SERVER['PHP_SELF']; ?>" id="dataForm" name="dataForm" method="post" class="search_form general_form">
<!--[if !IE]>start fieldset<![endif]-->
<fieldset>
<!--[if !IE]>start forms<![endif]-->
<div class="forms">
<!--[if !IE]>start row<![endif]-->
<div class="row">
<?php
$ckeditor = new CKEditor();
$ckeditor->basePath = 'ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = 'ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = 'ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = 'ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('cms_description', urldecode($ed_about_us));
?>
<!--[if !IE]>start row<![endif]-->
<div class="row">
<div class="buttons">
<span class="button send_form_btn"><span><span>Submit</span></span><input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" onclick="return validate();"></span>
</div>
</div>
<!--[if !IE]>end row<![endif]-->
</div>
</fieldset>
<!--[if !IE]>end fieldset<![endif]-->
<input type="hidden" id="param_action" name="param_action" value="
<?php
if(isset($_GET['ed_id']))
{
echo "edit";
}
else
{
echo "add";
}
?>
" />
<input type="hidden" id="cms_id" name="cms_id" value="<?php echo isset($_GET['ed_id'])?$_GET['ed_id']:"";?>" />
</form>
<?php include("tamplate/Template2.php");?>
<h2>About Us</h2>
<?php include("tamplate/NewTemplate1.php");?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="mainForm" name="mainForm" method="post">
<?php include("tamplate/ExtraTemplate.php");?>
<table cellpadding="0" cellspacing="0" width="100%">
<tbody>
<th style="width: 10px;">Check</th>
<th style="width: 450px;">About Us</th>
<th style="width: 10px;">Actions</th>
<?php
$get_data=$con->get_data("select id, about_us from cms order by id");
$cnt=1;$flag='';
while($data_row=mysql_fetch_assoc($get_data))
{
extract($data_row);
$cnt%2==0?$flag="second":$flag="first";
++$cnt;
echo "<tr class='$flag'>";
echo "<td><input type='checkbox' name='chk' value='$id'></td>";
echo "<td>".urldecode($about_us)."</td>";
echo "<td><div class='actions'><ul><li><a href='".$_SERVER['PHP_SELF']."?ed_id=$id' class='action2'></a></li>";
echo "<li><a href='".$_SERVER['PHP_SELF']."?del_id=$id&table_name=cms&pri=id' onclick='return deleteSingle($id);' class='action4'></a></li></ul></div></td>";
echo "</tr>";
}
?>
</tbody>
</table>
<input type='hidden' id='setDel' name='setDel'/>
<?php include("tamplate/Template3.php");?>
</form>
<?php include("tamplate/Template4.php");?>
</body>
</html>
Did you try to use html_entity_decode() to display the contents ? It will decode the encoded html for better output. Reference here
Edit
Change your query to the following
insert into cms (about_us) values ('".mysql_real_escape_string(urlecode(stripslashes($about_us)))‌​."')
When you get it from database it use
urldecode($value)
Where $value is the block you got from database.

Categories