【问题标题】:Pass PHP variable to MySQL database将 PHP 变量传递给 MySQL 数据库
【发布时间】:2015-08-24 23:45:40
【问题描述】:

我在将变量的值传递给 MySQL 数据库中的新记录时遇到问题。我创建了一个用户填写基本信息的表单。然后他们会上传一张图片。 PHP 代码使用要分配的下一个 id 重命名图像,并连接文件类型以创建新文件名。我用

将新名称分配给变量 $image
$image = mysqli_insert_id($con) . "." . $imageFileType;

我可以回显变量并验证它是否正常工作 - 例如 431.jpg 将是文件名。此外,图像会以正确的重命名约定上传到服务器。现在我需要在提交表单时将该值传递给数据库。它将被传递到数据库中的字段名称 image。所以我和其他变量一起

$id = $_POST['id'];
$firstname = $_POST['firstname'];
$department = $_POST['department'];
$email = $_POST['email'];
$image = $_POST['image'];

我正在尝试使用如下所示的隐藏字段在表单中传递值:

<input name="image" type="hidden" value="<?php echo $image; ?>" />

除了图像名称之外,所有其他数据都被传递到数据库中。我尝试了很多变体——甚至尝试使用 $_POST['$image'] 作为值。同样,我可以在提交表单时回显该值,因此该值存在-我只是无法将其传递到数据库记录中。如果我手动在表单字段中输入数据,我可以让它工作。我在 phpMyAdmin 中创建了字段类型 VARCHAR 和 TEXT 只是为了尝试不同的东西。

如果有任何帮助,那就太好了。

下面是 $sqlinsert 语句:

$sqlinsert = "INSERT INTO `test_2015`.`test_table` ( `id` , `firstname`, `department`,  `email`, `image` ) 
VALUES ( '$id',  '$firstname', '$department',  '$email', '$image' )";

下面是 PHP:

    <?php

if (isset($_POST['submitted'])){
include('connect.php');
// VARIABLES
    $id = $_POST['id'];
    $firstname = $_POST['firstname'];
    $department = $_POST['department'];
    $email = $_POST['email'];
    $image = $_POST['image'];
    $sqlinsert = "INSERT INTO `test_2015`.`test_table` ( `id` , `firstname`, `department`, `email`, `image` ) 
    VALUES ( '$id',  '$firstname', '$department', '$email', '$image' )";

    //NESTED IF STATEMENT
    // RUN THE QUERY
if ( !mysqli_query($con, $sqlinsert) )
{
    die('error inserting new record');

} // END OF NESTED IF STATEMENT

// START IMAGE UPLOAD HERE ******************************************

$target_dir = "../images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);


    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
//}  REMOVE THIS IF ISSET END

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.   ";
    $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 "<div style ='font:16px Arial,tahoma,sans-serif;color:#ff0000;font-weight:bold'>File was not uploaded.</div>";


// if everything is ok, try to upload file
} else {

        $imageName = mysqli_insert_id($con) . "." . $imageFileType;
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $imageName ))

    {

// CHANGE FILE NAME TO CURRENT ID
// USING mysqli_insert_id($con) TO GET ID AND CONCATENATE FILE TYPE
        echo "New IMAGE file name is : ", $imageName;

// PASS NAME FOR IMAGE TO $image HERE       
        $image = $imageName;
        echo "image =  : ", $image;
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        echo "<br>";
// GET THE ASSIGNED ID USING: mysqli_insert_id()
        echo "New Record ID is : "  . mysqli_insert_id($con);

    } else {
        echo "<div style ='font:16px Arial,tahoma,sans-serif;color:#ff0000;font-weight:bold'>
        Sorry, there was an error uploading your file.</div>";
        echo "<br>";

    }
}
    // END IMAGE UPLOAD HERE   ******************************************
    $newrecord = "1 record added to the database";
    echo "<br>";
} // END MAIN IF STATEMENT
// Close connection
mysqli_close($con);
?>

下面是我的表格:

    <form method="post" action="add_record.php" enctype="multipart/form-data">
<input type="hidden" name="submitted" value="true" />
<fieldset>
    <legend>New Record</legend>
    <label><input type="hidden" name="id" /></label>
    <label>First Name : <input type="text" name="firstname" required="required" /></label><br /><br />
    <label>Department : <input type="text" name="department" required="required" /></label><br /><br />
    <label>Email Address : <input type="text" name="email" required="required" /></label><br /><br />
    <label>Image Name: <input name="image" type="hidden" value="<?php echo $image; ?>" /></label>
</fieldset>
<br />
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="add new record button"  />
</form>

来自 var_dump($POST) 的结果;

array(6) { ["submitted"]=> string(4) "true" ["id"]=> string(0) "" ["firstname"]=> string(10) "first_name" [ "部门"]=> 字符串(10) "部门" ["电子邮件"]=> 字符串(5) "电子邮件" ["图像"]=> 字符串(0) "" }

【问题讨论】:

  • 如果您的文件名不是以数字开头并且您没有使用AUTO_INCREMENTing PRIMARY KEY,这无论如何都不会起作用。
  • 我应该提到我正在对设置为主键的 ID 字段使用自动增量。所有这一切都很好 - 图像上传的文件名是 ID 并附加了文件类型。我只是无法将该文件名传递到新创建的行/记录中的字段中。
  • 你能发布你的mysql插入语句吗?,编辑问题并包含它
  • 除了您对 sql 注入持开放态度之外,它应该可以正常工作。我怀疑您在发布表单之前根本没有用任何值填充隐藏的输入,这是如何处理的?你有一些javascript吗?通常你会从 $_FILES 数组中获取文件名,不太确定你的隐藏输入是什么
  • 我不是 PHP 专家——这和我迄今为止尝试过的一样复杂。我只使用了我在这个网站上找到的样本中的隐藏输入。我也尝试应用 mysqli_real_escape_string() 但在提交表单时收到错误消息。如果我可以回显新的文件名,我不应该能够将它传递给数据库吗?我什至尝试了一个单独的 isset 但同样的问题 - 没有传递任何值。

标签: php mysql database forms


【解决方案1】:

问题是当您运行插入查询时,$image 只是一个空字符串(源自一个空的隐藏输入)。我有点理解为什么它在那里,与验证失败有关,而不是它有多大帮助,因为如果是这种情况,则需要重新选择文件。

添加这个:

$image = mysqli_real_escape_string ($con , $image);
$queryStr = "update `test_2015`.`test_table` set `image`= '$image' where `id`=" . mysqli_insert_id($con);
mysqli_query($con, $queryStr);

之后:

 $image = $imageName;

(距离脚本底部大约 20 行)

【讨论】:

  • 添加了建议的代码,它可以工作了!这部分我把大部分头发都拉了出来。现在我明白我需要回去更新记录。检查了所有内容,它适用于不同的图像文件格式。谢谢。
【解决方案2】:

由于您的主要目标是保存在 image 字段中生成的文件名,因此请考虑以下 php 代码:

    <?php

if (isset($_POST['submitted'])){
include('connect.php');
// VARIABLES
    $id = $_POST['id'];
    $firstname = $_POST['firstname'];
    $department = $_POST['department'];
    $email = $_POST['email'];
    $image = $_POST['image'];
    $sqlinsert = "INSERT INTO `test_2015`.`test_table` ( `id` , `firstname`, `department`, `email`, `image` ) 
    VALUES ( '$id',  '$firstname', '$department', '$email', '$image' )";

    //NESTED IF STATEMENT
    // RUN THE QUERY
if ( !mysqli_query($con, $sqlinsert) )
{
    die('error inserting new record');

} // END OF NESTED IF STATEMENT

// START IMAGE UPLOAD HERE ******************************************

$target_dir = "../images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);


    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
//}  REMOVE THIS IF ISSET END

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.   ";
    $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 "<div style ='font:16px Arial,tahoma,sans-serif;color:#ff0000;font-weight:bold'>File was not uploaded.</div>";


// if everything is ok, try to upload file
} else {

        $imageName = mysqli_insert_id($con) . "." . $imageFileType;
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $imageName ))

    {

// CHANGE FILE NAME TO CURRENT ID
// USING mysqli_insert_id($con) TO GET ID AND CONCATENATE FILE TYPE
        echo "New IMAGE file name is : ", $imageName;

// PASS NAME FOR IMAGE TO $image HERE       
        $image = $imageName;
        echo "image =  : ", $image;
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        echo "<br>";
// GET THE ASSIGNED ID USING: mysqli_insert_id()
        echo "New Record ID is : "  . mysqli_insert_id($con);

// SAVE New IMAGE file name

        $sqlupdate = "UPDATE `test_2015`.`test_table` SET `image` = '$image' WHERE id = " . mysqli_insert_id($con);

        if ( !mysqli_query($con, $sqlupdate) )
        {
            die('error updating new record');
        }

    } else {
        echo "<div style ='font:16px Arial,tahoma,sans-serif;color:#ff0000;font-weight:bold'>
        Sorry, there was an error uploading your file.</div>";
        echo "<br>";

    }
}
    // END IMAGE UPLOAD HERE   ******************************************
    $newrecord = "1 record added to the database";
    echo "<br>";
} // END MAIN IF STATEMENT
// Close connection
mysqli_close($con);
?>

我添加的代码如下:

// SAVE New IMAGE file name

$sqlupdate = "UPDATE `test_2015`.`test_table` SET `image` = '$image' WHERE id = " . mysqli_insert_id($con);

if ( !mysqli_query($con, $sqlupdate) )
{
    die('error updating new record');
}

这里的想法是在您成功生成图像的新文件名后更新新插入的记录。插入新记录时无法保存图像文件名,因为尚未生成 id,因此您唯一的选择是更新它。

如果您的唯一目标是保存新生成的图像文件名,除非您有其他用途,否则我认为您不需要在表单中使用名为“图像”的隐藏输入。

【讨论】:

    猜你喜欢
    • 2017-07-23
    • 2020-01-24
    • 2015-12-17
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2021-01-04
    相关资源
    最近更新 更多