【问题标题】:trying to upload file - You have an error in your SQL syntax,尝试上传文件 - 您的 SQL 语法有错误,
【发布时间】:2018-09-13 21:11:03
【问题描述】:

当我尝试将图像文件上传到我的数据库以进行发布时收到错误消息。图像出现在我的文件夹中,但不会将其添加到 mysql 数据库中。 我还是一个初学者,不要评判......我找不到错误...... 错误: 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的“WHERE username = 'myusername'' 附近使用正确的语法

代码如下:

  $Destination = 'userfiles/posts';
    if(!isset($_FILES['attachment_image']) || !is_uploaded_file($_FILES['attachment_image']['tmp_name'])){
        $attachnewimg= 'default-background.jpg';
        move_uploaded_file($_FILES['attachment_image']['tmp_name'], "$Destination/$attachnewimg");
    }
    else{
        $RandomNum = rand(0, mt_getrandmax());
        $ImageName = str_replace(' ','-',strtolower($_FILES['attachment_image']['name']));
        $ImageType = $_FILES['attachment_image']['type'];
        $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
        $ImageExt = str_replace('.','',$ImageExt);
        $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
        $attachnewimg = $ImageName.'-'.$RandomNum.'.'.$ImageExt;
        move_uploaded_file($_FILES['attachment_image']['tmp_name'], "$Destination/$attachnewimg");
    }
    $sql1="UPDATE users SET attachment_image='$attachnewimg' WHERE username = '$temp'";
    $sql2="INSERT INTO users (attachment_image) VALUES ('$attachnewimg') WHERE username = '$temp'";
    $result = mysqli_query($mysqli,"SELECT * FROM users WHERE username = '$temp'");
    if( mysqli_num_rows($result) > 0) {
        if(!empty($_FILES['attachment_image']['name'])){
            mysqli_query($mysqli,$sql1)or die(mysqli_error($mysqli));
            header("location:/");
        }
    } 
    else {
        mysqli_query($mysqli,$sql2)or die(mysqli_error($mysqli));
        header("location:/");
    }

【问题讨论】:

  • INSERT 语句没有 WHERE 子句(除非 INSERT SELECT)。

标签: php mysqli upload localhost mariadb


【解决方案1】:

您的 INSERT 查询不正确,插入查询中没有 where 条件。更改您的插入查询,如下所示:

$sql2="INSERT INTO users (username ,attachment_image) VALUES ('$temp','$attachnewimg')";

检查 INSERT 语句的语法:

https://www.w3schools.com/sql/sql_insert.asp

【讨论】:

  • 现在它会将图像上传到之前的每个帖子,但不是我刚刚添加的那个。并将图像更改为所有以前的帖子都相同.. 这是屏幕截图prnt.sc/j0oo8o
  • 然后检查if( mysqli_num_rows($result) > 0) {这个条件返回什么?
  • 我弄错了,我需要从表中获取 ID,我稍微更改了代码 - 将 username = '$temp' 更改为 WHERE id = '.$id.' 现在每次我提交文章时它都会创建 2 个表。这是屏幕截图 - prnt.sc/j0otq9,如何防止它创建 2 个表但将所有信息放在一个表中?
  • 谢谢您,在更改了更多内容后,现在一切正常。
猜你喜欢
  • 2017-12-12
  • 2011-06-08
  • 1970-01-01
  • 2019-05-22
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
相关资源
最近更新 更多