在PHP中循环表单值,然后将它们放入数据库

时间:2016-10-21 05:21:40

标签: php mysqli

如何遍历$ _POST值。

  • $ _ POST [ “speaker_full_name”]
  • $ _ POST [ “speaker_description”]

让我试着解释......

我正在尝试将字段值存储到我的数据库表中。我的代码适用于上传文件 $ _ FILES ['uploads'] ['name'] ,但字段“ speaker_full_name ”和“ speaker_description “刚刚从最后一个被取代。

希望这不会让任何人感到困惑。我尽力解释这个问题。我花了很多时间试图解决这个问题,但我需要帮助。我只是在学习php。



这是我的HTML代码

<?php
session_start();
include_once 'db-connect.php';

if (!isset($_SESSION['userSession'])) {
 header("Location: index.php");
}

$query = $DBcon->query("SELECT * FROM users WHERE user_id=".$_SESSION['userSession']);
$userRow=$query->fetch_array();
$DBcon->close();

?>


<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title> </title>

    <!-- Bootstrap Core CSS -->
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="style.css" rel="stylesheet">

    <!-- Theme CSS -->
    <link href="css/clean-blog.css" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>


    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


    <script>
        $( function() {
            $( "#datepicker" ).datepicker();
        } );
    </script>


    <style type="text/css">
        .row {
            padding-bottom: 100px;
        }
        legend {
            font-weight: bolder;
            color: #16a085;
        }
    </style>


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

<div class="container">
    <form action="upload-data.php" method="post" enctype="multipart/form-data">


        <div class="row"> <!-- row -->

            <fieldset>
            <legend>Basic Information</legend>

            <div class="col-md-4">
                <label>Contact Person:</label>
                <input type="text" name="contact_person" placeholder="" value="Timothy Logue" /><br /><br />

            </div>

            <div class="col-md-4">
                <label>Contact Email:</label>
                <input type="text" name="contact_email" placeholder="" value="timmylogue@gmail.com" /><br /><br />
            </div>

            <div class="col-md-4">
                <label>Phone:</label>
                <input type="text" name="contact_phone" placeholder="" value="000-000-7606" /><br /><br />
            </div>


            <div class="col-md-6">
                <label>Code:</label>
                <input type="text" id="check_code" name="code" style="max-width:150px" maxlength="15" value="1234" required=""> <span id="check-result"></span>
                <p style="width:200px;"><br>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.</p>
            </div>

            <div class="col-md-6">
                <label>Group Or Organization:</label>
                <input type="text" name="group_or_organization" placeholder="" value="Timothy Seminar" /><br /><br />
                <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.</p>
            </div>

            </fieldset>

        </div> <!-- row -->


        <hr> 


        <div class="row"> <!-- row -->

        <fieldset>
        <legend>Seminar Information</legend>

            <div class="col-md-6">
                <label>Seminar Date:</label>
                <input type="text" id="datepicker" name="date_of_seminar" placeholder="" value="02/15/17" /><br /><br />
                <span class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean </span>
            </div>

            <div class="col-md-6">
                <label>Seminar Time:</label>
                <input type="text" name="time_of_seminar" placeholder="" value="12:00pm" /><br /><br />
                <span class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean </span>
            </div>

            <div style="margin-top:30px" class="col-md-6">
                <label>Name of Place:</label>
                <input type="text" name="seminar_name_of_place" placeholder="" value="Timothys Palace" /><br /><br />
                <span class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean </span>
            </div>

            <div style="margin-top:30px" class="col-md-6">
                <label>Address:</label>
                <input type="text" name="address_of_seminar" placeholder="" value="1417 Neshaminy Valley Dr." /><br /><br />
                <span class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean </span>
            </div>

            <hr>

            <div style="margin-top:100px" class="col-md-6">
                <label>Upload a cover photo</label>
                    <p>A cover photo is the larger photo at the top of your seminar page.</p>
                    <!-- <input name="cover_pic[]" type="file" size="30" multiple required /><br><span>(Max size of 1 file : 100Kb)</span> -->
            </div>

        </fieldset>

        </div> <!-- row -->



        <hr>


        <div class="row"> <!-- row -->

        <fieldset>
        <legend>Hotel Accommodations</legend>

            <div class="col-md-6">
                <label>Hotel Name:</label>
                <input type="text" name="hotel_name" placeholder="" value="Timothys Hotel" /><br /><br />
            </div>

            <div class="col-md-6">
                <label>Rate:</label>
                <input type="text" name="hotel_rate" placeholder="$0.00" value="0" /><br /><br />
            </div>

        </fieldset>

        </div> <!-- row -->



        <hr>


        <div class="row"> <!-- row -->

        <fieldset>
        <legend>Schedule:</legend>

            <div class="col-md-12">
                <span>Upload PDF file</span>
            </div>

        </fieldset>

        </div> <!-- row -->




        <hr>


        <div class="row"> <!-- row -->

        <fieldset>
        <legend>Speakers:</legend>

            <div class="col-md-12 input_fields_wrap">
                    <br>
                        <label>Full Name</label>
                        <input name="speaker_full_name" class="form-control" value="Timothy 1" type="text"><br>

                        <label>Description</label>
                        <textarea name="speaker_description" class="form-control" rows="3">dfsdgffhjfgjd</textarea><br>

                        <label>Upload Photo</label>
                        <input name="uploads[]" type="file" size="30"  /><br><span>(Max size of 1 file : 100Kb)</span>
                </div>

                <button style="margin-top:45px;" class="add_field_button">Add More Speakers</button>

        </fieldset>

        </div> <!-- row -->



        <div style="margin-top:50px">
        <input type="submit" value=" Submit " name="submit"/><br />
        </div>

    </form>
</div> <!-- container -->



<script type="text/javascript">
    $(document).ready(function() {
    var max_fields      = 5; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><br><br><label>Full Name</label><input name="speaker_full_name" class="form-control" type="text"><br> <label>Description</label><textarea name="speaker_description" class="form-control" rows="3"></textarea><br> <label>Upload Photo</label><input name="uploads[]" type="file" size="30" /> <a href="#" class="remove_field"><br><p style="color:red">Delete<p></a></div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});



</script>





<script type="text/javascript">
    $(document).ready(function() {
        var x_timer;    
        $("#check_code").keyup(function (e){
            clearTimeout(x_timer);
            var user_name = $(this).val();
            x_timer = setTimeout(function(){
                check_username_ajax(user_name);
            }, 1000);
        }); 

    function check_username_ajax(check_code){
        $("#check-result").html('<img src="images/ajax-loader.gif" />');
        $.post('check-if-code-exists.php', {'check_code':check_code}, function(data) {
          $("#check-result").html(data);
        });
    }
    });
</script>





</body>
</html>



这是我的PHP代码

session_start();

include_once 'db-connect.php';

// ***************
// Error Reporting
// ***************
error_reporting(E_ALL); 
ini_set('display_errors', 1);

// ***************
// Database Connection For User System Login
// **************

if (!isset($_SESSION['userSession'])) {
 header("Location: index.php");
}

$query = $DBcon->query("SELECT * FROM users WHERE user_id=".$_SESSION['userSession']);
$userRow=$query->fetch_array();
$DBcon->close();





// ***************
// Database Connection For User System Login
// ***************
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mychiroseminar";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}




$sql = "INSERT INTO seminars (code, users_email, group_or_organization, contact_person, contact_phone, contact_email, date_of_seminar, time_of_seminar, seminar_name_of_place, address_of_seminar, hotel_name, hotel_rate)

VALUES (
        '".$_POST["code"]."',
        '".$userRow['email']."',
        '".$_POST["group_or_organization"]."',
        '".$_POST["contact_person"]."',
        '".$_POST["contact_phone"]."',
        '".$_POST["contact_email"]."',


        '".$_POST["date_of_seminar"]."',
        '".$_POST["time_of_seminar"]."',
        '".$_POST["seminar_name_of_place"]."',
        '".$_POST["address_of_seminar"]."',
        '".$_POST["hotel_name"]."',
        '".$_POST["hotel_rate"]."'
        )";



if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}





// Getting the total number of files
$count = count($_FILES['uploads']['name']);

if (!$count)
    {
    echo "Upload files.";
    }
  else
    {

    // Processing each file iteratively

    for ($i = 0; $i < $count; $i++)
        {
        $file_name = $_FILES['uploads']['name'][$i];
        $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Uploading the file

        $tmp = $_FILES['uploads']['tmp_name'][$i];
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($file_name);


        if (move_uploaded_file($tmp, $target_file))
            {

            echo '<br>';
            echo '<strong>';
            echo $target_file;
            echo '</strong>'; 
            echo '<br>';
            }
          else
            {
            echo "Sorry, there was an error uploading your file";
            }



            $sql = "INSERT INTO uploaded_files (code, users_email, speaker_full_name, speaker_description, file)

                VALUES ('".$_POST["code"]."',
                        '".$userRow['email']."',
                        '".$_POST["speaker_full_name"]."',
                        '".$_POST["speaker_description"]."',
                        '".$target_file."'
                        )";


            if (mysqli_query($conn, $sql)) {
                    echo "New record created successfully";
                } else {
                    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
                }


        }
    }


mysqli_close($conn);

1 个答案:

答案 0 :(得分:0)

假设有问题的字段(即speaker_full_namespeaker_description〜ie:<input name='speaker_full_name[]' />)以相同的形式重复,那么可能使用相同的变量$ i来访问类似的值这可能有用吗?但是你很容易受到sql注入 - 使用准备好的语句!

// Getting the total number of files
$count = count( $_FILES['uploads']['name'] );

if( !$count ) {
    echo "Upload files.";
} else {


    // Processing each file iteratively
    for( $i = 0; $i < $count; $i++ ) {
        $file_name = $_FILES['uploads']['name'][$i];
        $ext = strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) );

        // Uploading the file

        $tmp = $_FILES['uploads']['tmp_name'][$i];
        $target_dir = "uploads/";
        $target_file = $target_dir . basename( $file_name );


        if ( move_uploaded_file( $tmp, $target_file ) ) {
            echo '
            <br />
            <strong>'.$target_file.'</strong>
            <br />';

            $sql = "INSERT INTO uploaded_files (code, users_email, speaker_full_name, speaker_description, file)
                    VALUES ('".$_POST["code"][$i]."',
                            '".$userRow['email'][$i]."',
                            '".$_POST["speaker_full_name"][$i]."',
                            '".$_POST["speaker_description"][$i]."',
                            '".$target_file."'
                            )";

            $res=mysqli_query($conn, $sql);
            echo $res ? 'New record created successfully' : 'Error: ' . mysqli_error( $conn );


        } else {
            echo "Sorry, there was an error uploading your file";
        }
    }
    mysqli_close($conn);
}