使用PHP和MySql创建通用更新功能

i'm trying to make an Update function that work with any database using PHP & MySQL "PDO" Connection" but it didn't work .. here's the Code

<?php
require_once "PDO-Connection.php";
function update ($table, $data, $id, $pdo)
{
    foreach($data as $column => $value)
    {
    $sql = "UPDATE {$table} SET ({$column}) VALUE (:{$column}) 
    WHERE (ID) = (:{$id});
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(':'.$column => $value));
    }
}
?>

Call to this Function

update("accounts", array("fname" => "ahmed90"), 1, $pdo);

i have (accounts) table & (fname, ID) Fields

Thanks in Advance

The SQL code you've written inside UPDATE isn't correct. It should be:

foreach($data as $column => $value)
    {
    $stmt = $pdo->prepare(" update $table set $column = ? where $id = ? ");
    $stmt->execute(array($column, $id);
    }

As a side-note, I don't think you really need to create a function to update database table rows. Every update you perform in the future might have a set of preconditions, or may require additional computation, which means you can't use update function in every case. Furthermore, if you have more than one column to update, the $data array would have multiple entries and also the foreach loop runs more than once. This means an SQL update is performed multiple times on the same row which could mean performance degradation.

this function works fine:

<?php
require_once "PDO-Connection.php";

function update ($table, $data, $id, $pdo)
{
    $setPart = array();
    $bindings = array();

    foreach ($data as $key => $value)
    {
        $setPart[] = "{$key} = :{$key}";
        $bindings[":{$key}"] = $value;
    }

    $bindings[":id"] = $id;

    $sql = "UPDATE {$table} SET ".implode(', ', $setPart)." WHERE ID = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($bindings);
}
?>

look at 'PHP Sandbox'.

You can create an update as :

    <?php
include 'connection.php';
function dbupdate($table, $data, $id)
{
    global $link;
    $setColumn= array();


    foreach ($data as $key => $value)
    {
        $setColumn[] = "{$key} = '{$value}'";

    }

   $sql = "UPDATE {$table} SET ".implode(', ', $setColumn)." WHERE ID = '$id'";
    mysqli_query($link,$sql);

}
?>