บทที่ x10 Upload File to MySQL

PHP Upload File to MySQL

ตัวอย่างการอัพโหลดไฟล์ด้วย PHP เข้าสู่ฐานข้อมูล MySQL โดยสามารถสร้าง CreateElement หรือ Delete Element ไม่จำกัดจำนวนช่อง

ตัวอย่างการอ่านจาก Element โดยตรง

php_multiple_upload1.php

<html><head><title></title></head>
<body>
<form action="php_multiple_upload2.php" method="post" name="form1" enctype="multipart/form-data">
<input type="text" name="txtGalleryName1"><input type="file" name="fileUpload1"><br>
<input type="text" name="txtGalleryName2"><input type="file" name="fileUpload2"><br>
<input type="text" name="txtGalleryName3"><input type="file" name="fileUpload3"><br>
<input type="text" name="txtGalleryName4"><input type="file" name="fileUpload4"><br>
<input name="hdnLine" type="hidden" value="4">
<input name="btnSubmit" type="submit" value="Submit">
</form>
</body></html>

 


php_multiple_upload2.php

<html><head><title></title></head>
<body>
<?
mysql_connect("localhost","root","root") or die (mysql_error());
mysql_select_db("mydatabase");
for($i=1;$i<=(int)($_POST["hdnLine"]);$i++)
{ if($_FILES["fileUpload".$i]["name"] != "")
{
if(move_uploaded_file($_FILES["fileUpload".$i]["tmp_name"],"thaicreate/".$_FILES["fileUpload".$i]["name"]))
{ $strSQL = "INSERT INTO gallery ";
$strSQL .="(GalleryName,Picture) VALUES ('".$_POST["txtGalleryName".$i]."','".$_FILES["fileUpload".$i]["name"]."')";
mysql_query($strSQL);
echo "Copy/Upload ".$_FILES["fileUpload".$i]["name"]." completed.<br>";
}}}
echo "<br><a href='php_multiple_upload3.php'>View file</a>";
mysql_close();
?>
</body></html>

 


php_multiple_upload3.php

<html><head><title></title></head>
<body>
<?
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM gallery";
$objQuery = mysql_query($strSQL);
echo"<table border=\"0\"  cellspacing=\"1\" cellpadding=\"1\"><tr>";
$intRows = 0;
while($objResult = mysql_fetch_array($objQuery))
{ echo "<td>";
$intRows++;
?>
<center>
<img src="thaicreate/<?=$objResult["Picture"];?>"><br>
<?=$objResult["GalleryName"];?>
<br>
</center>
<? echo"</td>";
if(($intRows)%2==0)
{echo"</tr>";
}}
echo"</tr></table>";
?>
</body></html>
<? mysql_close(); ?>