gpt4 book ai didi

PHP上传图片到文件夹并插入记录到数据库

转载 作者:行者123 更新时间:2023-12-01 00:41:06 26 4
gpt4 key购买 nike

我用 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 的表会保存图像记录。您是否正在更新现有用户记录以包含新值? That 将有一个 WHERE 子句。像这样:

UPDATE users SET img_page='$path', img_name='$file', img_type='$ext' WHERE id = '$session_user_id'

关于PHP上传图片到文件夹并插入记录到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32337157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com