简体   繁体   English

使用php从HTML表单多次插入Mysql

[英]Multiple insert into Mysql from an html form using php

Thanks so very much for all your help, Mysql DB works , now I am encountering a little problem, hope I'll fix it quickly and a litle help of course, so here My Html form : 非常感谢您的所有帮助,Mysql DB可以正常工作,现在我遇到了一个小问题,希望我能尽快解决它,当然还有一点帮助,所以这里是我的HTML表单:

<div>Date: 
    <input onclick="ds_sh(this);" name="trans_date" readonly="readonly" style="cursor: text" /><br/><br/>
    Product:
    <select name="product_id []">
        <option value="1">Item1</option>
        <option value="2">Item2</option>
        <option value="3">Item3</option>
        <option value="4">Item4</option>
        <option value="5">Item5</option>
    </select>
    Quantity:
    <input type="text" name="stock_plus []" /><br/>
</div>

This div is repeated 10 times or more, and I use that form to let user add inventory count of selected product 此div重复10次或更多次,我使用该表格让用户添加所选产品的库存数量

Now when I tried to used PHP to insert rows on my table : 现在,当我尝试使用PHP在表中插入行时:

1-Method 1 : 1方法1:

PHP Code: PHP代码:

$product = $_POST['product_id']; $stock_plus = $_POST['stock_plus'];
$Date = $_POST['trans_date']; $limit = count($stock_plus);
for($i=0;$i<$limit;$i++) {
    $product[$i] = mysql_real_escape_string($product[$i]);
    $stock_plus[$i] = mysql_real_escape_string($stock_plus[$i]);
}

$query = "INSERT INTO table (trans_date, product_id, stock_plus)
VALUES ('".$Date."','".$product[$i]."','".$stock_plus[$i]."')";
if(mysql_query($query))
    echo "$i successfully inserted.<br/>";
else
    echo "$i encountered an error.<br/>";

I got : Notice: Undefined offset: 2... and not all the rows are inserted. 我得到了:注意:未定义的偏移量:2 ...并没有插入所有行。

Method 2 : 方法2:

PHP Code: PHP代码:

$trans_date=$_POST['trans_date']; $sql = 'INSERT INTO table
(trans_date, product_id, stock_plus) VALUES ';

for($i = 0;$i < count($_POST['product_id']);$i++) {
    $sql .= "('$trans_date','".$_POST['product_id'][$i]."','".$_POST['stock_plus']i]."')";
    if($i != count($_POST['product_id']) - 1)
    {
        $sql .= ',';  
    } 
}
if (!mysql_query($sql))   {   die('Error: ' . mysql_error());   }

Here no errors but not all the rows are inserted. 这里没有错误,但是没有插入所有行。 Can you help me please to see clearier what I missed,regards 您能帮我看看我想念的更清楚吗?

Additional : 其他:

thanks Travesty3, I look too into myhtml for errors, My HTML body looks exactly like: 谢谢Travesty3,我也仔细研究了myhtml中的错误,我的HTML正文看起来像这样:

<body>
<form action="../inserts/stock_insert.php" method="post">
<div>
<!-- JS Datepicker -->
Date: <input onclick="ds_sh(this);" name="trans_date" readonly="readonly" style="cursor: text" />
<br/>
<!-- User should select product -->
Product:<select name="product_id []">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4">Item4</option>
<option value="5">Item5</option>
</select>
<!-- User must enter the quantity -->
Quantity: <input type="text" name="stock_plus []" /><br/>
</div> 
<input type="submit" name="Submit" value="Submit" />
</form>
</body>

the div is repeated 10 times, so the result I should have in my DB table is 10 rows insterted (trans_date, product_id(FK),stock_plus) When echoing Mysql errors, there are none. div重复了10次,所以我应该在数据库表中得到的结果是10行(trans_date,product_id(FK),stock_plus),当回显Mysql错误时,没有错误。

You are performing your query outside of your loop, so only one insert is being performed. 您正在循环外执行查询,因此仅执行一次插入。 Move your query inside your for-loop. 将查询移到for循环内。

Try this: 尝试这个:

$product = $_POST['product_id'];
$stock_plus = $_POST['stock_plus'];
$Date = mysql_real_escape_string($_POST['trans_date']);
$limit = count($stock_plus);

for ($i=0; $i<$limit; $i++)
{
    $product[$i] = mysql_real_escape_string($product[$i]);
    $stock_plus[$i] = mysql_real_escape_string($stock_plus[$i]);

    if(mysql_query("INSERT INTO table (trans_date, product_id, stock_plus) VALUES ('{$Date}', '{$product[$i]}', '{$stock_plus[$i]}')"))
        echo "$i successfully inserted.<br/>";
    else
        echo "$i encountered an error.<br/>";
}

First of all, and most importantly, before you do anything fix the massive security hole in both methods. 首先,最重要的是,在执行任何操作之前,请先修复这两种方法中的大量安全漏洞。 You are allowing unsanitised user input to be inserted directly into an SQL query which allows SQL injection. 您允许将未经过滤的用户输入直接插入允许SQL注入的SQL查询中。 You must, without exception, always sanitise input from the user. 您必须无一例外地始终清除用户的输入。 To do this pass all of the variables through mysql_real_escape_string before you put them in your query. 为此,在将所有变量放入查询之前,请将所有变量传递给mysql_real_escape_string。 You have sanitised some input, but you dont for example sanitise $date. 您已经清理了一些输入,但是没有例如清理$ date。 I assume this is because it is coming from a date picker and you don't see the risk. 我认为这是因为它来自日期选择器,您看不到风险。 You should never rely on anything client-side for security because it can always be changed - always include server side validation and sanitisation. 您绝对不应该依赖任何客户端来保证安全,因为可以随时对其进行更改-始终包括服务器端验证和清除。 A malicious user could, for example, modify the date through their own javascript before posting it to your server. 例如,恶意用户可以在将其发布到您的服务器之前,通过自己的JavaScript修改日期。

However, given you are doing the same query multiple times, I would strongly recommend you start using MySQLi or PDO and prepared statements. 但是,鉴于您多次执行相同的查询,因此强烈建议您开始使用MySQLi或PDO并准备好语句。 When you use a prepared statement it is pre-compiled, which means you get a big performance boost when you re-run the same query but only with different data. 当使用准备好的语句时,该语句将被预编译,这意味着当您重新运行相同的查询但仅使用不同的数据时,可以大大提高性能。 I would strongly recommend you look that up. 我强烈建议您查一下。

The reason you are getting an undefined offset is because the array index 2 does not exist in your array. 之所以得到未定义的偏移量,是因为数组索引2在您的数组中不存在。 Your code looks a bit confusing to me - your for loop excludes your mysql_query. 您的代码对我来说有些混乱-您的for循环不包含mysql_query。 You would need to do the mysql_query within the for loop. 您将需要在for循环中执行mysql_query。 You would be better doing a foreach round the product_ids eg 您最好在product_ids处进行一次foreach循环,例如

$i = -1;
$product_ids = $_POST['product_id'];
$stock_plus = $_POST['stock_plus'];
$date = mysql_real_escape_string($_POST['trans_date']);
foreach($product_ids as $product_id) {
    $product_id = mysql_real_escape_string($product_id);
    $stock = mysql_real_escape_string($stock_plus[++$i]);
    mysql_query("INSERT INTO table (trans_date, product_id, stock_plus) VALUES ({$date}, {$product_id}, {$stock})");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM