در این آموزش ، ما یاد خواهیم گرفت که چگونه با استفاده از PHP و MySQLi عملکرد CRDU را با تصویر ایجاد کنیم.

Files در این آموزشها گنجانده شده است

  • phpcrud.sql: حاوی ساختار جدول پایگاه داده.
  • dbconnection.php: برای اتصال به پایگاه داده استفاده می شود.
  • index.php: برای واکشی رکورد از پایگاه داده استفاده می شود.
  • insert.php: برای درج رکورد جدید استفاده می شود.
  • read.php: برای واکشی رکورد کاربر خاص استفاده می شود.
  • edit.php: برای ویرایش رکورد استفاده می شود.
  • change-image.php: برای تغییر عکس نمایه استفاده می شود.

مرحله 1– یک پایگاه داده ایجاد کنید

نوع مرورگر را باز کنید http://localhost/phpmyadmin، یک پایگاه داده با نام ‘phpcrud’ ایجاد کنید. پس از ایجاد پایگاه داده ، اسکریپت SQL را اجرا کنید یا فایل SQL را وارد کنید.

جدول MySQL tblusers ساختار

CREATE TABLE `tblusers` (
  `ID` int(10) NOT NULL,
  `FirstName` varchar(200) DEFAULT NULL,
  `LastName` varchar(200) DEFAULT NULL,
  `MobileNumber` bigint(10) DEFAULT NULL,
  `Email` varchar(200) DEFAULT NULL,
  `Address` mediumtext DEFAULT NULL,
  `ProfilePic` varchar(200) DEFAULT NULL,
  `CreationDate` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

مرحله 2 – ایجاد یک فایل اتصال پایگاه داده (dbconnection.php)

<?php
$con=mysqli_connect("localhost", "root", "", "phpcrud");
if(mysqli_connect_errno())
{
echo "Connection Fail".mysqli_connect_error();
}
?>

مرحله 3– یک فرم HTML برای درج داده ایجاد کنید. (insert.php)

<form  method="POST" enctype="multipart/form-data" >
<h2>Fill Data</h2>
<p class="hint-text">Fill below form.</p>

<div class="form-group">
<div class="row">
<div class="col"><input type="text" class="form-control" name="fname" placeholder="First Name" required="true"></div>
<div class="col"><input type="text" class="form-control" name="lname" placeholder="Last Name" required="true"></div>
</div>        	
</div>

<div class="form-group">
 <input type="text" class="form-control" name="contactno" placeholder="Enter your Mobile Number" required="true" maxlength="10" pattern="[0-9]+">
 </div>
        
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Enter your Email id" required="true">
</div>
		
<div class="form-group">
<textarea class="form-control" name="address" placeholder="Enter Your Address" required="true"></textarea>
</div>  

<div class="form-group">
<input type="file" class="form-control" name="profilepic"  required="true">
<span style="color:red; font-size:12px;">Only jpg / jpeg/ png /gif format allowed.</span>
</div>      
      
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg btn-block" name="submit">Submit</button>
</div>
</form>

مرحله 4– اکنون کد PHP را برای درج داده بنویسید و این کد را در بالای پرونده insert.php قرار دهید.

<?php 
//Databse Connection file
include('dbconnection.php');
if(isset($_POST['submit']))
  {
  	//getting the post values
    $fname=$_POST['fname'];
    $lname=$_POST['lname'];
    $contno=$_POST['contactno'];
    $email=$_POST['email'];
    $add=$_POST['address'];
   $ppic=$_FILES["profilepic"]["name"];
// get the image extension
$extension = substr($ppic,strlen($ppic)-4,strlen($ppic));
// allowed extensions
$allowed_extensions = array(".jpg","jpeg",".png",".gif");
// Validation for allowed extensions .in_array() function searches an array for a specific value.
if(!in_array($extension,$allowed_extensions))
{
echo "<script>alert('Invalid format. Only jpg / jpeg/ png /gif format allowed');</script>";
}
else
{
//rename the image file
$imgnewfile=md5($imgfile).time().$extension;
// Code for move image into directory
move_uploaded_file($_FILES["profilepic"]["tmp_name"],"profilepics/".$imgnewfile);
// Query for data insertion
$query=mysqli_query($con, "insert into tblusers(FirstName,LastName, MobileNumber, Email, Address,ProfilePic) value('$fname','$lname', '$contno', '$email', '$add','$imgnewfile' )");
if ($query) {
echo "<script>alert('You have successfully inserted the data');</script>";
echo "<script > document.location ="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/index.php"; </script>";
} else{
echo "<script>alert('Something Went Wrong. Please try again');</script>";
}}
}
?>

مرحله 5– رکورد را از پایگاه داده بخوانید / واکشی کنید (index.php)

در این مرحله ما تمام داده های پایگاه داده از جمله تصویر را می خوانیم / واکشی می کنیم.

 <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Profile Pic</th>
                        <th>Name</th>                       
                        <th>Email</th>
                        <th>Mobile Number</th>
                        <th>Created Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                     <?php
$ret=mysqli_query($con,"select * from tblusers");
$cnt=1;
$row=mysqli_num_rows($ret);
if($row>0){
while ($row=mysqli_fetch_array($ret)) {

?>
<!--Fetch the Records -->
<tr>
<td><?php echo $cnt;?></td>
<td><img src="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/profilepics/<?php  echo $row["ProfilePic'];?>" width="80" height="80"></td>
<td><?php  echo $row['FirstName'];?> <?php  echo $row['LastName'];?></td>
<td><?php  echo $row['Email'];?></td>                        
 <td><?php  echo $row['MobileNumber'];?></td>
<td> <?php  echo $row['CreationDate'];?></td>
<td>
<a href="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/read.php?viewid=<?php echo htmlentities ($row["ID']);?>" class="view" title="View" data-toggle="tooltip"><i class="material-icons">&#xE417;</i></a>
<a href="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/edit.php?editid=<?php echo htmlentities ($row["ID']);?>" class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
<a href="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/index.php?delid=<?php echo ($row["ID']);?>&&ppic=<?php echo $row['ProfilePic'];?>" class="delete" title="Delete" data-toggle="tooltip" onclick="return confirm('Do you really want to Delete ?');"><i class="material-icons">&#xE872;</i></a>
</td>
</tr>
<?php 
$cnt=$cnt+1;
} } else {?>
<tr>
<th style="text-align:center; color:red;" colspan="6">No Record Found</th>
</tr>
<?php } ?>                 
                
</tbody>
</table>

مرحله 6 – خواندن / واکشی رکورد خاص (read.php)

فایل read.php ایجاد کنید. برای واکشی رکورد باید شناسه ردیف آن رکورد را بدست آوریم و در آن ذخیره کنیم $vid. ما به $_GET[‘viewid’] متغیر برای انجام آن.
کد برای یک رکورد بر اساس شناسه داده شده دریافت می کند.

  <div class="table-title">
                <div class="row">
                    <div class="col-sm-5">
                        <h2>User <b>Details</b></h2>
                    </div>
<?php
$vid=$_GET['viewid'];
$ret=mysqli_query($con,"select * from tblusers where ID =$vid");
$cnt=1;
while ($row=mysqli_fetch_array($ret)) {

?>

<div class="col-sm-7" align="right">
<a href="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/edit.php?editid=<?php echo htmlentities ($row["ID']);?>" class="btn btn-primary"><span>Edit User Details</span></a>
</div>
</div>
</div>

<table cellpadding="0" cellspacing="0" border="0" class="display table table-bordered" id="hidden-table-info">
               
<tbody>
<tr>
<th width="200">Profile Pic</th>
<td><img src="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/profilepics/<?php  echo $row["ProfilePic'];?>" width="80" height="80"></td>
<th width="200">Creation Date</th>
<td><?php  echo $row['CreationDate'];?></td>
</tr>

 <tr>
    <th>First Name</th>
    <td><?php  echo $row['FirstName'];?></td>
    <th>Last Name</th>
    <td><?php  echo $row['LastName'];?></td>
  </tr>
  <tr>
    <th>Email</th>
    <td><?php  echo $row['Email'];?></td>
    <th>Mobile Number</th>
    <td><?php  echo $row['MobileNumber'];?></td>
  </tr>
  <tr>
    <th>Address</th>
    <td><?php  echo $row['Address'];?></td>
 
  </tr>
<?php 
$cnt=$cnt+1;
}?>
                 
</tbody>
</table>

مرحله 7 – ویرایش / به روزرسانی رکورد خاص (edit.php)

مرحله 7.1 داده ها را در فرم HTML دریافت کنید.

فایل edit.php ایجاد کنید. برای به روزرسانی یک رکورد باید شناسه ردیف آن رکورد را دریافت کرده و در آن ذخیره کنیم $eid. ما به $_GET[‘editid’] متغیر برای انجام آن.
کد برای یک رکورد بر اساس شناسه داده شده دریافت می کند. به این ترتیب ، می توانیم داده های تکمیل خودکار داده ها را در فرم HTML دریافت کنیم.

    <form  method="POST">
 <?php
$eid=$_GET['editid'];
$ret=mysqli_query($con,"select * from tblusers where ID='$eid'");
while ($row=mysqli_fetch_array($ret)) {
?>

<h2>Update </h2>
<p class="hint-text">Update your info.</p>

<div class="form-group">
<img src="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/profilepics/<?php  echo $row["ProfilePic'];?>" width="120" height="120">
<a href="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/change-image.php?userid=<?php echo $row["ID'];?>">Change Image</a>
</div>

<div class="form-group">
<div class="row">
<div class="col"><input type="text" class="form-control" name="fname" value="<?php  echo $row['FirstName'];?>" required="true"></div>

<div class="col"><input type="text" class="form-control" name="lname" value="<?php  echo $row['LastName'];?>" required="true"></div>
</div>        	
</div>

<div class="form-group">
<input type="text" class="form-control" name="contactno" value="<?php  echo $row['MobileNumber'];?>" required="true" maxlength="10" pattern="[0-9]+">
</div>
        
<div class="form-group">
<input type="email" class="form-control" name="email" value="<?php  echo $row['Email'];?>" required="true">
</div>
		
<div class="form-group">
<textarea class="form-control" name="address" required="true"><?php  echo $row['Address'];?></textarea>
</div>   

<?php 
}?>

<div class="form-group">
 <button type="submit" class="btn btn-success btn-lg btn-block" name="submit">Update</button>
        </div>
    </form>

مرحله 7.1 کد را برای به روزرسانی رکورد خاص وارد کنید. این کد را در بالای edit.php قرار دهید

<?php 
//Database Connection
include('dbconnection.php');
if(isset($_POST['submit']))
  {
  $eid=$_GET['editid'];
  //Getting Post Values
    $fname=$_POST['fname'];
    $lname=$_POST['lname'];
    $contno=$_POST['contactno'];
    $email=$_POST['email'];
    $add=$_POST['address'];

//Query for data updation
$query=mysqli_query($con, "update  tblusers set FirstName="$fname",LastName="$lname", MobileNumber="$contno", Email="$email", Address="$add" where ID='$eid'");

if ($query) {
echo "<script>alert('You have successfully update the data');</script>";
echo "<script > document.location ="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/index.php"; </script>";
}
else
{
echo "<script>alert('Something Went Wrong. Please try again');</script>";
}
}
?>

مرحله 7.3 یک صفحه برای به روزرسانی تصویر ایجاد کنید. (change-image.php)

فایل change-image.php را ایجاد کنید. برای به روزرسانی عکس نمایه ، باید شناسه ردیف آن رکورد را دریافت کرده و در آن ذخیره کنیم $eid. ما به $_GET['userid'] متغیر برای انجام آن.

<form  method="POST" enctype="multipart/form-data">
<?php
$eid=$_GET['userid'];
$ret=mysqli_query($con,"select * from tblusers where ID='$eid'");
while ($row=mysqli_fetch_array($ret)) {
?>

<h2>Update </h2>
<p class="hint-text">Update your profile pic.</p>
<input type="hidden" name="oldpic" value="<?php  echo $row['ProfilePic'];?>">
<div class="form-group">
<img src="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/profilepics/<?php  echo $row["ProfilePic'];?>" width="120" height="120">
</div>

<div class="form-group">
<input type="file" class="form-control" name="profilepic"  required="true">
<span style="color:red; font-size:12px;">Only jpg / jpeg/ png /gif format allowed.</span>
</div> 

<div class="form-group">
<button type="submit" class="btn btn-success btn-lg btn-block" name="submit">Update</button>
</div>
<?php }?>
</form>

مرحله 7.4 برای به روزرسانی عکس مشخصات کاربر خاص کد را وارد کنید. این کد را در بالای change-image.php قرار دهید

<?php 
//Database Connection
include('dbconnection.php');
if(isset($_POST['submit']))
  {
$uid=$_GET['userid'];
//getting the post values
 $ppic=$_FILES["profilepic"]["name"];
$oldppic=$_POST['oldpic'];
$oldprofilepic="profilepics"."/".$oldppic;
// get the image extension
$extension = substr($ppic,strlen($ppic)-4,strlen($ppic));
// allowed extensions
$allowed_extensions = array(".jpg","jpeg",".png",".gif");
// Validation for allowed extensions .in_array() function searches an array for a specific value.
if(!in_array($extension,$allowed_extensions))
{
echo "<script>alert('Invalid format. Only jpg / jpeg/ png /gif format allowed');</script>";
}else{
//rename the image file
$imgnewfile=md5($imgfile).time().$extension;
// Code for move image into directory
move_uploaded_file($_FILES["profilepic"]["tmp_name"],"profilepics/".$imgnewfile);
// Query for data insertion
$query=mysqli_query($con, "update tblusers set ProfilePic="$imgnewfile" where id='$uid' ");
if ($query) {
//Old pic deletion
unlink($oldprofilepic);
echo "<script>alert('Profile pic updated successfully');</script>";
echo "<script > document.location ="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/index.php"; </script>";
}else{
echo "<script>alert('Something Went Wrong. Please try again');</script>";
 }
}
}
?>

مرحله 8 – کد حذف داده ها یک رکورد از پایگاه داده را کد کنید

<?php
//database conection  file
include('dbconnection.php');
//Code for deletion
if(isset($_GET['delid']))
{
$rid=intval($_GET['delid']);
$profilepic=$_GET['ppic'];
$ppicpath="profilepics"."/".$profilepic;
$sql=mysqli_query($con,"delete from tblusers where ID=$rid");
unlink($ppicpath);
echo "<script>alert('Data deleted');</script>"; 
echo "<script>window.location.href="https://phpgurukul.com/crud-operation-with-image-using-php-and-mysqli/index.php"</script>";     
} 
?>

بارگیری کد منبع (php-mysqli-crud-with-image)

اندازه: 201 کیلوبایت

نسخه: V 1.0