PHP 获取输入、单选、选择数据并插入到 MySQL 表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6882633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:32:37  来源:igfitidea点击:

PHP get input , radio , selection data and insert into MySQL table

phpmysql

提问by ETAN

i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.

我是 php 新手,我一直在寻找有关使用 php 将表单的输入(文本)、收音机和选择数据插入 MySQL 数据库表的教程。我找到了一些教程,但大多数都令人困惑。所以我决定问问。

Okay here's what i want to do. I have a form which have two types of input and a selection 1. input type text 2. input type radio 3. selection

好的,这就是我想要做的。我有一个表单,它有两种类型的输入和一个选择 1. 输入类型文本 2. 输入类型单选 3. 选择

Here's the HTML code :

这是 HTML 代码:

<form action="" method="post" enctype="multipart/form-data">

  <strong>Your Name: </strong><br>
     <input type="text" name="myname" value="" />
  <br /><br/>    

  <strong>Which class type you want:</strong><br>
    <select name="selection">
      <option value="A">A</option>
      <option value="B">B</option>
      <option value="C">C</option>
    </select>

  <strong>Do you agree?</strong><br>
    <input type="radio" name="agree" value="Yes"> or 
    <input type="radio" name="agree" value="No">


  <input type="submit" name="submit" value="Submit">

</form>  

I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)

我已将表单操作设置为空白,因为 php 代码将与 HTML 位于同一文件中(顺便说一句,它是一个 php 文件)

MySQL table : info structure : 1. name 2. class 3. agree

MySQL表:信息结构:1.名称2.类3.同意

I want the php code to insert myname into name, selection's selected data into class, radio selected data into agree

我希望 php 代码将 myname 插入name,选择的选定数据插入class,radio selected data 插入同意

P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.

P/S 是的,我添加了一个连接到数据库的 php 脚本,我只想知道如何将表单数据导入 mysql。

Can someone write a php code example on how can i do this?

有人可以写一个关于如何执行此操作的 php 代码示例吗?

Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.

感谢,并有一个愉快的一天 。我希望我提供了足够的信息。如果你有帮助,再次感谢。

回答by Shef

1. There is a problem with your radioelement. The name should be the same for both options.

1.你的radio元素有问题。两个选项的名称应该相同。

It should be like this:

应该是这样的:

<input type="radio" name="agree" value="Yes"> or 
<input type="radio" name="agree" value="No">

2. You can access everything in the $_POSTarray, since you are using the method postfor the form.

2. 您可以访问$_POST数组中的所有内容,因为您使用的post是表单的方法。

$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];

3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you mustalways escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.

3. 如果您没有使用带有 PDO、MySQLi 等库的参数化 SQL……您必须始终对将在查询中使用的数据进行转义mysql_real_escape_string(),以防止 SQL 注入。

This would be a sample code, to do the escaping and the query.

这将是一个示例代码,用于进行转义和查询。

// write a function somewhere, to use as a shortcut 
// for escaping data which will be used in a query
function sql_escape($str){
    return "'".mysql_real_escape_string($str)."'";
}

// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
                    sql_escape($_POST['myname']),
                    sql_escape($_POST['selection']),
                    sql_escape($_POST['agree']));

// finally run it
$result = mysql_query($query);

回答by flxa

I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong. Considering your form is fairly simple you would not need this. @Shef's code would certainly do the job but I thought you might be interested in some more.

我在这里更进一步,还有很多事情可以做,有很多方法可以做到,例如,您可以扩展 $errors 数组以包含字段 id,然后突出显示 HTML 表单字段,以便用户可以准确地看到他们出错的地方。考虑到您的表单相当简单,您不需要这个。@Shef 的代码肯定可以完成这项工作,但我认为您可能对更多内容感兴趣。

    <?php
    // check the form has been submitted
    if (isset($_POST['submit'])) {
        // escape the form fields and assign them to variables
        // validate myname to ensure the user entered data
        if (isset($_POST['myname']) && $_POST['myname']!='') {
            $myname = mysql_real_escape_string($_POST['myname']);
        } else {
            // create an error variable array to store errors to display
            $errors[] = 'Please enter your name'; 
        }

        // no need to validate selection here as it alway's has a value
        $classtype = mysql_real_escape_string($_POST['selection']);

        // validate agree unless you want to add 'checked' to one of the values
        if (isset($_POST['agree']) && $_POST['agree']!='') {
            $agree = mysql_real_escape_string($_POST['agree']);
        } else {
            $errors[] = 'Please tell us if you agree?'; 
        }

        //if errors found tell the user else write and execute the query
        if ($errors) {
            $message = '<p class="error">We found a problem:</p><ul>';
            foreach($error as $msg){
                $message .= '<li>'.$msg.'</li>';
            }
            $message .= '</ul><p>Please fix the error/s to continue.</p>';
        } else {
            // write the query
            $query = "INSERT INTO table (myname, classtype, agree) VALUES ";                           
            $query .= "('$myname','$classtype','$agree')"
            // run the query
            mysql_query($query);
            $message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
        }
    }

    // print the message
    // show the variables in the form field so they don't need re-input
    if ($message!='') { echo $message; }
    ?>
    <form action="" method="post" enctype="multipart/form-data">

      <strong>Your Name: </strong><br>
        <input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
      <br /><br/>    

      <strong>Which class type you want:</strong><br>
        <select name="selection">
          <option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
          <option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
          <option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
        </select>

      <strong>Do you agree?</strong><br>
        <input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or 
        <input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>

      <input type="submit" name="submit" value="Submit">

    </form> 

Also: @sqwk, Don't point people towards w3schools, see this: http://w3fools.com/

另外:@sqwk,不要将人们指向 w3schools,请参阅:http://w3fools.com/

回答by bayburt

check this simple example:

检查这个简单的例子:

<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>

after you submit form, you can take name and sname.

提交表单后,您可以使用 name 和 sname。

welcome.php::

欢迎.php::

    <?php 
$name= $_POST["name"]; 
$sname= $_POST["sname"]; ?>

now you can use this variables as if you want.

现在您可以随意使用此变量。

回答by sqwk

Check whether there is any data in the $_POST array and get the values from it.

检查 $_POST 数组中是否有任何数据并从中获取值。

Have a look here—the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp

看看这里 - 第二个例子是你需要的:http: //www.w3schools.com/php/php_mysql_insert.asp

(You do have to make the changes that Shef suggested, though.)

(不过,您确实必须进行 Shef 建议的更改。)

Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.

还要记住检查您的数据完整性,否则人们可能会使用您的插入来运行恶意代码。