将PHP变量传递给MySQL数据库

时间:2015-06-09 22:55:23

标签: php mysql database forms

我无法将变量的值传递给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 [&#39; $ image&#39;]作为值。同样,我可以在提交表单时回显值,因此值存在 - 我只是无法将其传递到数据库记录中。如果我手动输入表单字段中的数据,我可以使它工作。我在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){[&#34;已提交&#34;] =&gt; string(4)&#34; true&#34; [&#34; ID&#34;] =&GT; string(0)&#34;&#34; [&#34;姓名&#34;] =&GT; string(10)&#34; first_name&#34; [&#34;部门&#34;] =&GT; string(10)&#34; department&#34; [&#34;电子邮件&#34;] =&GT;字符串(5)&#34;电子邮件&#34; [&#34;图像&#34;] =&GT; string(0)&#34;&#34; }

2 个答案:

答案 0 :(得分: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行)

答案 1 :(得分:0)

由于您的主要目标是保存在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,因此在插入新记录时无法保存图像文件名,因此您唯一的选择是更新它。

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