【问题标题】:Image uploaded by users is not being inserted to the table用户上传的图像未插入到表中
【发布时间】:2018-05-21 06:20:48
【问题描述】:

除了 $sqlImg(它应该将上传的图像插入到表中)之外的所有东西都在工作。有人可以向我解释为什么它不起作用吗?或者,如果有另一种可行的方法,我很想听听。下面的文件是我的upload.inc.php。我打算将图像插入到我的表中后,在另一个名为 home.php 的文件中回显该图像。

<?php

if (!isset($_SESSION)) {
session_start();}

include_once 'includes/dbh.inc.php';
$id = $_SESSION['key'];

if (isset($_POST['submitFile'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));


$allowed = array('jpg', 'jpeg', 'png');

if (in_array($fileActualExt, $allowed)) {
    if ($fileError == 0) {
        if ($fileSize < 1000000) {
            $fileNameNew = "profile".$id.".".$fileActualExt;
            $fileDestination = 'uploads/'.$fileNameNew;
            move_uploaded_file($fileTmpName, $fileDestination);

            $sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
            mysqli_query($conn, $sql);

            $sqlImg = "INSERT INTO profileimg (image) WHERE userid='$id' VALUES ($fileNameNew);";
            mysqli_query($conn, $sqlImg);

            header("Location: home.php?upload=success");
        }
        else { echo "Sorry, your file size is too big.";}
    }
    else { echo "Oops, an error occurred!";}
}
else { echo "Please upload png and jpg files only.";}
}

【问题讨论】:

    标签: php mysqli insert-into


    【解决方案1】:

    您正在对新图像执行INSERT。我认为你需要UPDATE

    更改:

    $sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
    

    收件人:

    $sql = "UPDATE profileimg SET status=0, image = '$fileNameNew' WHERE userid='$id';";
    

    并删除:

    $sqlImg = "INSERT INTO profileimg (image) WHERE userid='$id' VALUES ($fileNameNew);";
    mysqli_query($conn, $sqlImg);
    

    您以错误的方式执行 session_start()。它应该一直被调用。

    更改:

    if (!isset($_SESSION)) {
    session_start();}
    

    收件人:

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    

    【讨论】:

    • 当我把它改成“session_start();”此错误再次出现:注意:会话已启动 - 忽略第 3 行 C:\wamp\www\FormFinalPush\upload.php 中的 session_start()。这就是我使用 "if (!isset($_SESSION)) { session_start();}" 代替。
    • 更新了我的答案。
    • 但无论如何,非常感谢你!它起作用了,图片现在插入到我的桌子上。 :)
    • 哦,第一次遇到这种情况,感谢您传授的知识! :)
    【解决方案2】:
    $sqlImg = "INSERT INTO profileimg (image) WHERE userid='$id' VALUES ($fileNameNew);";
            mysqli_query($conn, $sqlImg);
    

    应该是

    $sqlImg = "INSERT INTO profileimg (image) WHERE userid=".$id." VALUES (".$fileNameNew.")";
            mysqli_query($conn, $sqlImg);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 2015-10-17
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      相关资源
      最近更新 更多