如何使用php将数据从数组插入到mysql中

时间:2018-05-02 08:03:13

标签: php

我有这个firstname和lastname数组,我想将名字插入数据库,数组看起来像这样:

TelemetryConfiguration configuration = new TelemetryConfiguration();
configuration.InstrumentationKey = "9d3ebb4f-7a11-4fb1-91ac-7ca8a17a27eb";

QuickPulseTelemetryProcessor processor = null;

configuration.TelemetryProcessorChainBuilder
    .Use((next) =>
    {
        processor = new QuickPulseTelemetryProcessor(next);
        return processor;
    })
    .Build();

var QuickPulse = new QuickPulseTelemetryModule();
QuickPulse.Initialize(configuration);
QuickPulse.RegisterTelemetryProcessor(processor);

我有这个代码来插入它们但是它不起作用

Array(
[0] => firstname1
[1] => firstname2
[2] => firstname3
)

Array(
[0] => lastname1
[1] => lastname2
[2] => lastname3
)

打印数组中的字符串不是一个问题,但是当我插入它时会出错 注意:第259行的D:\ xampp \ htdocs \ SPAC_Online_Grading_System \ system \ pages \ addfunction.php中的数组到字符串转换 我怎样才能使它发挥作用?

3 个答案:

答案 0 :(得分:0)

您的循环条件错误,请更改:

for($i=0, $count = count($fname); $i < $count; $i++)

致:

for($i=0; $i < count($fname); $i++)

另请注意,您很容易受到SQL注入攻击,您应该准备并绑定您的语句

答案 1 :(得分:0)

你循环错了。试试这段代码:

 <?php 
 $fname = $_POST['fname'];
 $lname = $_POST['lname'];

 for($i=0; $i < count($fname); $i++){

   $firstname = $fname[$i];
   $lastname = $lname[$i];

   $query = mysqli_query($con,"INSERT INTO 
      persons(firstname,lastname)VALUES('$firstname','$lastname')");
 }
 ?>

答案 2 :(得分:0)

    for($i=0; $i<count($fname);$i++){
        $lastname = $lname[$i];
        $firstname = $fname[$i];
        $stmt = $conn->prepare($con,"INSERT INTO persons(firstname,lastname)VALUES(?,?)");
        $stmt->bind_param("ss", $firstname, $lastname);
        $stmt->execute();
    }

试试这段代码。从sql注入(使用prepare语句)并修复for循环是安全的。