简体   繁体   English

为MySQL中的INSERT查询声明php变量

[英]Declare php variables for INSERT query in MySQL

How to declare php variables that will consist the mysql query columns and values properly? 如何声明将正确组成mysql查询列和值的php变量? The thing is obviously in quotations, I tried several combination witn no success. 事情显然是在报价中,我尝试了几种组合但均未成功。

This is the query declared in php: 这是在php中声明的查询:

$query = "INSERT INTO table1(pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8) VALUES ('$q[1]','$q[2]','$q[3]','$q[4]','$q[5]','$q[6]','$q[7]','$q[8]')"; 

This is my wrong variables in php: (two wrong approaches) 这是我在php中的错误变量:(两种错误方法)

$pt_all = pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8;

for($i=1;$i<9;$i++) {
    $q_all .= '$q[$i]',;
}

This is made in order to place the holder variables into the sql query in php: 这样做是为了将Holder变量放入php中的sql查询中:

$query = "INSERT INTO table1($pt_all) VALUES ($q_all)"; 

And make it easier and shorter. 并使其更容易,更短。 Is there maybe other better technique? 还有其他更好的技术吗?

FIrst of all, do not use mysql_* functions , since those are deprecated. 首先, 不要使用mysql_ *函数 ,因为这些函数已被弃用。 Use mysqli_* or PDO. 使用mysqli_ *或PDO。 That said, you probably need something like this: 也就是说,您可能需要这样的东西:

$fields = "pt".join(", pt",array_keys($q)); //pt1, pt2, pt3, ..
$values = "'".join("','",array_values($q))."'"; //values

echo "INSERT INTO ({$fields}) VALUES ({$values})";

Obviously, you will need to adjust this to fit your requirements, but this should give you good sense on array manipulation. 显然,您将需要对此进行调整以满足您的要求,但这应该使您对数组操作有很好的了解。

start with an associative array. 从关联数组开始。 As an example, I'll use fruit.. 例如,我将使用水果。

$array = array("banana" => "yellow", "apple" => "red", "kiwi" => "green");

Go through and make the strings "banana, apple, kiwi" and "yellow, red, green" 仔细检查并制作字符串“香蕉,苹果,猕猴桃”和“黄色,红色,绿色”

$fields = array();
$values = array();
foreach($array as $key => $val){
    $fields[] = $key;
    $values[] = $val;
}

Now concatenate into a string to be used as SQL 现在连接成一个字符串以用作SQL

$query = 'INSERT INTO table1("'.implode('", "', $fields).'") ';
$query .= 'VALUES ("'.implode('", "', $values).'");';
echo $query; // "INSERT INTO table1("banana", "apple", "kiwi") VALUES ("yellow", "red", "green");

Hope that's what you're looking for. 希望这就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM