0

i'm trying to make an insertion 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 insert ($table, $column, $value)
{
$data = array ();
foreach($data as $column => $value)
{
$sql = "INSERT INTO $table ($column) VALUES (:$column)";
$stmt = $pdo->prepare($sql);
$stmt -> execute (array(':$column' => '$value'));
}
}

Call this Function

insert ('accounts', 'fname', 'ahmed');

i have (accounts) table & (fname) Field

Thanks in Advance

user3516382
  • 1
  • 1
  • 3

1 Answers1

0

If you're going to use a foreach, you need to send an array into the function. Foreach is built specifically to iterate over arrays. If you create an empty array within the function, it will iterate zero times.

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

function insert ($table, $data, $pdo)
{
    foreach($data as $column => $value)
    {
        $sql = "INSERT INTO {$table} ({$column}) VALUES (:{$column});";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(':'.$column => $value));
    }
}

$table = "accounts";
$data = array("fname" => "ahmed");

insert($table, $data, $pdo);

For a more robust approach to this problem, check out this question and answer.

Community
  • 1
  • 1
larsAnders
  • 3,813
  • 1
  • 15
  • 19