插入HTML表单数据为空白

时间:2019-09-09 10:36:30

标签: php html

我正在尝试将我输入的信息发送到HTML表单,MySQL数据库表中。该功能有效,但是...将空白数据输入到Mysql数据库中

我不知道还能尝试什么。我真的很新

这是我的HTML表单:

<form action="" method="post">
  <div class="form-group">
    <label for="date">Date</label>
    <input type="date" class="form-control" id="date" aria-describedby="emailHelp" placeholder="Date">
    <small id="emailHelp" class="form-text text-muted">The date the team went to the job site</small>
  </div>
  <div class="form-group">
    <label for="job_number">Job Number</label>
    <input type="text" class="form-control" id="job_number" placeholder="JC2020">
  </div>
  <div class="form-group">
    <label for="job_name">Job Name</label>
    <input type="text" class="form-control" id="job_name" placeholder="AVI Tender">
  </div>
 <div class="form-group">
    <label for="team_name">Team Name</label>
    <input type="text" class="form-control" id="team_name" placeholder="Shane">
  </div>
  <div class="form-group">
    <label for="pastel_code">Pastel Code</label>
    <input type="text" class="form-control" id="pastel_code" placeholder="012">
  </div>
  <div class="form-group">
    <label for="vrn">Vehicle Registration</label>
    <input type="text" class="form-control" id="vrn" placeholder="ND 123-456">
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>

</form>

这是我的PHP文件,用于处理数据:

<?php
require_once('config.php');

$date= $_POST['date'];
$job_number= $_POST['job_number'];
$team_name= $_POST['team_name'];
$pastel_code= $_POST['pastel_code'];
$vrn= $_POST['vrn'];
$job_name= $_POST['job_name'];


$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO job_records (date, job_number, team_name, pastel_code, vrn, job_name)
VALUES ('$date', '$job_number', '$team_name', '$pastel_code', '$vrn', '$job_name')";

$conn->exec($sql);
echo "<script>alert('Data successfully added!'); window.location='dataentry.php'</script>";
?>

提交表单后,将显示一条消息,提示已添加数据,然后重定向到“主数据”页面,其中包含我随时间输入的所有条目。但是我处理的所有条目都是空白。我在做什么错了?

2 个答案:

答案 0 :(得分:0)

正如我提到的,每个表单元素都需要一个name属性,以便在提交表单时它会出现在POST数组中。在使用Javascript与DOM交互时,主要使用ID属性,因此在/ /上确实不需要。

<form action='' method='post'>

  <div class='form-group'>
    <label for='date'>Date</label>
    <input type='date' class='form-control' id='date' name='date' aria-describedby='emailHelp' placeholder='Date'>
    <small id='emailHelp' class='form-text text-muted'>The date the team went to the job site</small>
  </div>

  <div class='form-group'>
    <label for='job_number'>Job Number</label>
    <input type='text' class='form-control' id='job_number' name='job_number' placeholder='JC2020'>
  </div>

  <div class='form-group'>
    <label for='job_name'>Job Name</label>
    <input type='text' class='form-control' id='job_name' name='job_name' placeholder='AVI Tender'>
  </div>

 <div class='form-group'>
    <label for='team_name'>Team Name</label>
    <input type='text' class='form-control' id='team_name' name='team_name' placeholder='Shane'>
  </div>

  <div class='form-group'>
    <label for='pastel_code'>Pastel Code</label>
    <input type='text' class='form-control' id='pastel_code' name='pastel_code' placeholder='012'>
  </div>

  <div class='form-group'>
    <label for='vrn'>Vehicle Registration</label>
    <input type='text' class='form-control' id='vrn' name='vrn' placeholder='ND 123-456'>
  </div>

  <button type='submit' class='btn btn-primary'>Submit</button>
</form>

这表示已在注释中解决的主要问题是SQL injection漏洞-PDOmySQLi的好处之一是prepared statements。当您使用PDO时,这可能有用:

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        require_once('config.php');

        $args=array(
            'date'          =>  FILTER_SANITIZE_STRING,
            'job_number'    =>  FILTER_SANITIZE_STRING,
            'team_name'     =>  FILTER_SANITIZE_STRING,
            'pastel_code'   =>  FILTER_SANITIZE_STRING,
            'vrn'           =>  FILTER_SANITIZE_STRING, 
            'job_name'      =>  FILTER_SANITIZE_STRING
        );
        $_POST=filter_input_array( INPUT_POST, $args );


        $params=array();

        $sql='insert into `job_records` ( `date`, `job_number`, `team_name`, `pastel_code`, `vrn`, `job_name` ) values ( :date, :job_number, :team_name, :pastel_code, :vrn, :job_name )';
        foreach( array_keys( $args ) as $key ){
            $params[ ':'.$key ] = ${$key};
        }

        $stmt=$conn->prepare( $sql );
        $res = $stmt->execute( $params );

        exit( header( sprintf( 'Location: dataentry.php?status=%s', $res ? 'ok' : 'fail' ) ) );
    }
?>

演示-经过测试,似乎可以正常运行

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        try{

            /* PDO connection */
            $dbport =   3306;
            $dbhost =   'localhost';
            $dbuser =   'root'; 
            $dbpwd  =   'xxx'; 
            $dbname =   'xxx';

            $options=array( 
                PDO::ATTR_CURSOR                    =>  PDO::CURSOR_SCROLL,
                PDO::ATTR_PERSISTENT                =>  false,
                PDO::MYSQL_ATTR_USE_BUFFERED_QUERY  =>  true,
                PDO::ATTR_EMULATE_PREPARES          =>  true,
                PDO::MYSQL_ATTR_INIT_COMMAND        =>  'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_unicode_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
            );

            $dsn='mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname.';charset=UTF8';
            $db = $conn = new PDO( $dsn, $dbuser, $dbpwd, $options );



            /* disabled as not relevant in demo */
            #require_once('config.php');


            $args=array(
                'date'          =>  FILTER_SANITIZE_STRING,
                'job_number'    =>  FILTER_SANITIZE_STRING,
                'team_name'     =>  FILTER_SANITIZE_STRING,
                'pastel_code'   =>  FILTER_SANITIZE_STRING,
                'vrn'           =>  FILTER_SANITIZE_STRING, 
                'job_name'      =>  FILTER_SANITIZE_STRING
            );
            $_POST=filter_input_array( INPUT_POST, $args );
            extract( $_POST );


            $errors=array();
            $params=array();
            $keys=array_keys( $args );


            /* dynamically build sql query from $args array */
            $sql=sprintf('insert into `job_records` 
                            ( `%s` ) 
                            values 
                            ( :%s ) ', 
                            implode( '`,`', $keys ),
                            implode( ', :', $keys )
                        );

            /* check that each variable is set else throw exception and continue */
            foreach( array_keys( $args ) as $key ){
                try{
                    /* test variable variable against those generated by `extract` above */
                    if( empty( ${$key} ) ) throw new Exception( sprintf( 'empty field: %s', $key ) );

                    /* add the parameter to the args to be executed */
                    $params[ ':'.$key ] = ${$key};
                }catch( Exception $e ){
                    $errors[]=$e->getMessage();
                    continue;
                }
            }

            /* If all went well execute the query & redirect user */
            if( !empty( $params ) && empty( $errors ) && !empty( $conn ) ){

                $stmt=$conn->prepare( $sql );
                if( !$stmt ) throw new PDOException('Failed to prepare SQL Query');
                $res = $stmt->execute( $params );

                exit( header( sprintf( 'Location: dataentry.php?status=%s', $res ? 'ok' : 'fail' ) ) ); 
            }

            if( !empty( $errors ) ) printf( '<pre>%s</pre>', print_r($errors,true) );


        }catch( PDOException $e ){
            exit( $e->getMessage() );
        }
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>PDO form test</title>
    </head>
    <body>
        <form action='' method='post'>

          <div class='form-group'>
            <label for='date'>Date</label>
            <input type='date' class='form-control' id='date' name='date' aria-describedby='emailHelp' placeholder='Date'>
            <small id='emailHelp' class='form-text text-muted'>The date the team went to the job site</small>
          </div>

          <div class='form-group'>
            <label for='job_number'>Job Number</label>
            <input type='text' class='form-control' id='job_number' name='job_number' placeholder='JC2020'>
          </div>

          <div class='form-group'>
            <label for='job_name'>Job Name</label>
            <input type='text' class='form-control' id='job_name' name='job_name' placeholder='AVI Tender'>
          </div>

         <div class='form-group'>
            <label for='team_name'>Team Name</label>
            <input type='text' class='form-control' id='team_name' name='team_name' placeholder='Shane'>
          </div>

          <div class='form-group'>
            <label for='pastel_code'>Pastel Code</label>
            <input type='text' class='form-control' id='pastel_code' name='pastel_code' placeholder='012'>
          </div>

          <div class='form-group'>
            <label for='vrn'>Vehicle Registration</label>
            <input type='text' class='form-control' id='vrn' name='vrn' placeholder='ND 123-456'>
          </div>

          <button type='submit' class='btn btn-primary'>Submit</button>

        </form>
    </body>
</html>

答案 1 :(得分:-1)

您的代码正确无误,但在您的输入字段中产生了错误
在输入字段中简单地使用name(Attribute)并传递该名称以保存数据。

<form action="insert.php" method="post">
    <p>
        <label for="firstName">First Name:</label>
        <input type="text" name="first_name" id="firstName">
    </p>
    <p>
        <label for="lastName">Last Name:</label>
        <input type="text" name="last_name" id="lastName">
    </p>
    <p>
        <label for="emailAddress">Email Address:</label>
        <input type="text" name="email" id="emailAddress">
    </p>
    <input type="submit" value="Submit">
</form>

获取表单值并将其插入数据库

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['last_name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);

// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>

代码错误的结论

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO job_records ('database column name with comma seperated')
VALUES ('Input variable value seperated by comma')";