如何使用php在mysql中插入多个值 [英] How to insert the multiple values in mysql using php

查看:59
本文介绍了如何使用php在mysql中插入多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 列的 mysql 表persons",

i have the mysql table 'persons' with 3 columns as,

Name   Salary  Profession

我使用 php get 方法发送 3 个带值的参数,

I am sending 3 parameters with values using php get method as,

 $name = raj|lokesh|amar
 $salary = 10000|20000|30000
 $job = telecom|marine|shipyard

我必须将它们插入到人员"表中,

I have to insert them in 'persons' table as,

Name     Salaray  Profession

raj      10000     telecom
lokesh   20000     marine
amar     30000     shipyard

谁能告诉我我该怎么做?

Can any one tell me how can i do this?

推荐答案

您可以使用 爆炸 功能.使用我的小演示,您肯定可以在您的情况下使用它:

You can turn string into an array using the explode function. You can surely use this in your case, using my little demonstration:

$name = "raj|lokesh|amar";
$salary = "10000|20000|30000";
$job = "telecom|marine|shipyard";

您只需设置变量.现在把它们变成 exploded 数组:

You just set the variables. Now turn them into exploded arrays:

$name = explode("|", $name);
$salary = explode("|", $salary);
$job = explode("|", $job);

您基本上想要获取字符 | 之间的所有单词并将每个单词转换为数组项,因此每个单词都有自己的索引.

You basically want to get all of the words between the character | and turn each word into an array item, so each word will have it's own index.

现在,$name[0](第一个数组索引),

now, $name[0] (the first array index),

echo $name[0]; // echoes 'raj'
echo $name[1]; // echoes lokesh'
echo $job[3]; // echoes 'shipyard';

现在你必须循环遍历这些数组并将其插入到查询中:

And now you have to loop trough these arrays and insert it in the query:

for ($i = 0; $i < count($name); $i++) {
    echo $name[$i];
}

所以最终的解决方案将如下所示:

for ($i = 0; $i < count($name); $i++) {
    $query = $pdoObject->prepare("INSERT INTO table (name, salary, profession) VALUES (:name, :salary, :jobs)");
    $query->execute(array(
        ":name" => $name[$i], 
        ":salary" => $salary[$i], 
        ":jobs" => $jobs[$i]
    );
}

这篇关于如何使用php在mysql中插入多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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