将未知的行数到MySQL使用PHP [英] Insert unknown number of rows into MySQL using PHP

查看:92
本文介绍了将未知的行数到MySQL使用PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用PHP来插入一个未知的行数到MySQL。这是它应该如何工作的:

I am trying to insert an unknown number of rows into MySQL using PHP. This is how it should work:


  1. 的Javascript解析HTML DOM来创建基于CSS类的多维数组。阵列将有一定数目的对应于具有类元素的行数(或子阵列)的。 (这可能是任何整数0或更大......很明显)。

  1. Javascript parses HTML DOM to create a multi-dimensional array based on a css class. The array will have a certain number of rows(or sub-arrays) corresponding to the number of elements that have that class. (This could be any integer 0 or greater... obviously).

然后,在一个JavaScript事件,阵列发送一个PHP脚本。

Then, on a JavaScript event, the array is sent to a PHP script.

PHP脚本将插入来自阵列数据到MySQL。

The PHP script will INSERT data from the array into MySQL.

我的问题是,我不知道该怎么告诉我的PHP脚本多少个值的数组中为止。我不知道如何在不知道将要被插入的值(或行)的数量写的mysql_query()。

My problem is that I don't know how to tell my PHP script how many values are in the array. And I don't know how to write the mysql_query() without knowing the number of values (or rows) that should be inserted.

推荐答案

您可以一次到MySQL插入多行:

You can insert more than one row at a time to MySQL:

INSERT INTO表1(列1,列2,...)VALUES(value_col1,value_col2),(value2_col1,value2_col2),...;

在PHP中,你可以通过行循环,并将它们添加到SQL字符串构建查询:

In PHP, you can build your query by looping through rows and adding them to the SQL string:

$sql = "INSERT INTO table1 (col1, col2) VALUES ";
foreach($rows as $i=>$row) {
    if ($i>0) {
        $sql .= sprintf(",(%s,%s)", $row["col1_value"], $row["col2_value"]);
    } else {
        $sql .= sprintf("(%s,%s)", $row["col1_value"], $row["col2_value"]);
    }
}
mysql_query($sql);

您必须确保正确地逃避自己的价值取决于你实际上插入。

You have to be sure to properly escape your values depending upon what you're actually inserting.

这篇关于将未知的行数到MySQL使用PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆