插入更新语句而不将数据插入表

时间:2018-01-21 09:42:48

标签: php sql

提交Fresh Forms时,除app_id外没有任何内容插入到数据库中。但是当我们在现有的 appid 上传图片时,它会更新到数据库。所以插入查询不适用于除appid之外的其他字段。并且更新查询在这里正常工作。

<?php

session_start();

$appid = $_GET['appid'];

include("connect.php");

if($_POST){

$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
        $pptimg =  $_FILES["file"]["name"];
        $_SESSION['pptimg'] = $pptimg;
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

}

// Insert record
  $query = "INSERT INTO payments (app_id, pptimg) VALUES('$appid', '$pptimg') ON DUPLICATE KEY UPDATE    
            app_id='$appid', pptimg='$pptimg'";
  if (mysqli_query($connect,$query)){
    echo "Image were updated successfully.";
    header("Location: preview.php?appid=".$appid);
    }else{
    echo "Photo not uploaded".mysqli_error($connect);
    }

?>

1 个答案:

答案 0 :(得分:0)

让我们仔细看看你的代码的这一部分:

if($_POST){
   // Many checks here...

    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "uploaded";
            $pptimg =  $_FILES["file"]["name"]; // <-- Variable set only here
            $_SESSION['pptimg'] = $pptimg;
        } else {
            echo "didn't upload";
        }
    }
}

// Insert record
$query = "INSERT INTO payments (app_id, pptimg) VALUES('$appid', '$pptimg')
          ON DUPLICATE KEY UPDATE
          app_id='$appid', pptimg='$pptimg'";

我缩进了它,删除了一些行并简化了其他行以专注于结构。

现在,你看到发生了什么? 每次访问此脚本时,您都会尝试插入记录。但等等 - 如果有错误?你只需打印它就可以了。

是否有错误 - 您正在插入记录。但是,您在查询中使用的$pptimg变量仅在文件上载时设置。 在其他情况下$pptimg未设置,因此您将此字段设为空

相关问题