drxpt06820 2015-11-13 13:42
浏览 35
已采纳

如何在数据库类中创建插入函数以插入具有多个coloumns和多个值的新记录(使用PDO)?

the problem is my function insert inserts my record in two rows.

this is my code to connect to database in a file named :

connect.php

<?php
try{
$db = new PDO("mysql:host=localhost;dbname=NPD" , "root" , "");

echo "connected";
}
catch(Exception $e){
    echo $e->getMessage();
}

this is my database class in a file

database.php

<?php

require 'connect.php';
class DB {
public function insertInto($tableName , $info){
        global $db;
        foreach ($info as $coloumnName => $coloumnValue) {          
            $stmt = $db->prepare("INSERT INTO $tableName ($coloumnName) VALUES ('$coloumnValue') ");
            $stmt->execute();   
        }
    }
}
$da = new DB;
$da->insertInto('tableOne',array('name' => 'lolo' , 'deg' => '100'));

the result in the database is : tableOne

how can to make the insert function inserts my record in one row.

note : i want to insert any number of columns and values.

  • 写回答

4条回答 默认 最新

  • dongzan2740 2015-11-13 13:57
    关注

    try to do something like this:

    $arr = array('name' => 'lolo' , 'deg' => '100');
    $columns=array_keys($arr);
    $values=array_values($arr);
    
               $str="INSERT INTO $tableName (".implode(',',$columns).") VALUES ('" . implode("', '", $values) . "' )";
               echo $str;//your sql
             //  $stmt = $db->prepare($str);
             //  $stmt->execute();//uncomment to execute
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?