gpt4 book ai didi

php - 如果为空则跳过输入字段的条件

转载 作者:行者123 更新时间:2023-11-29 17:06:04 25 4
gpt4 key购买 nike

我正在尝试设置一个条件,其中如果“文件字段”为空,它将跳过在数据库中的插入,因为它只是一个选项,然后继续在数据库中插入“名称”和“描述”,永远不会为空。

<?php
include("connection.php");

if (isset($_POST['submit']))
{

$name = mysqli_real_escape_string($conn, $_POST['name']);
$description = mysqli_real_escape_string($conn, $_POST['description']);

if ($name == '' || $description == '' )
{

$error = 'ERROR: Please fill required fields!';

renderForm($name, $description);
}
else
{

if(!empty($_FILES['filefield'])){
if(isset($_FILES['filefield'])){
$file=$_FILES['filefield'];
$upload_directory='uploads/';
$ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf";
$allowed_extensions=explode(',',$ext_str);
$ext = substr($file['name'], strrpos($file['name'], '.') + 1);
if (!in_array($ext, $allowed_extensions) )
{

echo '<script language="javascript">';
echo 'alert("file type not allowed for upload")';
echo '</script>';
exit();
}

$path=md5(microtime()).'.'.$ext;

if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){

$filefield = $_FILES["filefield"]["name"];
$path = $path."/".$filefield;
}
}
}
}

if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);
if($result)
{
echo '<script language="javascript">';
echo 'alert("Success!")';
echo '</script>';
exit();
}
}
?>

我不知道如何继续处理这个情况。非常感谢任何帮助。

最佳答案

首先,关闭所有逻辑,包括 if(move_uploaded_file),以便 $query 完全脱离任何条件。然后只需检查filefield是否已填写即可。如果不为空,您的 $query 将插入所有三个字段。如果是,您的 $query 仅插入 $name$description

这可以在以下(大量删减的)代码中看到:

/* Existing logic */
else
{
if (!empty($_FILES['filefield'])) {
if (isset($_FILES['filefield'])) {
if (move_uploaded_file($file['tmp_name'], $upload_directory.$path)) {
...
$path = $path."/".$filefield;
}
}
}
}

/* Modified logic */
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);

关于php - 如果为空则跳过输入字段的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52049341/

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