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?

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.