且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将用mysql PHP多行

更新时间:2023-12-04 13:06:16

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

  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.