如何使用 PHP 将数组插入到 mysql 中?

发布于 2024-11-03 01:41:42 字数 1545 浏览 0 评论 0原文

我有一个包含 11 列的复杂表单。至于排数,根据学生人数的不同,排数从 20 到 50 不等。我通过 php 脚本 将数据捕获为数组。每列生成一个数组。例如,在表单中,我有 fname[]、lname[]、exam_no[] 等,因此当提交表单时,比如说 10 行,我最终会得到 11 个数组,每个数组有 10 个条目,其中我通过一些 php 函数 来删除空元素。正在生成数组,没有任何问题。

我想使用循环将这些数组中的数据插入到 mysql 中。基本上,lname array 将包含第一个名称列的所有first_name,lname array 将提供数据库的last_name 列,依此类推。

我什至无法开始构建 MySQL 查询 来插入数据,我非常熟悉“普通”插入,其中包含列和值,并且您已经知道将插入多少行,大多数情况下每个插入一行。

甚至可以使用 PHP 循环 和这么多数量的列来填充 MySQL 数据库表 的插入,并可以灵活地插入任意数量的行每次用户输入学生数据时都会有所不同?

更新

这是我想出的。它有效,但不符合预期!

数组如 $fname[]、lname[] 等 然后我将主数组构建为 $master_array=array['$fname, $lname];

$sql = "INSERT INTO testing (date, fname, lname) VALUES ";
foreach($master_array as $subarray) {
   $sql .= "(NOW( )";
   echo 'A nested array: '.$subarray.'<br />';
   foreach($subarray as $value) {
      $sql .= ", '$value'";
      echo 'A Name: '.$value.'<br />';
   }
   $sql.= "), ";
}
$sql = substr($sql,0,-2); //removes extraneous , at end.
echo $sql;
$result=mysqli_query($dbc, $sql)
or die('Query Failed!');
?>

由于我的查询涉及连接小段代码,因此我在构建后打印它以查看要做什么被插入。看起来是这样的;

INSERT INTO table (date, fname, lname) VALUES (NOW( ), 'Andrew', 'Alex'), (NOW( ), 'Peterson', 'Marlon')

正如我怀疑的那样,它将所有名字插入第一行,将所有姓氏插入第二行。所需的结果是在名字列中插入名字,在第二个名字列中插入名字。所以现在我需要一种方法将一个数组的所有元素插入到单个列中,然后移动到第二个数组并将其插入到下一列中。这听起来很复杂,我想知道它是否可行!让我接受一下php语言大师的教育吧,因为我是一个中级或者可能是全新的新手!

I have a complex form that has 11 columns. As for rows they will vary from about 20 to 50 depending on number of students. I am capturing data via a php script as arrays. Each column produces an array. Example, from the form I have fname[], lname[], exam_no[] etc so when the form is submitted with say, 10 rows, I end up with 11 arrays each with 10 entries, which I pass through some php function to remove empty elements. The arrays are being generated with no issues.

I want to insert data from these arrays into mysql using a loop. Basically, lname array will have all first_name for the first name column, lname array will feed the last_name column of the db and so on.

I am just unable to even start constructing the MySQL query to insert the data, I am well conversant with the 'ordinary' insert where you have columns and values and you already know how many rows will insert, mostly one row per insert.

Is is even possible to populate a MySQL Database Table with an insert using a PHP loop and with this many number of columns and making it flexible to insert any number of rows as that will vary each time a user enters student data?

UPDATE

This is what I came up with. It works but NOT as desired!

Arrays are coming like $fname[], lname[] etc
Then I built the master array to be $master_array=array['$fname, $lname];

$sql = "INSERT INTO testing (date, fname, lname) VALUES ";
foreach($master_array as $subarray) {
   $sql .= "(NOW( )";
   echo 'A nested array: '.$subarray.'<br />';
   foreach($subarray as $value) {
      $sql .= ", '$value'";
      echo 'A Name: '.$value.'<br />';
   }
   $sql.= "), ";
}
$sql = substr($sql,0,-2); //removes extraneous , at end.
echo $sql;
$result=mysqli_query($dbc, $sql)
or die('Query Failed!');
?>

Since my query involves conactinating small pieces of code, I was printing it after its built to see what is to be inserted. It looked like so;

INSERT INTO table (date, fname, lname) VALUES (NOW( ), 'Andrew', 'Alex'), (NOW( ), 'Peterson', 'Marlon')

As I suspected, it inserts all first names in the first row, and all last names in the second row. The desired result is to insert first names in the first-name column and second names in the second name column. So now I need a way to insert all elements of one array into a single column and then move to the second array and insert it in the next column. That sounds complex, and I wonder if it's doable! Let me be educated by the masters of the php language as I am an intermediate or may be brand new newbie!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

玩心态 2024-11-10 01:41:42

按学生对信息进行分组不是更好吗?

例子:

<form...>
<? foreach ($students as $id => $info) : ?>
  <input type="text" name="fname;<=$id;?>" value="<?=$info['fname'];?>" />
  <input type="text" name="lname;<=$id;?>" value="<?=$info['lname'];?>" />
  etc
<? endforeach ?>
</form>

(我在这里使用 PHP 短标签)

然后,当您处理表单时:

$update = array();

foreach ($_POST as $key => $value) {
  // key will look like: fname;1, fname;2, etc
  // so, split it on the ; sign to separate the field name from the student's id
  $data = explode(';',$key);

  // result:
  // $data[0] = fname, lname, etc
  // $data[1] = 1, 2, etc
  // you can add some checks to make sure that this field is valid
  // and that the id is in fact a valid id (number, > 0, etc)

  // sanitize data (however you want, just an example)
  $value = mysql_real_escape_string(trim($value));

  // now add it to the update array, grouped by student id
  $update[$data[1]][$data[0]] = $value;

  // result:
  // $update[1]['fname'] = 'First name student 1';
  // $update[1]['lname'] = 'Last name student 1';
  // $update[2]['fname'] = 'First name student 2';
  // $update[2]['lname'] = 'Last name student 2';
  // etc
}

之后,遍历更新数组:

foreach ($update as $id => $info) {
  $sql = "UPDATE students
          SET fname = '".$info['fname']."', lname = '".$info['lname']."'
          WHERE id = $id";
  mysql_query($sql);
}

Isn't it better to group the information by student?

Example:

<form...>
<? foreach ($students as $id => $info) : ?>
  <input type="text" name="fname;<=$id;?>" value="<?=$info['fname'];?>" />
  <input type="text" name="lname;<=$id;?>" value="<?=$info['lname'];?>" />
  etc
<? endforeach ?>
</form>

(I'm using PHP short tags here)

Then, when you process the form:

$update = array();

foreach ($_POST as $key => $value) {
  // key will look like: fname;1, fname;2, etc
  // so, split it on the ; sign to separate the field name from the student's id
  $data = explode(';',$key);

  // result:
  // $data[0] = fname, lname, etc
  // $data[1] = 1, 2, etc
  // you can add some checks to make sure that this field is valid
  // and that the id is in fact a valid id (number, > 0, etc)

  // sanitize data (however you want, just an example)
  $value = mysql_real_escape_string(trim($value));

  // now add it to the update array, grouped by student id
  $update[$data[1]][$data[0]] = $value;

  // result:
  // $update[1]['fname'] = 'First name student 1';
  // $update[1]['lname'] = 'Last name student 1';
  // $update[2]['fname'] = 'First name student 2';
  // $update[2]['lname'] = 'Last name student 2';
  // etc
}

After that, go through the update array:

foreach ($update as $id => $info) {
  $sql = "UPDATE students
          SET fname = '".$info['fname']."', lname = '".$info['lname']."'
          WHERE id = $id";
  mysql_query($sql);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文