duan0513 2014-08-24 13:49
浏览 45
已采纳

php pdo使用函数插入数据

I'm trying to insert the datas with php & pdo. I'm writing this below codes for insert function and I call them like this php_insert_data("admin", array( 'user_name', 'user_pwd', 'user_email', 'profile_created_on' ), array( 'Administrator', '123456', 'admin@gmail.com', 'date here' ));. I tried this below code. But it doesn't insert the datas into db table. How do I pass these above column names and column values properly?

function php_insert_data($table_name, array $field_name, array $field_values)   
    {
        global $dbh;
        foreach($field_name as $f_names)
        {
            $transform_array_fnames[] = $f_names;
        }
        foreach($field_values as $f_values)
        {
            $transform_array_fvalues[] = $f_values;
        }
        $comma_fnames = implode(',', $transform_array_fnames);
        $comma_fvalues = implode(',', $transform_array_fvalues);
        $insert_query = $dbh->prepare("INSERT INTO $table_name SET $comma_fnames = $comma_fvalues");
        $insert_query->bindValue(':comma_fvalues', $comma_fvalues);
        $insert_query->execute();
    }
  • 写回答

1条回答 默认 最新

  • dsjpqpdm620596 2014-08-24 13:58
    关注

    Ultimately your prepared query will look something like:

    INSERT INTO admin SET user_name = Administrator
    

    You are missing the quotes around Administrator which is not a valid column in the table. Hence you will get an SQL error. You can see this by turning error reporting on and up.

    Using variables in your queries makes them vulnerable to injection, so it's generally something to avoid -- even if the variables come from a trusted location.

    You are using bindValue incorrectly. For it to work you would need a single field in the query named :comma_fvalues.

    You can rewrite this as:

    $field_value_tokens = array_fill(0, count($f_values), "?");
    $field_value_tokens_commas = implode(",", $field_value_tokens);
    $insert_query = $dbh->prepare("INSERT INTO $table_name ($comma_fnames)
        VALUES ($field_value_tokens_commas)");
    $insert_query->execute($f_values);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?