mysql_query to PDO and prepared statements

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 21:17:58

PHP provides quite a few convenience functions that do a lot of the stuff you're doing by hand.

  • PDO supports named parameters in your SQL statements, so you can then pass a key/value array where the keys match your named parameter placeholders.
  • The join() function is very useful for building comma-separated lists.
  • Many functions exist to manipulate arrays.
  • Some functions allow you to give a callback (which can be a closure in PHP 5.3), to process arrays dynamically.

Example (not tested):

function insertFields($fields) {
    $columns = join(",", array_map(
        function($col) { return "`".preg_replace("/`/gu","``",$col)."`"}, 
        array_keys($fields)));

    $params = join(",", array_map(
        function($col) { return ":".preg_replace("/[`\s]/gu","",$col)},
        array_keys($fields)));

    $stdquery = "INSERT INTO masteridx ({$columns}) VALUES ({$params})";
    $stmt = $pdo->prepare($stdQuery);
    $stmt->execute($fields);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!