Você está na página 1de 11

Upload,Insert,Update,DeleteImageinPHPMySQL

Addnew.php
<?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....";

}
?>
<!DOCTYPEhtmlPUBLIC"//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1
transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttpequiv="ContentType"content="text/html;charset=utf8"/>
<title>Upload,Insert,Update,DeleteanImageusingPHPMySQLCodingCage</title>

<linkrel="stylesheet"href="bootstrap/css/bootstrap.min.css">

<!Optionaltheme>
<linkrel="stylesheet"href="bootstrap/css/bootstraptheme.min.css">

</head>
<body>

<divclass="navbarnavbardefaultnavbarstatictop"role="navigation">
<divclass="container">

<divclass="navbarheader">
<aclass="navbarbrand"href="http://www.codingcage.com"title='ProgrammingBlog'>CodingCage</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/CRUD">CRUD</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/PDO">PDO</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/jQuery">jQuery</a>
</div>

</div>
</div>

<divclass="container">

<divclass="pageheader">

<h1class="h2">addnewuser.<aclass="btnbtndefault"href="index.php"><spanclass="glyphiconglyphiconeye
open"></span>&nbsp;viewall</a></h1>
</div>


<?php

if(isset($errMSG)){

?>
<divclass="alertalertdanger">
<spanclass="glyphiconglyphiconinfosign"></span><strong><?phpecho$errMSG;?></strong>
</div>
<?php

elseif(isset($successMSG)){

?>
<divclass="alertalertsuccess">
<strong><spanclass="glyphiconglyphiconinfosign"></span><?phpecho$successMSG;?></strong>
</div>
<?php

?>

<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>

<divclass="alertalertinfo">
<strong>tutoriallink!</strong><ahref="http://www.codingcage.com/2016/02/uploadinsertupdatedeleteimage
using.html">CodingCage</a>!
</div>

</div>

<!LatestcompiledandminifiedJavaScript>
<scriptsrc="bootstrap/js/bootstrap.min.js"></script>

</body>
</html>

Dbconfig.php
<?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();
}

Editform.php
<?php

=:uid');

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

$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!";

?>
<!DOCTYPEhtmlPUBLIC"//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1
transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttpequiv="ContentType"content="text/html;charset=utf8"/>
<title>Upload,Insert,Update,DeleteanImageusingPHPMySQLCodingCage</title>

<linkrel="stylesheet"href="bootstrap/css/bootstrap.min.css">

<!Optionaltheme>
<linkrel="stylesheet"href="bootstrap/css/bootstraptheme.min.css">

<!customstylesheet>
<linkrel="stylesheet"href="style.css">

<!LatestcompiledandminifiedJavaScript>
<scriptsrc="bootstrap/js/bootstrap.min.js"></script>

<scriptsrc="jquery1.11.3jquery.min.js"></script>
</head>
<body>

<divclass="navbarnavbardefaultnavbarstatictop"role="navigation">
<divclass="container">

<divclass="navbarheader">
<aclass="navbarbrand"href="http://www.codingcage.com"title='ProgrammingBlog'>CodingCage</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/CRUD">CRUD</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/PDO">PDO</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/jQuery">jQuery</a>
</div>

</div>
</div>

<divclass="container">

<divclass="pageheader">

<h1class="h2">updateprofile.<aclass="btnbtndefault"href="index.php">allmembers</a></h1>
</div>

<divclass="clearfix"></div>

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

<?php

if(isset($errMSG)){

?>
<divclass="alertalertdanger">
<spanclass="glyphiconglyphiconinfosign"></span>&nbsp;<?phpecho$errMSG;?>
</div>
<?php

?>

<tableclass="tabletableborderedtableresponsive">

<tr>

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

<tr>

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

<tr>

<td><labelclass="controllabel">ProfileImg.</label></td>
<td>

<p><imgsrc="user_images/<?phpecho$userPic;?>"height="150"width="150"/></p>

<inputclass="inputgroup"type="file"name="user_image"accept="image/*"/>
</td>
</tr>

<tr>
<tdcolspan="2"><buttontype="submit"name="btn_save_updates"class="btnbtndefault">
<spanclass="glyphiconglyphiconsave"></span>Update
</button>

<aclass="btnbtndefault"href="index.php"><spanclass="glyphiconglyphiconbackward"></span>cancel</a>

</td>
</tr>

</table>

</form>

<divclass="alertalertinfo">

<strong>tutoriallink!</strong><ahref="http://www.codingcage.com/2016/02/uploadinsertupdatedeleteimage
using.html">CodingCage</a>!
</div>

</div>
</body>
</html>

Index.php
<?php

require_once'dbconfig.php';

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");

?>
<!DOCTYPEhtmlPUBLIC"//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1
transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttpequiv="ContentType"content="text/html;charset=utf8"/>
<metaname="viewport"content="width=devicewidth,initialscale=1,maximumscale=1,userscalable=no"/>
<title>Upload,Insert,Update,DeleteanImageusingPHPMySQLCodingCage</title>
<linkrel="stylesheet"href="bootstrap/css/bootstrap.min.css">
<linkrel="stylesheet"href="bootstrap/css/bootstraptheme.min.css">
</head>

<body>

<divclass="navbarnavbardefaultnavbarstatictop"role="navigation">
<divclass="container">

<divclass="navbarheader">
<aclass="navbarbrand"href="http://www.codingcage.com"title='ProgrammingBlog'>CodingCage</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/CRUD">CRUD</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/PDO">PDO</a>
<aclass="navbarbrand"href="http://www.codingcage.com/search/label/jQuery">jQuery</a>
</div>

</div>
</div>

<divclass="container">

<divclass="pageheader">

<h1class="h2">allmembers./<aclass="btnbtndefault"href="addnew.php"><spanclass="glyphiconglyphicon
plus"></span>&nbsp;addnew</a></h1>
</div>

<br/>

<divclass="row">
<?php

$stmt=$DB_con>prepare('SELECTuserID,userName,userProfession,userPicFROMtbl_usersORDERBYuserID
DESC');

$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="returnconfirm('suretoedit?')"><spanclass="glyphiconglyphiconedit"></span>Edit</a>

<aclass="btnbtndanger"href="?delete_id=<?phpecho$row['userID'];?>"title="click
fordelete"onclick="returnconfirm('suretodelete?')"><spanclass="glyphiconglyphiconremovecircle"></span>Delete</a>

</span>

</p>

</div>

<?php

else

?>
<divclass="colxs12">

<divclass="alertalertwarning">
<spanclass="glyphiconglyphiconinfosign"></span>&nbsp;NoDataFound...
</div>
</div>
<?php

?>
</div>

<divclass="alertalertinfo">
<strong>tutoriallink!</strong><ahref="http://www.codingcage.com/2016/02/uploadinsertupdatedeleteimage
using.html">CodingCage</a>!
</div>

</div>

<!LatestcompiledandminifiedJavaScript>
<scriptsrc="bootstrap/js/bootstrap.min.js"></script>

</body>
</html>

Testdb.sql
phpMyAdminSQLDump
version4.1.14
http://www.phpmyadmin.net

Host:127.0.0.1
GenerationTime:Feb05,2016at02:50PM
Serverversion:5.6.17
PHPVersion:5.5.12

SETSQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SETtime_zone="+00:00";

/*!40101SET@OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT*/;
/*!40101SET@OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS*/;
/*!40101SET@OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION*/;
/*!40101SETNAMESutf8*/;

Database:`testdb`

Tablestructurefortable`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;

10

Dumpingdatafortable`tbl_users`

INSERTINTO`tbl_users`(`userID`,`userName`,`userProfession`,`userPic`)VALUES
(42,'dwaynejohnson','actor,wrestler','380289.jpg'),
(43,'justinbieber','singer','995062.jpg'),
(44,'chrishemsworth','actor','171544.jpg'),
(41,'johncena','wrestler','549279.jpg');

/*!40101SETCHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT*/;
/*!40101SETCHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS*/;
/*!40101SETCOLLATION_CONNECTION=@OLD_COLLATION_CONNECTION*/;

11

Você também pode gostar