将用mysql PHP多行 [英] Insert Multiple rows of mysql using php

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

问题描述

我如何使用PHP插入多个数据MySQL数据库。我试着使用循环,但没有运气。

  //阵列的输入框
$ ID1 =阵列($ AA1,AA2 $,$ AA3,AA4 $,$ AA5,$ AA6,$ AA7);
$ timeRank1 =阵列($ A3,A6 $,$ A9,A12 $,$ A15,A18 $,$ A21);
为($ I = 0; $ I< 7; $ I ++){
require_once(connection.php);
$ a = $ ID1 [$ i];
$ B = $ timeRank1 [$ i];
$ SQL =INSERT INTO的结果(ID,swim_rank)
VALUES('$ A。','$ B。');


解决方案

只是建立在一个循环您的查询,然后执行它当循环竞争

  require_once(connection.php);
$ SQL =INSERT INTO的结果(ID,swim_rank)VALUES
为($ I = 0; $ I< 7; $ I ++){
    。$ SQL =('。$ ID1 [$ i]。','$ timeRank1 [$ i]。');
}
$ SQL = RTRIM($ sql中,'');
//运行查询这里

您还会注意到我动了你的包括循环之外你的数据库的连接。无需反复打这通电话。

此外,还要确保你要么难逃被插入的值,或使用parametized查询,让您的插入,以防止SQL注入。

How can I insert multiple data to mysql database using php. I tried using for loop but no luck.

//array of input boxes
$id1=array($aa1,$aa2,$aa3,$aa4,$aa5,$aa6,$aa7);
$timeRank1=array($a3,$a6,$a9,$a12,$a15,$a18,$a21);
for ($i = 0; $i < 7; $i++) {
require_once("connection.php");
$a = $id1[$i];
$b = $timeRank1[$i];
$sql = "INSERT INTO results (id,swim_rank)
VALUES ('".$a."','".$b."')";

解决方案

Just build your query in a loop and then execute it when the loop is compete

require_once("connection.php");
$sql = "INSERT INTO results (id,swim_rank) VALUES ";
for ($i = 0; $i < 7; $i++) {
    $sql .= "('".$id1[$i]."','".$timeRank1[$i]."'),";
}
$sql = rtrim($sql, ',');
// run your query here

You'll also notice I moved your include of your DB connection outside of the loop. No need to repeatedly make that call.

Also, make sure you either escape those values being inserted or use parametized queries to make your inserts to protect against SQL injections.

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

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