tutorial101 is the one place for high quality web development, Web Design and software development tutorials and Resources programming. Learn cutting edge techniques in web development, design and software development, download source components and participate in the community.
Ajax Add & Delete MySQL records using jQuery & PHP
Create Table
CREATE TABLE IF NOT EXISTS `add_delete_record` ( `id` int(11) NOT NULL AUTO_INCREMENT, `content` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
//index.php
<html>
<head>
<title>Ajax Add/Delete Record with jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val()==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
jQuery.ajax({
type: "POST", // Post / Get method
url: "response.php", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
$("#responds").append(response);
$("#contentText").val('');
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
$("body").on("click", "#responds .del_button", function(e) {
e.returnValue = false;
var clickedID = this.id.split('-'); //Split string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
jQuery.ajax({
type: "POST", // Post method
url: "response.php",
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
$('#item_'+DbNumberID).fadeOut("slow");
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
</script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content_wrapper">
<ul id="responds">
<?php
include_once("config.php");
//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");
//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
echo '<li id="item_'.$row["id"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $row["content"].'</li>';
}
mysql_close($connecDB);
?>
</ul>
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
<button id="FormSubmit">Add record</button>
</div>
</div>
</body>
</html>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script><script>
$(document).ready(function(){
var totalChars = 100; //Total characters allowed in textarea
var countTextBox = $('#counttextarea') // Textarea input box
var charsCountEl = $('#countchars'); // Remaining chars count will be displayed here
charsCountEl.text(totalChars); //initial value of countchars element
countTextBox.keyup(function() { //user releases a key on the keyboard
var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea
var per = thisChars*100;
var value= (per / totalChars); // total percent complete
if(thisChars > totalChars) //if we have more chars than it should be
{
var CharsToDel = (thisChars-totalChars); // total extra chars to delete
this.value = this.value.substring(0,this.value.length-CharsToDel); //remove excess chars from textarea
}else{
charsCountEl.text( totalChars - thisChars ); //count remaining chars
$('#percent').text(value +'%');
}
});
});
</script>
<div class="main-item"><div><textarea name="counttextarea" id="counttextarea" cols="45" rows="5" style="width: 400px;padding: 10px;"></textarea></div>
<div><span name="countchars" id="countchars"></span> Characters Remaining. <span name="percent" id="percent"></span></div>
</div>
Create Database Table CREATE TABLE `categories` ( `id` INTEGER(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM Crate Model app\models\category.php
<?php
class Category extends AppModel {
var $name = 'Category';
var $validate = array( //validate
'name' => array(
'rule' => 'notEmpty',
'message' => 'No, no, this field must not be empty!'
)
);
}
?>
<?php
class CategoriesController extends AppController {
var $name = 'Categories';
function index() {
$this->set('categories', $this->Category->find('all'));
}
function add() {
if (!empty($this->data)) {
if ($this->Category->save($this->data)) {
$this->Session->setFlash('Your category has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
function delete($id) {
$this->Category->delete($id);
$this->Session->setFlash('The category with id: '.$id.' has been deleted.');
$this->redirect(array('action'=>'index'));
}
function edit($id = null) {
$this->Category->id = $id;
if (empty($this->data)) {
$this->data = $this->Category->read();
} else {
if ($this->Category->save($this->data)) {
$this->Session->setFlash('Your category has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
}
?>
<?php
class CategoriesController extends AppController {
var $name = 'Categories';
function index() {
$this->set('categories', $this->Category->find('all'));
}
function add() {
if (!empty($this->data)) {
if ($this->Category->save($this->data)) {
$this->Session->setFlash('Your category has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
}
?>
A function is a self-contained piece of code which carries out a particular task or function. benefit of using functions is that they are reusable
<?php
//Defining a Function
//syntax for defining a function
function addNumbers($num1, $num2) {
$result = $num1 + $num2;
return $result;
}
$total = addNumbers(5, 10);
//echo $total; //result 15
//Organizing Functions
function hello() {
echo "<h1>HELLO!</h1>";
echo "<p>Welcome to my web site</p>";
}
function printBreak($text) {
echo "$text<br>";
}
function addNumbers($num1, $num2) {
return $num1 + $num2;
}
echo hello();
echo printBreak("This is a line");
echo addNumbers(3.75, 5.645); //9.39536.75
//Accepting a Variable Number of Arguments
function calcAverage() {
// initialize value to be used in calculation
$total = 0;
// find out how many arguments were given
$arguments = func_num_args();
// loop to process each argument separately
for ($i = 0; $i < $arguments; $i++) {
// add the value in the current argument to the total
$total += func_get_arg($i);
}
// after adding all arguments, calculate the average
$average = $total / $arguments;
// return the average
return $average;
}
// invoke the function with 5 arguments
//echo calcAverage(44, 55, 66, 77, 88); //output 66
// invoke the function with 8 arguments
echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7); //ouput 36.75
CREATE TABLE IF NOT EXISTS `users` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`username` varchar(15) NOT NULL,
`password` text NOT NULL,
`fullname` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
)
Setup Controller
application\controllers\user.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
/**
* The __construct function is called so that I don't have to load the model each and every time.
* And any change while refactoring or something else would mean change in only one place.
*/
function __construct() {
parent::__construct();
$this->load->model('Model_user');
$this->load->library('form_validation');
$this->load->helper('form');
}
function index(){
$data['query'] = $this->Model_user->getAll();
$this->load->view('view_user/input',$data);
}
function submit(){
if ($this->input->post('submit')){
if ($this->input->post('id')){
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'matches[passconf]');
$this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]');
if ($this->form_validation->run() == FALSE){
$data['id'] = $this->input->post('id');
$data['username'] = set_value('username');
$data['fullname'] = set_value('fullname');
$this->load->view('view_user/edit',$data);
}else{
$this->Model_user->update();
redirect('view_user/index');
}
}else{
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]');
if ($this->form_validation->run() == FALSE){
$data['query'] = $this->Model_user->getAll();
$this->load->view('view_user/input',$data);
}else{
$this->Model_user->save();
redirect('user/index');
}
}
}
}
function edit(){
$id=$this->uri->segment(3);
$data['result']=$this->Model_user->getUser($id);
if (empty($id) or count($data['result'])==0 ){
redirect('user/index');
}else{
$result=$this->Model_user->getUser($id);
$data['id'] = $result['id'];
$data['username'] = $result['username'];
$data['fullname'] = $result['fullname'];
$this->load->view('view_user', $data);
}
}
function delete($id){
$this->db->delete('user', array('id' => $id));
redirect('user/index');
}
}
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login_view');
}
else
{
//Go to private area
redirect('home', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
Home Controller (application/controllers/home.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('home_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home', 'refresh');
}
}
?>
<script>
function confirmDelete()
{
return confirm("Are you sure you wish to delete this entry?");
}
</script>
<a href="?action=delete&id=3" onclick="return confirmDelete();"> Delete this entry</a>
<?php
//PHP Tutorial: Classes and OOP
//The first thing you do is to define the class:
class cow
{
}
//Next, we'll create our first function - this is defined exactly the same as if you were not using classes:
// First we define the class
class cow
{
// Define the function moo() - no parameters
function moo()
{
// Define the variable
$sound = 'Moooooo';
return $sound;
}
}
//create the new class object 'in' a variable
// Create new cow object
$daisy = new cow;
//then call the moo() function
echo $daisy->moo();
//If you put this code together then, you will get something like this:
// First we define the class
class cow
{
// Define the function moo() - no parameters
function moo()
{
// Define the variable
$sound = 'Moooooo';
return $sound;
}
}
// Create new cow object
$daisy = new cow;
echo $daisy->moo();
//Ex. more functions
// First we define the class
class cow
{
var $eaten;
// Define the function moo() - no parameters
function moo()
{
// Define the variable
$sound = 'Moooooo<br />';
return $sound;
}
function eat_grass($colour)
{
if ($colour == 'green')
{
// cow is happy
$this->eaten = true;
return $this->moo();
}
}
function make_milk()
{
if ($this->eaten)
{
return 'Milk produced<br />';
}
else
{
return 'cow has not eaten yet<br />';
}
}
}
//call these functions and try out the new class
// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();
echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced
//final version
// First we define the class
class cow
{
var $eaten;
// Define the function moo() - no parameters
function moo()
{
// Define the variable
$sound = 'Moooooo<br />';
return $sound;
}
function eat_grass($colour)
{
if ($colour == 'green')
{
// cow is happy
$this->eaten = true;
return $this->moo();
}
}
function make_milk()
{
if ($this->eaten)
{
return 'Milk produced<br />';
}
else
{
return 'cow has not eaten yet<br />';
}
}
}
// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();
echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced
?>
//do_search.php
<?php
//if we got something through $_POST
if (isset($_POST['search'])) {
// here you would normally include some database connection
include('db.php');
$db = new db();
// never trust what user wrote! We must ALWAYS sanitize user input
$word = mysql_real_escape_string($_POST['search']);
$word = htmlentities($word);
// build your search query to the database
$sql = "SELECT title, url FROM pages WHERE content LIKE '%" . $word . "%' ORDER BY title LIMIT 10";
// get results
$row = $db->select_list($sql);
if(count($row)) {
$end_result = '';
foreach($row as $r) {
$result = $r['title'];
// we will use this to bold the search word in result
$bold = '<span class="found">' . $word . '</span>';
$end_result .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
}
?>