0

I'm coding my web app in PHP and when I run my script, I've got this error : array to string conversion

Here is the script where the error fires.

public function insert($table, array $columns, array $values) {
            $sql = "INSERT INTO " . $table .
                    " (" . implode(',' , $columns) . " ) 
                    VALUES (" . implode(',',
                    $values) . ")";
            $this->request($sql);
    }

Here is the request function :

public function request($sql, $param = null) {
        if ($param == null) {
            $query = Database::getInstance()->getDb()->query($sql);
        }

        else {
           $query = Database::getInstance()->getDb()->prepare($sql);
           $query->execute(array($param));
        }

        return $query;
    }

N.B : I'm using my own MVC framework.

So, any advise or help would be apreciated ?

Regards

YT

4
  • Do yourself a favour and start using prepared statements. They're available for most RDBMS and are supported by both the mysqli and PDO APIs. Commented Dec 17, 2020 at 14:41
  • Also, which line of code is giving you that error? Your query looks like it should produce a valid string. sandbox.onlinephpfunctions.com/code/… Commented Dec 17, 2020 at 14:43
  • Sorry, just saw your request method is using a prepared statement if you pass through $params. Why aren't you passing through params in this case? I'd change your insert statements so that it generates INSERT INTO ... (...) VALUES (?, ?, ?, ...) and then pass through the values as $params. Commented Dec 17, 2020 at 14:50
  • Look my code here phpize.online/… Can it halp you? Commented Dec 17, 2020 at 15:27

1 Answer 1

1

I advice to modify your class methods for using parameterized queries:

class Test {
    public function insert($table, array $columns, array $values) {
        $sql = "INSERT INTO " . $table . " (" . implode(',' , $columns) . ") 
                VALUES (?" . str_repeat(",?", count($columns) - 1) . ");";

        echo $sql;
        $this->request($sql, $values);
    }
    
    public function request($sql, $param = null) {
        if ($param == null) {
            $query = Database::getInstance()->getDb()->query($sql);
        }

        else {
           $query = Database::getInstance()->getDb()->prepare($sql);
           $query->execute($param);
        }

        return $query;
    }   
};

$test = new Test();

$test->insert('tbl', ['id', 'name'], [1, 'first row']);

Online PHP test

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.