从阵列MySQL和PHP构建插入查询 [英] Build insert query from array MySQL and PHP

查看:111
本文介绍了从阵列MySQL和PHP构建插入查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写在PHP一个小型Web服务,我有一点麻烦我的头围绕以下情形。

I'm writing a small web service in PHP and I'm having a bit of trouble getting my head around the following scenario.

我的计划是能够数组数据发送到一个功能,那么这将构建对MySQL运行查询。在阵列I计划的关键是列名,并将该值是将在该列中的值..即

My plan is to be able to send an array of data to a function, which would then build a query for MySQL to run. In the array I plan for the key to be the column name, and the value to be the value going in to the columns.. i.e.

$myData = array('userName'=>'foo','passWord'=>'bar');
$myClass = new users();

$myClass->addUser($myData);

然后,在我的功能我目前有:

Then, in my function I currently have:

function addUser($usrData){
   foreach($usrData as $col => $val){

      // This is where I'm stuck..

   }
}

基本上,我想知道我怎么能分开键和值,这样我的查询将变成:

Basically, I am wondering how I can separate the keys and values so that my query would become:

INSERT INTO `myTable` (`userName`,`passWord`) VALUES ('foo','bar');

我知道我大概可以做这样的事情:

I know I could probably do something like:

function addUser($usrData){
   foreach($usrData as $col => $val){
      $cols .= "," . $col;
      $values .= ",'".$val."'";
   }
}

不过,我认为有可能是一个更优雅的解决方案。

But I thought there might be a more elegant solution.

这可能是很简单的东西,但我从来没有碰到这个才恍然大悟,于是我将是任何帮助和指导表示感谢。

This is probably something really simple, but I have never came across this before, so I would be grateful for any help and direction..

谢谢,

戴夫

推荐答案

试试这个:

function addUser($usrData) {
   $count = 0;
   $fields = '';

   foreach($usrData as $col => $val) {
      if ($count++ != 0) $fields .= ', ';
      $col = mysql_real_escape_string($col);
      $val = mysql_real_escape_string($val);
      $fields .= "`$col` = $val";
   }

   $query = "INSERT INTO `myTable` SET $fields;";
}

这篇关于从阵列MySQL和PHP构建插入查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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