[英]PHP upload image to folder and insert record to database
我用PHP編寫了用於上傳圖像的代碼,但是我有一個問題,當我上傳圖像時,數據庫中沒有記錄,但是圖像被上傳到了我想要的路徑。
這是我的代碼:
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload_form">
<input id="file" type="file" name="file[]" />
<input type="submit" id="upload" name="submit" value="Dodaj" />
</form>
include 'init.php';
$uploaded = [];
$allowed = ['jpg', 'png'];
$succeeded = [];
$failed = [];
if(!empty($_FILES['file'])){
foreach($_FILES['file']['name'] as $key => $name){
if($_FILES['file']['error'][$key] == 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if(in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true){
$succeeded[] = array('name' => $name, 'file' => $file);
$path = 'uploads';
$sql = "INSERT INTO users (img_path, img_name, img_type) VALUES ('$path', '$file', '$ext') WHERE id = '$session_user_id'";
$result = mysql_query($sql);
}else{
$failed[] = array('name' => $name);
}
}
}
初始化文件:
session_start();
mysql_connect('localhost','root','');
mysql_select_db('croglas');
mysql_query('SET CHARACTER SET utf8');
include 'functions.php';
if(logged_in() === true){
$session_user_id = $_SESSION['id'];
$user_data = user_data($session_user_id, 'id', 'username', 'password', 'email', 'address', 'zip', 'phone_number', 'city', 'type', 'points', 'img_path', 'img_name', 'img_type');
}
這可能會返回代碼忽略的錯誤:
INSERT INTO users (img_path, img_name, img_type) VALUES ('$path', '$file', '$ext') WHERE id = '$session_user_id'
INSERT
語句沒有WHERE
子句。 只需完全省略該子句:
INSERT INTO users (img_path, img_name, img_type) VALUES ('$path', '$file', '$ext')
此外,您應該在執行SQL語句后檢查SQL錯誤。
編輯:或者...是否需要改為UPDATE
語句? 讓我感到奇怪的是,一個名為users
的表將保存圖像記錄。 您是在更新 現有用戶記錄以包括新值嗎? 那將有一個WHERE
子句。 像這樣:
UPDATE users SET img_page='$path', img_name='$file', img_type='$ext' WHERE id = '$session_user_id'
您的查詢是錯誤的,你不能有where
在INSERT語句。
應該是這樣
INSERT INTO users (img_path, img_name, img_type) VALUES ('$path', '$file', '$ext')
另外,一個提示:使用mysqli
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.