In this tutorial we will see that how to create database CRUD operations using Object Oriented concept in PDO with Bootstrap framework, i have used here Bootstrap framework for front-end design and the MySQL database operations will done by PDO and OOP, recently i have posted pagination tutorial using PDO and OOP and one of my blog reader request me to post that how to use OOP concept to create CRUD operations in PDO, so in this tutorial i I'm going to explain OOP with PDO using Bootstrap framework. so Learn PHP OOP with PDO.
create() and update() functions are in try/catch block to handle exceptions.
dataview() function selects the whole records from database table.
paging() function set’s the QueryString like “page_no=number”.
paginglink() function creates the paging number links with “previoue and next” feature.
all the CRUD and Pagination operations are done by this file.
header.php
This header.php file will be included at the beginning of all files so that we won’t have to write the same header codes every-time. this file contains bootstrap file links.
footer.php
This footer.php file will be included at the end of all files so that we won’t have to write the same footer codes every-time.
above code will give following output :
in this file some appropriate message are given about data are insert or not with bootstrap label.
this will create following form :
above code for deletion gives following output :
if the record was deleted the output will be as follow :
that’s it we have created here Simple PDO CRUD Operation using OOP with Bootstrap framework with pagination feature.
download the script by clicking following link and try it in your projects.
Feel free to comment your suggestions regarding this tutorial.
Database Design & table
create database named 'dbpdo' and import the following code in your phpmyadmin it will create table and user fields.
CREATE TABLE IF NOT EXISTS `tbl_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
`email_id` varchar(50) NOT NULL,
`contact_no` bigint(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;
Directory
our directory will be as follow :
bootstrap/
├── css/
│ ├── bootstrap.min.css
├── js/
│ └── bootstrap.min.js
└── fonts/
├── glyphicons-halflings-regular.eot
├── glyphicons-halflings-regular.svg
├── glyphicons-halflings-regular.ttf
└── glyphicons-halflings-regular.woff
add-data.php
class.crud.php
dbconfig.php
delete.php
edit-data.php
footer.php
header.php
index.php
dbconfig.php
Set the credentials for the database and make a new PDO connection if the connection fails display the error . Next include the ‘class.crud.php’ file and make an instance of it, pass in the database object to the class to make use of the database.
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "dbpdo";
try
{
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
include_once 'class.crud.php';
$crud = new crud($DB_con);
?>
class.crud.php
this is the main class file which contains code for database operations.create() and update() functions are in try/catch block to handle exceptions.
dataview() function selects the whole records from database table.
paging() function set’s the QueryString like “page_no=number”.
paginglink() function creates the paging number links with “previoue and next” feature.
all the CRUD and Pagination operations are done by this file.
<?php
class crud
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function create($fname,$lname,$email,$contact)
{
try
{
$stmt = $this->db->prepare("INSERT INTO tbl_users(first_name,last_name,email_id,contact_no) VALUES(:fname, :lname, :email, :contact)");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":email",$email);
$stmt->bindparam(":contact",$contact);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function getID($id)
{
$stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
public function update($id,$fname,$lname,$email,$contact)
{
try
{
$stmt=$this->db->prepare("UPDATE tbl_users SET first_name=:fname,
last_name=:lname,
email_id=:email,
contact_no=:contact
WHERE id=:id ");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":email",$email);
$stmt->bindparam(":contact",$contact);
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function delete($id)
{
$stmt = $this->db->prepare("DELETE FROM tbl_users WHERE id=:id");
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
/* paging */
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['first_name']); ?></td>
<td><?php print($row['last_name']); ?></td>
<td><?php print($row['email_id']); ?></td>
<td><?php print($row['contact_no']); ?></td>
<td align="center">
<a href="edit-data.php?edit_id=<?php print($row['id']); ?>"><i class="glyphicon glyphicon-edit"></i></a>
</td>
<td align="center">
<a href="delete.php?delete_id=<?php print($row['id']); ?>"><i class="glyphicon glyphicon-remove-circle"></i></a>
</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position=($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><ul class="pagination"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<li><a href='".$self."?page_no=1'>First</a></li>";
echo "<li><a href='".$self."?page_no=".$previous."'>Previous</a></li>";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<li><a href='".$self."?page_no=".$i."' style='color:red;'>".$i."</a></li>";
}
else
{
echo "<li><a href='".$self."?page_no=".$i."'>".$i."</a></li>";
}
}
if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<li><a href='".$self."?page_no=".$next."'>Next</a></li>";
echo "<li><a href='".$self."?page_no=".$total_no_of_pages."'>Last</a></li>";
}
?></ul><?php
}
}
/* paging */
}
layouts
To reduce and make it less our code, we will create these two template files: header.php, footer.phpheader.php
This header.php file will be included at the beginning of all files so that we won’t have to write the same header codes every-time. this file contains bootstrap file links.
<!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>PDO OOP CRUD using Bootstrap</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="http://www.codingcage.com" title='Programming Blog'>Coding Cage</a>
<a class="navbar-brand" href="https://codingcage.com/search/label/CRUD">CRUD</a>
<a class="navbar-brand" href="https://codingcage.com/search/label/PDO">PDO</a>
<a class="navbar-brand" href="https://codingcage.com/search/label/jQuery">jQuery</a>
</div>
</div>
</div>
footer.php
This footer.php file will be included at the end of all files so that we won’t have to write the same footer codes every-time.
<div class="container">
<div class="alert alert-info">
<strong>tutorial !</strong> <a href="https://codingcage.com/">Coding Cage</a>!
</div>
</div>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
index.php
this file will show the records from the mysql database with pagination feature. the table which are used in this file are created under bootstrap data table with class='table table-bordered table-responsive' it will make tables look pretty.
<?php
include_once 'dbconfig.php';
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<a href="add-data.php" class="btn btn-large btn-info"><i class="glyphicon glyphicon-plus"></i> Add Records</a>
</div>
<div class="clearfix"></div><br />
<div class="container">
<table class='table table-bordered table-responsive'>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>E - mail ID</th>
<th>Contact No</th>
<th colspan="2" align="center">Actions</th>
</tr>
<?php
$query = "SELECT * FROM tbl_users";
$records_per_page=3;
$newquery = $crud->paging($query,$records_per_page);
$crud->dataview($newquery);
?>
<tr>
<td colspan="7" align="center">
<div class="pagination-wrap">
<?php $crud->paginglink($query,$records_per_page); ?>
</div>
</td>
</tr>
</table>
</div>
<?php include_once 'footer.php'; ?>
above code will give following output :
add-data.php
now create a file and name it 'add-data.php' to get data from users to store into mysql database.in this file some appropriate message are given about data are insert or not with bootstrap label.
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email_id'];
$contact = $_POST['contact_no'];
if($crud->create($fname,$lname,$email,$contact))
{
header("Location: add-data.php?inserted");
}
else
{
header("Location: add-data.php?failure");
}
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<?php
if(isset($_GET['inserted']))
{
?>
<div class="container">
<div class="alert alert-info">
<strong>WOW!</strong> Record was inserted successfully <a href="index.php">HOME</a>!
</div>
</div>
<?php
}
else if(isset($_GET['failure']))
{
?>
<div class="container">
<div class="alert alert-warning">
<strong>SORRY!</strong> ERROR while inserting record !
</div>
</div>
<?php
}
?>
<div class="clearfix"></div><br />
<div class="container">
<form method='post'>
<table class='table table-bordered'>
<tr>
<td>First Name</td>
<td><input type='text' name='first_name' class='form-control' required></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type='text' name='last_name' class='form-control' required></td>
</tr>
<tr>
<td>Your E-mail ID</td>
<td><input type='text' name='email_id' class='form-control' required></td>
</tr>
<tr>
<td>Contact No</td>
<td><input type='text' name='contact_no' class='form-control' required></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-save">
<span class="glyphicon glyphicon-plus"></span> Create New Record
</button>
<a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> Back to index</a>
</td>
</tr>
</table>
</form>
</div>
<?php include_once 'footer.php'; ?>
this will create following form :
edit-data.php
after creating a data insert form, this file updates the users data and the update operation are done by update() function which are define in 'class.crud.php' class file
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-update']))
{
$id = $_GET['edit_id'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email_id'];
$contact = $_POST['contact_no'];
if($crud->update($id,$fname,$lname,$email,$contact))
{
$msg = "<div class='alert alert-info'>
<strong>WOW!</strong> Record was updated successfully <a href='index.php'>HOME</a>!
</div>";
}
else
{
$msg = "<div class='alert alert-warning'>
<strong>SORRY!</strong> ERROR while updating record !
</div>";
}
}
if(isset($_GET['edit_id']))
{
$id = $_GET['edit_id'];
extract($crud->getID($id));
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($msg))
{
echo $msg;
}
?>
</div>
<div class="clearfix"></div><br />
<div class="container">
<form method='post'>
<table class='table table-bordered'>
<tr>
<td>First Name</td>
<td><input type='text' name='first_name' class='form-control' value="<?php echo $first_name; ?>" required></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type='text' name='last_name' class='form-control' value="<?php echo $last_name; ?>" required></td>
</tr>
<tr>
<td>Your E-mail ID</td>
<td><input type='text' name='email_id' class='form-control' value="<?php echo $email_id; ?>" required></td>
</tr>
<tr>
<td>Contact No</td>
<td><input type='text' name='contact_no' class='form-control' value="<?php echo $contact_no; ?>" required></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-update">
<span class="glyphicon glyphicon-edit"></span> Update this Record
</button>
<a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> CANCEL</a>
</td>
</tr>
</table>
</form>
</div>
<?php include_once 'footer.php'; ?>
delete.php
this file contains code for data delete operation using delete() function by passing id argument's value of selected data and row and by pressing the delete button the record will be deleted and message will be given that the record was deleted.
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-del']))
{
$id = $_GET['delete_id'];
$crud->delete($id);
header("Location: delete.php?deleted");
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($_GET['deleted']))
{
?>
<div class="alert alert-success">
<strong>Success!</strong> record was deleted...
</div>
<?php
}
else
{
?>
<div class="alert alert-danger">
<strong>Sure !</strong> to remove the following record ?
</div>
<?php
}
?>
</div>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($_GET['delete_id']))
{
?>
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>E - mail ID</th>
<th>Gender</th>
</tr>
<?php
$stmt = $DB_con->prepare("SELECT * FROM tbl_users WHERE id=:id");
$stmt->execute(array(":id"=>$_GET['delete_id']));
while($row=$stmt->fetch(PDO::FETCH_BOTH))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['first_name']); ?></td>
<td><?php print($row['last_name']); ?></td>
<td><?php print($row['email_id']); ?></td>
<td><?php print($row['contact_no']); ?></td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
</div>
<div class="container">
<p>
<?php
if(isset($_GET['delete_id']))
{
?>
<form method="post">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
<button class="btn btn-large btn-primary" type="submit" name="btn-del"><i class="glyphicon glyphicon-trash"></i> YES</button>
<a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> NO</a>
</form>
<?php
}
else
{
?>
<a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> Back to index</a>
<?php
}
?>
</p>
</div>
<?php include_once 'footer.php'; ?>
above code for deletion gives following output :
if the record was deleted the output will be as follow :
that’s it we have created here Simple PDO CRUD Operation using OOP with Bootstrap framework with pagination feature.
download the script by clicking following link and try it in your projects.
Feel free to comment your suggestions regarding this tutorial.
looks good using bootstrap, nice tutorial
ReplyDeleteVery good stuff. Thanks a lot.
ReplyDeletevery nice script, with all, so use PDO for PHP and use bind of variables style JAVA prepared statements.
ReplyDeleteThank you so much...
Change contact_no in MySQL from int to bigint, and everything starts working.
ReplyDeletethanks for correcting me on it...
DeleteGracias por el código.
ReplyDeleteNice script! Although, if you keep ?inserted at the end of url and hit submit without a field you get blank in db.. I would put ... if (empty($_POST['example'] || etc, etc)) { header("Location: index.php?failure"); } else { $example = $_POST['example']}inside the if(isset($_POST['btn-save'])) to prevent this.
ReplyDeleteIt is nice to work with, but not safe so, because you can fill out all input fields in the what ever you want, such as, for example, niek# hotmail.com or [email protected]@hotmail.com
ReplyDeleteya but it was just for clearing concept.
Deletefor proper form validations, TRY the following
Form Validatiosn using jQuery
Form Validatiosn using HTML5
Server Side Form Validatiosns using PHP
I have those other links below once viewed and tried out.
ReplyDeleteBut when I put a patern as below in the input field then put that doesn't work in this PDO script
input type='text' pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" name='email_id' class='form-control' required
try the following, it works
Delete<input type='email' pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" name='email_id' class='form-control' required>
Thanks that works.
ReplyDeleteOnly one more question: why email_id and email.
I ask that because I already have a registration script, with a user_id, user_name, user_email and user_password, But that has no edit and delette script.
And that's why I use now this Grud script
you can change "email_id" into "user_email" and
Delete<input type="email" />
well it's a new HTML5 attribute
could not find driver
ReplyDeleteFatal error: Call to a member function prepare() on a non-object in C:\AppServ\www\poo\class.crud.php on line 16
porq este error ??????
open "php.ini" file of your localhost server and
Deletefind for ";extension=php_pdo_mysql.dll" and remove the
semi-colon then save file and restart your server it enables PDO Driver.
Great beginning php tutorials Very clear and helpful for beginners.
ReplyDeleteThank you for this tutorial. For someone that has to re-learn PHP as several functions (like mysql_connect) no longer work in the newest version of PHP, this has helped me quite a bit. I do have a couple questions though. When adding a phone number in U.S. format (XXX-XXX-XXXX), only the first 3 numbers are added to the database but the first dash and everything behind it is not added. I've been trying to figure out why, but I'm kind of stumped. Any ideas? Also any tips on adding a search function?
ReplyDeleteAhh, I figured out why the phone number wasn't doing the dashes. Changed the MySQL table BIGINT to VARCHAR and it saves correctly now.
ReplyDeleteNice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.
ReplyDeleteHi, I posted a comment in your tutorial Simple PHP CRUD Operations.I think i should have posted it here instead. My question is, how do i add images and pdf's to the crud operations. I want the user to upload images and pdf's and save them in folders. I tried combining this tutorial with http://cleartuts.blogspot.com/2014/12/simple-file-uploading-with-php.html but wasn't successful. Thank you and i really like your tutorials. Great work :)
ReplyDeletecombining these two things is easy, just alter your mysql table and add image, pdf file fields to the table and make change in sql insert query as i showed in following tutorial :
Deletehttps://codingcage.com/2014/12/file-upload-and-view-with-php-and-mysql.html
it is easy up to the point where the folder comes in.I am confused as to how and where some of the code from the file upload tutorial will fit into the php-pdo-crud-tutorial. This is what i have so far. Thank you. I really appreciate your help.
Deletecreate($first_name,$last_name,$gender, $student_phone_number, $parent_phone_number, $student_email, $course, $admission_type, $qualification))
{
$sql="INSERT INTO students(file,type,size) VALUES('$final_file','$file_type','$new_size')";
mysql_query($sql);
header("Location: add-data.php?inserted");
}
else
{
// header("Location: add-data.php?failure");
echo "string";
}
}
?>
Have available the code to integrate search functionality? Thank you.
ReplyDeleteI'll post a tutorial about it soon
DeleteRally awesome tutorial, very well!
ReplyDeleteI also see your login tutorial, how to apply your login to this?
Thanks.
Hello everybody !
ReplyDeleteThank you very much for this job very well explained, being a novice in php coding, I have a comment,
Pagination displays all the page numbers, it is a big disadvantage when we have a database with 1000 line,
Because with 1000 lines in database, if we want to see 10 lines per page, there will be 100 pages number in the paging bar,
Can we add some settings in the paging function to limit the number of links (number of pages) displayable in the pagination bar?
Best regards.
did you mean page no as query string in address bar if so , then we can use jquery ,ajax to paginate all the records ...
DeleteHi Pradeep !
DeleteIn my case I have for example 1000 records (rows) in the database
The only config parameter for the function is : "$records_per_page=X;"
With "$records_per_page=10;" there will be 100 page links in the paging bar, it's a lot
I asked i you cas improve the function by limiting the number of page links displayed
Cordially, Hafid.
Rally awesome tutorial, very well!
ReplyDeleteI also see your login tutorial, how to apply your login to this?
Thanks.
How i can do radio insert, file gen male or female?
ReplyDeletetry the following example :
Delete<?php
if(isset($_POST['btn']))
{
echo $_POST['gen'];
}
?>
<form method="post">
<label>Male <input type="radio" name="gen" value="Male" /></label>
<label>FeMale <input type="radio" name="gen" value="FeMale" /></label>
<button type="submit" name="btn">print</button>
</form>
Hello !
ReplyDeleteReally good works !
But i've got a problem :) I've changed an "input" with a "textarea"... "Insert" and "delete" works fine.. but with "edit" the textarea is blank ! Where is the problem ?
Thanks
hi there,
Deletewithin textarea <textarea name="txt_area"> put here php code </textarea> while editing
Where do the variables that you echo out in the update section? I don't see $first_name, $last_name, etc.. being set anywhere. Not sure where you got them.. Can someone explain?
ReplyDeleteThx
hello laslomcd,
Deletethese variables are extracted using extract() function and within class.crud.php file "extract($crud->getID($id))" function returns edited rows from database.
Hello thanks for your Best crud...but what are the modification for putting edit and delete form in a Popup ?thankssss
ReplyDeletehello heyhooo, i will make a tutorial about it soon, keep visiting :)
DeleteUr the best !
ReplyDeleteUr the best !
ReplyDeletethanks heyhoo ....
DeleteHello...How can I add a button to select all rows for example in order to delete multiple rows....thankkssss
ReplyDeleteHi HeyHooo, this article might help you to delete multiple rows
Deletemultiple update delete using php mysql
Thxx for all!
ReplyDeleteThe "problem" is about the code: mysqli in one and Pdo in the other....can I use your First crud (multiple) without putting Pdo ?
yes you can use, without using pdo
Delete...because the multiple delete,update,....is really wonderfull!...but for more "security" a confirmation before delete (like in ur CRUD PDO oop) is necessary...so, for u, can I use ur First multiple CRUD without re-coding all With Pdo ?(ps: I use already phpmyadmin)
ReplyDeletehi heyhooo, you can use both, without re-coding, you can use pdo or mysqli, crud concept was same they are only improved extensions .
Deletetutorial is really nice and useful .. only two thing I want to know is what does this means
ReplyDelete"bindparam(":fname",$fname);"
1-bindparam
2-colon(":").
I will be grateful if you explain those two things.. I am relatively new so there is confusion in it.
hello taj,
Deletebindparam(":fname",$fname);
1 bindParam — Binds a parameter to the specified variable name
2 colon -- specifies the column which are declared in bindParam(),
well you can also use this
bindParam('val', $value, PDO::PARAM_STR);
click here to know more
i will give it a try , thank for the code, greetings from el salvador.
ReplyDeletethanks jose....
DeleteHello,
ReplyDeleteEverything works fine for me, but i've changed a "input" with a "textarea" with a wysiwyg...and now, i've got html tags in my database... how can i delete these html tags in PDO ?
Hello cetmol,
Deletesorry for the late reply and use htmlspecialchars(); function to convert html elements to special characters
Congratulations on the job , a question if possible .
ReplyDeleteHow can I insert a button print on the edit-data.php , to pass parameters to a page xxx.php ( html2pdf ) to generate a page pdf data ??
thank you
how can i get bootstrap for my template
ReplyDeleteHi Thank You for posting these posts your code is work perfectly
ReplyDeletebut i have one problem i was added some ID it's work when i ad New record but when i try to update name contact number it's come blank field
$id = $_GET['edit_id'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email_id'];
$emp_dep = $_POST['emp_dep'];
$emp_sal = $_POST['emp_sal'];
$login_id = $_POST['login_id'];
$pass = $_POST['pass'];
$contact = $_POST['contact_no'];
if($crud->update($id,$fname,$lname,$email,$emp_dep,$emp_sal,$login_id,$pass,$contact))
Got the same problem, did you find a way to fix it?
Deletedownload botton doesn't work
ReplyDeleteUpdated, working now ... download it ...
DeleteHi Pradeep, very good script, thank you. An excellent enhancement to this would be to use a bootstrap modal and call the add-data.php and edit-data.php etc. I've tried and posted on stackoverflow but not getting the answers. Any chance you could do this for us?
ReplyDeleteHi Pradeep, very good script, thank you. An excellent enhancement to this would be to use a bootstrap modal and call the add-data.php and edit-data.php etc. I've tried and posted on stackoverflow but not getting the answers. Any chance you could do this for us?
ReplyDeletehey james, i will post modal window crud with php tutorial soon ...
DeleteMr. Khodke
ReplyDeleteThis is a nice tutorial blog. Could you help me with code in PDP MySQL in OOPHP to upload file.
Thanks
i will post file uploading tutorial using PHP PDO with OOP ....
DeleteMr. Khodke,
DeleteCould the post as needed be posted immediately? If it would be possible it would be really very helpful for me. Good night.
Mr Khodke,
ReplyDeleteThank you again for the wonderful tutorial. How to add image to mysql table in this script? Could you help?
Hello Bishwajit,
Deletejust alter your table and add new field for image and add code for image uploading with insert query,
here is file uploading code : file upload with php mysql
The image insertion , update and delete should happen in php mysql pdo environment
DeleteHello..
ReplyDeleteNice tutorials and thanks, greetings from Indonesia.
thanks wahyu... keep visiting :)
DeleteVery good example !!!
ReplyDeletethanks jordan... do visit again :)
DeleteAre you able to unit test this, if so how?
ReplyDeletevery useful example, exactly what I was looking for - many thanks.
ReplyDeleteThank you... Danut
DeleteVery cool script...EXACTLY what I've been searching for and trying to acheive for several weeks now. I have 7 different test sites that I have been trying accomplish the same thing on, problem is, every tutorial throws errors and I have NO CLUE how to fix them. This tut is no different. Getting undefined variables in dbcrud file and Fatal error: Call to a member function prepare() on null. I don't want the answer to these, I want to know how to fix these myself. Any suggestions, PLEASE????
ReplyDeleteHallo admin ..
ReplyDeletepreviously thank you for sharing script free PDO. This is very cool.
I added in the database UNIQUE USERS hopes that could not make anything duplicate with others.
For example, I edit the username as 'Admin' which have previously been stored in the database with another account.
In fact, USERS can not change their name to Admin, however, ERROR messages that appear unsightly.
Like this:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'Admin' for key 'uname'
How to change the error message?
Interesting example, but based on the date of the post,I am surprised that you show it using mySql database connections and not PDO when mySql has been deprecated for several years. At the very least the database connections should be in mySqli. Also as a DB programmer, I would always try to use '?' for params in your query strings for safety/security reasons.
ReplyDeleteDo you have updated code for this example?
hi there, why are you surprised, i have just used here PDO extension to Perform CRUD operations with OOP way, and my friend mysql query(extension) is deprecated from several years the PDO extension is improved mysql extension it is a database layer and it also prevent sql injections cause there are prepare, bindparam and execute statements and methods.
DeleteHi Pradeep,
ReplyDeletei have add a column name "status" at tbl_users. the value is 0 and 1. i want to data on,ly have status = 1. How to code ?
sorry my english :)
Hi, I found this error both when I try to re-write them by myself and use the script I've downloaded:
ReplyDeleteFatal error: Uncaught Error: Call to a member function prepare() on string in C:\xampp\htdocs\CRUD2\class.crud.php:71 Stack trace: #0 C:\xampp\htdocs\CRUD2\index.php(27): crud->dataview('SELECT*FROM tbl...') #1 {main} thrown in C:\xampp\htdocs\CRUD2\class.crud.php on line 71
The line for C:\xampp\htdocs\CRUD2\class.crud.php:71 is:
$stmt = $this->db->prepare($query);
and for C:\xampp\htdocs\CRUD2\index.php(27):
$crud->dataview($newquery);
Can you please tell me that this error mean?
Thank you.
Interesting article. I really enjoyed reading entire page content. PDO is very better in use in PHP. The article is so clear to understand crud. http://www.phptutorials.club
ReplyDeletesir / ma'am
ReplyDeletecan i use this for my project?
is there anything i need so i can able to use this for free?
sir gud day,
ReplyDeletei like ur tutorial
if ok sir, i u want to use this for my projct?
is there anything i need to be able to use this for free?
Hi Bon...
Deleteglad you liked it, you can use it freely ... :)
How to have user also as a class
ReplyDeleteHow to have User also as one class
ReplyDeleteHi Pradeep...Thank You very much for all your perfectly tested examples. These are very useful and the way you explained these is great.
ReplyDeleteI am new to php and using your CRUD example. i am just trying to update record of another table based on the id displayed by this example but it is throwing error..."[SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens]".
Actually i have two table one is "tbl_users" table and other is "two2" based on the id in "tbl_users" table i have to update the "two2" table data. I am just trying to fit your example for this.
Any help please....
The code is like this...
.............
//update tran table
public function update2($id,$ref,$name,$amount,$remarks,$date,$remark2,$int1,$int2,$date2)
{
try
{
$stmt=$this->db->prepare("UPDATE two2 SET ref=:id,
name=:name,amount=:amount,remarks=:remarks,date=date,remark2=remark2,int1=int1,
int2=int2,date2=date2 WHERE ref=:id ");
$stmt->bindparam(":ref",$id);
$stmt->bindparam(":name",$name);
$stmt->bindparam(":amount",$amount);
$stmt->bindparam(":remarks",$remarks);
$stmt->bindparam(":date",$date);
$stmt->bindparam(":remark2",$remark2);
$stmt->bindparam(":int1",$int1);
$stmt->bindparam(":int2",$int2);
$stmt->bindparam(":date2",$date2);
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
....................-----------------------
edit-data.php
.....
include_once 'dbconfig.php';
if(isset($_POST['btn-update']))
{
//$id = $_GET['id'];
$id = $_GET['edit_id'];
$ref = $_POST['ref'];
$name = $_POST['name'];
$amount = $_POST['amount'];
$remarks = $_POST['remarks'];
$date = $_POST['date'];
$remark2 = $_POST['remark2'];
$int1 = $_POST['int1'];
$int2 = $_POST['int2'];
$date2 = $_POST['date2'];
if($crud->update2($id,$ref,$name,$amount,$remarks,$date,$remark2,$int1,$int2,$date2))
{
good thanks for this excellent tutorial, as you would to add a search field in the index
ReplyDeleteHi pradeep, i have done it. thanks
ReplyDeletecould you please help how to use drop down box in this example to filter records(index.php)
ReplyDeleteHi,
ReplyDeleteHow would i use this multiple times on 1 page? For example i would like to extract data from the database and display the data based on different queries in 3 tables in a single php page. Im guessing it would involve adding to the class file as i've tried changing the variable names to $query2, $crud2 etc for the second table but nothing is displayed.
Thank you.
ReplyDeleteI gathered much needed info.
Great tutorial!
Can we use the GetId method to show an individual record in non-edit mode?
ReplyDelete"public function getID($id)"
Do you have an example like this but accessing a MSAccess Database using PDO?
ReplyDeleteSo long as you have the database in the structure shown and the PDO connector for MSAccess, if there is one, you should be good to go. That's the beauty of PDO; change the database and connector; the rest stays the same. Access previously used MickeySoft connectors RDO and ADO...much similar.
DeleteAmazed to hear someone still using Access.
Thanks, Khodke! :D
ReplyDeleteoh wow!! thanks a lot :)
ReplyDeleteGracias amigo, saludos..
ReplyDeletei have found such a great material from your blog,
ReplyDeleteThanks for sharing with us,.
image uploader
Sir how about search engine attached in tables. Can give us samples. im using pdo extension with php 7.. thank you..
ReplyDeleteHi, thanks lot for your job. I have make a generator crud pdo for based this tuto. your can tested here : http://generator-crud-pdo.890m.com/
ReplyDeletesee you all !
Hi Le,
Deletethanks for the crud generator, you did a great job...
New generator URL (officiel) crud.fr
ReplyDeletehow if I use dbconfig.php like this?
ReplyDeleteconn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
Hi there if i have many tables how can i use the crud class?
ReplyDeleteI need to have a class configured to each form?
Many thanks! Great you save me a lot of work and time to learn.
ReplyDeleteCan you inform me if we can create a list a values for a filed, based on DB table records?
For example I would like to have a
-field Menu, which take values from table t_Menu
- user selects a value and moves to the next field SubMenu
- now the values on the list that will appear, must be filtered based on the value selected from Menu field
Thanks
Many thanks! Great you save me a lot of work and time to learn.
ReplyDeleteCan you inform me if we can create a list a values for a filed, based on DB table records?
For example I would like to have a
-field Menu, which take values from table t_Menu
- user selects a value and moves to the next field SubMenu
- now the values on the list that will appear, must be filtered based on the value selected from Menu field
Thanks
Hi everyone,
ReplyDeleteMany thanks for your tutorial, PRADEEP KHODKE!
When I run this project I saw the following message:
Fatal error: Cannot declare class crud, because the name is already in use in ..../class.crud.php on line 3 which is:
class crud
Is necessary to reset a CRUD object which have been previously created?
Thanks in advance. Best regards.
Dear sir,
ReplyDelete"id" field not want to auto. how to update "id" field
Really nice examples. Thank you very much. However, to print out the table
ReplyDeleteI would rather loop through the keys of the $row array. (My database contains
more fields). I am not very familiar with OOP, so bear with me for a stupid question: in OOP PHP, do I write a loop like
(I removed < and > from the code because the tag is not allowed.)
as in the good old php, or would there be a better way?
Congratulations for this great tutorial i'm happy to bump into it.
ReplyDeleteI created an new table by following the code process to add new data, unfortunately i have this message in this code part in add-data.php file :
ERROR while inserting record !
db->errorInfo()))
so that i can display and see what the error is about?
thanks
Again i'm back to this nice tuto, i try to add die(print_r($DB_con->errorInfo(), true)); in add-data.php file after ERROR while inserting record !. As result i get this message :
ReplyDeleteArray ( [0] => 00000 [1] => [2] => )
How to display the error information so that i can debbug ?
Hi Bro Pradep, thank you very much for sharing this great tutorial! :D
ReplyDeleteit's clear explained and easy to follow. Keep posting something great like this.
Oh yea, do you have some good references tutorial for create REST API data exchange from PHP to JSON for Ionic ?
Best regards
Great tutorial my friend... thank you very much!! One little question, how do you handle this using a Login form to prevent the use for a non registered users? hope that you can make an example on this :)
ReplyDeleteHey KIEV, it's simple, just make crud pages with session so that only logged in users can access it, BTW thanks for the suggestion i'll post tutorial on it very soon :)
Deletekeep visiting ....