0

I am new to PHP and I'm trying to make a function that can insert any arguments given in the param into a table specified also as a param of the function, but when I execute my code it says:

call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object

here is my code:

function insert($table, $args){
    
    $Query = "INSERT INTO ? VALUES(";
    $types="";
    foreach($args as $arg){
        $Query=$Query."?,";
        $type = gettype($arg);
        switch ($type) {
            case "string": 
                $types = $types."s";
                break;
            case "integer": 
            case "double": 
                $types = $types."d";
                break; 
        }
    }
    $Query=substr($Query, 0, -1);
    $Query=$Query.")";
    global $mysqli;
    $stmt=$mysqli->prepare($Query);
    echo $stmt;
    array_unshift($args, $table);
    array_unshift($args, $types);

    call_user_func_array(array($stmt, "bind_param"), $args);
    $stmt->execute();
}

so what's wrong here and thank you?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Hamdi
  • 49
  • 7
  • 1
    Table names, btw, cannot be binded. – u_mulder Jun 26 '20 at 21:55
  • Does this answer your question? [Can I parameterize the table name in a prepared statement?](https://stackoverflow.com/questions/11312737/can-i-parameterize-the-table-name-in-a-prepared-statement) – Progman Jun 26 '20 at 22:18

1 Answers1

1

Why, oh why would you want to create such function?

Don't even think about creating such complex and utterly useless function. This will be your nightmare. Trust my advice and stop what you are doing right now.

If you are only starting with PHP then forget about mysqli. It is missing a lot of functionality and is very complex. Start learning PDO.

With PDO you do not need such functions.

Start by opening PDO connection:

$pdo = new PDO("mysql:host=localhost;dbname=db_name;charset=utf8mb4", 'username', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

Then you can execute a simple statement like this:

$pdo->prepare('INSERT INTO tableA(col1, col2) VALUES(?,?)')
    ->execute(['val1', 'val2']);

Binding unknown number of parameters is also quite simple.

$stmt = $pdo->prepare('SELECT * FROM TableA WHERE Id IN ('.implode(',', array_fill(0, count($ids), '?')).')');
$stmt->execute($ids);
$data = $stmt->fetchAll();

Just take a look how much simpler it is compared to your custom function.

Dharman
  • 30,962
  • 25
  • 85
  • 135