我想制作一个功能,可以按功能打印出php中的插入查询。题 :

时间:2018-11-02 06:27:24

标签: javascript php mysql

  

表名称:emp
  列名称:(emp_name,emp_salry,emp_city,emp_country)
  列值:(“ ali”,“ 2000”,“ Multan”,“巴基斯坦”)

我有一个数组

$info = array(
  'emp_name'=>'Ali',
  "emp_salery"=> '2000',
  "emp_city"=> 'Multan',
  "emp_country"=> "Pakistan"
);

我想调用一个函数

insert($info,"emp");

在浏览器中返回答案,如下所示

insert into emp (emp_name,emp_salery,emp_city,emp_country) value("ali",'2000','multan', "Pakistan");

使用循环的解决方案是什么?

4 个答案:

答案 0 :(得分:0)

尝试

   $info = array(
             'emp_name'=>'Ali',
             "emp_salery"=> '2000',
             "emp_city"=> 'Multan',
            "emp_country"=> "Pakistan");
    $tblname = "emp";

    print_r(insert($info,$tblname));

    function insert($info,$tblname){
      $q = "insert into ".$tblname ."(";
      $keys ="";
      $val = "";
      foreach($info as $key=>$value){
        $keys .= $key.",";
        $val .= "'".$value."',"; 
      }
      $keys = rtrim($keys, ',');
      $val =rtrim($val, ',');
      $q .= $keys.") value(".$val.")";
      return $q;
    }

输出

insert into emp(emp_name,emp_salery,emp_city,emp_country) value('Ali','2000','Multan','Pakistan')

答案 1 :(得分:0)

function insert($info,$table){
    $qry    = "";
    $fields = "";
    $values = "";
    foreach($info as $field => $value){
        $fields.=$field.",";
        $values.="'".$value."',";
    }
    $qry.="insert into ".$table." (".rtrim($fields,',').") value (".rtrim($values,',').")";

    return $qry;
}

$info = array(
       "emp_name"   => "Ali",
       "emp_salery" => "2000",
       "emp_city"   => "Multan",
       "emp_country"=> "Pakistan"
);

echo insert($info,"emp");

答案 2 :(得分:0)

you can use the following function
$array_col=array_keys($info);
$array_val=array_values($info);

function get_insert_syntax($table,$info){
$cols="insert into $table(";
$vals="values (";
for($i=0;$i<count($info);$i++)
{
    if($i<(count($a)-1)){
        $cols.=$array_col[$i].',';
        $vals.="'".$array_val[$i]."',";
    }
    else{
        $cols.=$array_col[$i].')';
        $vals.="'".$array_val[$i]."')";
    }

}
return $cols.' '.$vals;
}

答案 3 :(得分:0)

$info = array(
  'emp_name'=>'Ali',
  "emp_salery"=> '2000',
  "emp_city"=> 'Multan',
  "emp_country"=> "Pakistan"
);


$table="emp";
function get_insert_syntax($table,$info){
    $array_col=array_keys($info);
$array_val=array_values($info);

$cols="insert into $table(";
$vals="values (";
for($i=0;$i<count($info);$i++)
{
    if($i<(count($info)-1)){
        $cols.=$array_col[$i].',';
        $vals.="'".$array_val[$i]."',";
    }
    else{
        $cols.=$array_col[$i].')';
        $vals.="'".$array_val[$i]."')";
    }

}
echo $cols.' '.$vals;
}
 get_insert_syntax($table,$info);