如何使用数组和内爆使这样的查询?

时间:2017-04-25 04:29:52

标签: php mysql

$data = array('Cardinal', 'Tom B.','tom@email.com');
$stmt = mysqli_prepare("INSERT INTO $table  (username,password,email) VALUES ($data)");

3 个答案:

答案 0 :(得分:0)

希望这会帮助你。在这里,我们在$data数组的字符串的开头和结尾附加单引号,然后使用,

将该数组包含在内
<?php

$data = array('Cardinal', 'Tom B.','tom@email.com');
//adding single quotes
$data=array_map(function($value){
    return $value="'$value'";
}, $data);
//imploding array with ,
$data=  implode(",", $data);
echo $query="INSERT INTO $table  (username,password,email) VALUES ($data)";
$stmt = mysqli_prepare($query);

输出: of echo $query;

INSERT INTO   (username,password,email) VALUES ('Cardinal','Tom B.','tom@email.com')

答案 1 :(得分:0)

我认为最简单的方法就是:

$data = implode("','", ['Cardinal', 'Tom B.', 'tom@email.com']);
$stmt = mysqli_prepare(
    "INSERT INTO $table (username,password,email) VALUES ('$data')"
);

答案 2 :(得分:0)

您只需使用

即可
"INSERT INTO $table (username,password,email) VALUES ('$data[0]','$data[1]','$data[2]')"