Sunteți pe pagina 1din 9

Upload,Insert,Update,DeleteanImageusingPHP

MySQL
On2/06/2016ByPradeepKhodke

Hellofriends,afteralongtimeiamgoingtopostasimpletutorialyetusefulinyourwebapplicationor
project,SimpleInsert,Select,UpdateandDelete(CRUD)withImageusingPDOQuery.anImagewillbe
Uploaded,Inserted,UpdatedandDeletedaswellwithMySQL.wealreadyhaveaCRUDTutorialsbuti
haven'tcoveredthis,thistutorialiscoveredwithproperimagevalidation,letsayonlyvalidimageextensions
areallowedtouploadandimagesizeisalsomatters.Solet'seeimageuploadinphp.

Database/Table
"testdb"nameddatabaseisusedinthistutorial,socreateitandpastethefollowingsqlcodeinyour
phpmyadminitwillcreateuserstable"tbl_users".

CREATETABLEIFNOTEXISTS`tbl_users`(
`userID`int(11)NOTNULLAUTO_INCREMENT,
`userName`varchar(20)NOTNULL,
`userProfession`varchar(50)NOTNULL,
`userPic`varchar(200)NOTNULL,
PRIMARYKEY(`userID`)
)ENGINE=MyISAMDEFAULTCHARSET=latin1AUTO_INCREMENT=51;

nowwehavetocreateonly4filesphpfileswhichwillhandleourcrudoperationswithanimageandtheyare
asfollow.

Dbconfig.Php
simplehost/databaseconfigurationfilecreatedwithPDOQuery/Extension.changethecredentialsasper
yourconfiguration.

<?php

$DB_HOST='localhost';
$DB_USER='root';
$DB_PASS='';
$DB_NAME='testdb';

try{
$DB_con=newPDO("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();
}

Addnew.Php
SimpleHTMLformcreatedwithbootstrap,thefieldsihavetakenhereforuserisusername,userjob,and
userimage,youcanalsoaddmorefields.

<formmethod="post"enctype="multipart/formdata"class="formhorizontal">

<tableclass="tabletableborderedtableresponsive">

<tr>
<td><labelclass="controllabel">Username.</label></td>
<td><inputclass="formcontrol"type="text"name="user_name"placeholder="EnterUsername"value="<?phpecho
$username;?>"/></td>
</tr>

<tr>
<td><labelclass="controllabel">Profession(Job).</label></td>
<td><inputclass="formcontrol"type="text"name="user_job"placeholder="YourProfession"value="<?phpecho
$userjob;?>"/></td>
</tr>

<tr>
<td><labelclass="controllabel">ProfileImg.</label></td>
<td><inputclass="inputgroup"type="file"name="user_image"accept="image/*"/></td>
</tr>

<tr>
<tdcolspan="2"><buttontype="submit"name="btnsave"class="btnbtndefault">
<spanclass="glyphiconglyphiconsave"></span>&nbsp;save
</button>
</td>
</tr>

</table>

</form>

TheAboveFormWillLookLike:

asitoldthat,ihaveusedherbootstrapforthistutorialsoactualfilecodelookslengthy,that'swhyihave
puttedhereonlyimportantandmaincode,thedesigningcodeisavoided.nowletcometothenextpoint.

PHPCode:
putthefollowingphpcodejustabovestarting<!DOCTYPEhtml>tag.inthisscriptanimageanduserdetails
willbeinserted,properimagevalidationisthereorifanyerroroccuredanappropriatemessagewillbe
displayedwithbootstrapdesign.

<?php
error_reporting(~E_NOTICE);//avoidnotice
require_once'dbconfig.php';

if(isset($_POST['btnsave']))
{
$username=$_POST['user_name'];//username
$userjob=$_POST['user_job'];//useremail

$imgFile=$_FILES['user_image']['name'];
$tmp_dir=$_FILES['user_image']['tmp_name'];
$imgSize=$_FILES['user_image']['size'];

if(empty($username)){
$errMSG="PleaseEnterUsername.";
}
elseif(empty($userjob)){
$errMSG="PleaseEnterYourJobWork.";

}
elseif(empty($imgFile)){
$errMSG="PleaseSelectImageFile.";
}
else
{
$upload_dir='user_images/';//uploaddirectory

$imgExt=strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));//getimageextension

//validimageextensions
$valid_extensions=array('jpeg','jpg','png','gif');//validextensions

//renameuploadingimage
$userpic=rand(1000,1000000).".".$imgExt;

//allowvalidimagefileformats
if(in_array($imgExt,$valid_extensions)){
//Checkfilesize'5MB'
if($imgSize<5000000){
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else{
$errMSG="Sorry,yourfileistoolarge.";
}
}
else{
$errMSG="Sorry,onlyJPG,JPEG,PNG&GIFfilesareallowed.";
}
}

//ifnoerroroccured,continue....
if(!isset($errMSG))
{
$stmt=$DB_con>prepare('INSERTINTOtbl_users(userName,userProfession,userPic)VALUES(:uname,:ujob,:upic)');
$stmt>bindParam(':uname',$username);
$stmt>bindParam(':ujob',$userjob);
$stmt>bindParam(':upic',$userpic);

if($stmt>execute())
{
$successMSG="newrecordsuccesfullyinserted...";
header("refresh:5;index.php");//redirectsimageviewpageafter5seconds.
}
else
{
$errMSG="errorwhileinserting....";
}
}
}
?>

Editform.Php
editingformissimplelikeaninsertformis,thecompletecodeisgiveninthedownloadablefile.whileediting
arecordwehavetofetchselectedrecordfromdatabase,ifimageisselectedtoeditthenoldimagewillbe
deletedandnewimagewillbeuploaded,hereistheonlyPHPscript.

<?php
error_reporting(~E_NOTICE);
require_once'dbconfig.php';

if(isset($_GET['edit_id'])&&!empty($_GET['edit_id']))
{
$id=$_GET['edit_id'];
$stmt_edit=$DB_con>prepare('SELECTuserName,userProfession,userPicFROMtbl_usersWHEREuserID=:uid');
$stmt_edit>execute(array(':uid'=>$id));
$edit_row=$stmt_edit>fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location:index.php");
}

if(isset($_POST['btn_save_updates']))
{
$username=$_POST['user_name'];//username
$userjob=$_POST['user_job'];//useremail

$imgFile=$_FILES['user_image']['name'];
$tmp_dir=$_FILES['user_image']['tmp_name'];
$imgSize=$_FILES['user_image']['size'];

if($imgFile)
{
$upload_dir='user_images/';//uploaddirectory
$imgExt=strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));//getimageextension
$valid_extensions=array('jpeg','jpg','png','gif');//validextensions
$userpic=rand(1000,1000000).".".$imgExt;
if(in_array($imgExt,$valid_extensions))
{
if($imgSize<5000000)
{
unlink($upload_dir.$edit_row['userPic']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
$errMSG="Sorry,yourfileistoolargeitshouldbelessthen5MB";
}
}
else
{
$errMSG="Sorry,onlyJPG,JPEG,PNG&GIFfilesareallowed.";

}
}
else
{
//ifnoimageselectedtheoldimageremainasitis.
$userpic=$edit_row['userPic'];//oldimagefromdatabase
}

//ifnoerroroccured,continue....
if(!isset($errMSG))
{
$stmt=$DB_con>prepare('UPDATEtbl_users
SETuserName=:uname,
userProfession=:ujob,
userPic=:upic
WHEREuserID=:uid');
$stmt>bindParam(':uname',$username);
$stmt>bindParam(':ujob',$userjob);
$stmt>bindParam(':upic',$userpic);
$stmt>bindParam(':uid',$id);

if($stmt>execute()){
?>
<script>
alert('SuccessfullyUpdated...');
window.location.href='index.php';
</script>
<?php
}
else{
$errMSG="SorryDataCouldNotUpdated!";
}
}
}
?>

UpdatingFormWillLookLike:

nowthenextstepisrecorddisplayingalongwithimage,wellusingbootstrapiteasytocreateanimage
gallerylet'shavealookatthescript.

Index.Php
withindivtagclass="row"animagegallerythumbnailwillbegeneratedfromuserstable.

<divclass="row">
<?php

$stmt=$DB_con>prepare('SELECTuserID,userName,userProfession,userPicFROMtbl_usersORDERBYuserIDDESC');
$stmt>execute();

if($stmt>rowCount()>0)
{
while($row=$stmt>fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<divclass="colxs3">
<pclass="pageheader"><?phpecho$userName."&nbsp;/&nbsp;".$userProfession;?></p>
<imgsrc="user_images/<?phpecho$row['userPic'];?>"class="imgrounded"width="250px"height="250px"/>
<pclass="pageheader">
<span>
<aclass="btnbtninfo"href="editform.php?edit_id=<?phpecho$row['userID'];?>"title="clickforedit"onclick="return
confirm('suretoedit?')"><spanclass="glyphiconglyphiconedit"></span>Edit</a>
<aclass="btnbtndanger"href="?delete_id=<?phpecho$row['userID'];?>"title="clickfordelete"onclick="return
confirm('suretodelete?')"><spanclass="glyphiconglyphiconremovecircle"></span>Delete</a>

</span>
</p>
</div>
<?php
}
}
else
{
?>
<divclass="colxs12">
<divclass="alertalertwarning">
<spanclass="glyphiconglyphiconinfosign"></span>&nbsp;NoDataFound...
</div>
</div>
<?php
}

?>
</div>

GalleryWillLookLike:

DeletingRecordWithImage
NowPutthefollowingcodejustabove<html>tagwithin"index.php"oryoucancreatenewpagetodelete
recordlike"delete.php"justhyperlinkthepagenamealongwithrecordid

if(isset($_GET['delete_id']))
{
//selectimagefromdbtodelete
$stmt_select=$DB_con>prepare('SELECTuserPicFROMtbl_usersWHEREuserID=:uid');
$stmt_select>execute(array(':uid'=>$_GET['delete_id']));
$imgRow=$stmt_select>fetch(PDO::FETCH_ASSOC);
unlink("user_images/".$imgRow['userPic']);

//itwilldeleteanactualrecordfromdb
$stmt_delete=$DB_con>prepare('DELETEFROMtbl_usersWHEREuserID=:uid');
$stmt_delete>bindParam(':uid',$_GET['delete_id']);
$stmt_delete>execute();

header("Location:index.php");

that'sit,hereyoucandownloadthiscompletecodeandtryinyourlocalhostserver,thiswasjustfor
beginners(beginnerlevel)hencewecanalsocreatefileuploadingclasstoavoidreuseoffileuploadingand
wecanalsouseObjectOrientedwaytoachievethesame,hopeyoulikeit.pleasedoshare.

S-ar putea să vă placă și