<?php declare(strict_types=1); ini_set('display_errors', 'On'); ini_set('error_reporting', E_ALL); /** * 构造INSERT语句模板(仅用于预处理,不可直接执行) * * @param array $data 要插入的数据(键值对格式),示例:['name' => '张三', 'sex' => '男', 'birth' => 2003] * @return string INSERT语句模板,示例:INSERT INTO `user` SET `name` = :name, `sex` = :sex, `birth` = :birth */ function get_insert_sql(array $data): string { $arr = []; foreach ($data as $column => $value) { $arr[] = "`$column` = :$column"; } $set = implode(', ', $arr); return "INSERT INTO `user` SET $set"; } // 要插入的数据 $data = [ 'name' => '张三', 'sex' => '男', 'birth' => 2003, ]; echo get_insert_sql($data); // INSERT INTO `user` SET `name` = :name, `sex` = :sex, `birth` = :birth
Copyright © 2024 码农人生. All Rights Reserved