好吧我有一個困境。我希望能夠上傳最多六個圖像和兩個文本字段(標題和desc)到數據庫...實際上讓我糾正自己,我想存儲在圖像的名稱,所以我可以得到後來的照片。我知道如何將多個圖片上傳到一個文件夾,並且我知道如何將行插入到數據庫中,但是我無法弄清楚如何組合這兩者。如果將其與圖像工作結合起來,如果其中一個文件存在問題,將取消整個過程?上傳多個圖像到db與2個文本字段
my db setup is simply id |標題| desc | img1 | img2 | img3 | img4 | img5 | img6
我寫到目前爲止代碼:
if (isset($_POST['formsubmitted'])) { //if form was submitted
$error = array();//Declare An Array to store any error message
if (empty($_POST['title'])) {//if no name has been supplied
$error[] = 'Please enter a title for your post.';//add to array "error"
$show_errors = 'show';
} else {
$title = $_POST['title'];//else assign it a variable
}
if (empty($_POST['desc'])) {
$error[] = 'Please enter a short desc of your post.';//add to array "error"
$show_errors = 'show';
} else {
$desc = $_POST['desc'];//else assign it a variable
}
if (empty($error)){ //if no error, insert into db
$new_post = "INSERT INTO `posts` (`title`, `desc`) VALUES ('$title', '$desc')";
$result = mysql_query($new_post) or die(mysql_error('error inserting post'));
}
}
那麼HTML是:
<!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>Untitled Document</title>
</head>
<body>
<?php if (isset($show_errors)) {
//show user the errors if form cant be submitted
echo '<div> <ol>';
foreach ($error as $key => $values) { echo ' <li>'.$values.'</li>'; }
echo '</ol></div><br />'; }?>
<br />
<form method="post" id="newpost" action="" enctype="multipart/form-data">
<div><input name="title" type="text" value="" class="title_input"></div>
<div><textarea id="area4" cols="40" rows="5" name="desc" class="desc_texbox"></textarea></div>
<div><input type="file" name="images1"></div>
<div><input type="file" name="images2"></div>
<div><input type="file" name="images3"></div>
<div><input type="file" name="images4"></div>
<div><input type="file" name="images5"></div>
<div><input type="file" name="images6"></div>
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" id="upload" value="Upload">
</form>
</body>
</html>
我會建議通過將圖像移動到圖像表而不是在posts表中設置重複字段來規範化數據結構。 – nnichols 2012-04-14 15:55:00