0

My array:

print_r($entryarray) = Array ( [Place] => lucky [Location] => India [Time] => [Info] => beautiful )

My code to insert the array into INSERT query:

if(count($entryarray) >0 ) {
        $query = "INSERT INTO testing (";
        foreach($entryarray as $col => $val){
            $query.="$col,";
        }
        $query.=" )
        VALUES(";
        foreach($entryarray as $col => $val){
            $query.="$val,";
        }
        $query.=" )";
}

But I am getting an error.

Error: INSERT INTO testing (Place,Location,Time,Info, ) VALUES array_values(lucky,India,,beautiful, )

How can I get INSERT INTO testing ("Place", "Location", "Time", "Info").............?

3
  • What is array_values doing in your SQL code? Commented May 28, 2020 at 11:40
  • Ya, my mistake. I removed it but still getting same error. Commented May 28, 2020 at 12:46
  • You can't get the (exactly) same error. However.. you are missing the quotes. But you should you should use a prepared statement. See how-can-i-prevent-sql-injection-in-php. BTW: With laravels querybuilder it would be DB::table('testing')->insert($entryarray); Commented May 28, 2020 at 12:51

1 Answer 1

2

You could do something like this:

$keys = implode(",", array_keys($entryarray));
$vals = implode("','", array_values($entryarray));

$query = "INSERT INTO testing ('$keys') VALUES ('$vals')";

As mickmackusa suggested, you should sanitize any user input.

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

7 Comments

Thank you. But still can't resolve it. Error: INSERT INTO testing ('Place','Location','Time','Info') VALUES ('lucky','India','','beautiful') You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''Place','Location','Time','Info') VALUES ('lucky','India','','beautiful')' at line 1
The query looks ok to me, does time allow null values? Are the colum names right?
I set the time to be a timestamp. So it will take it automatically.
I figured it. It has to be, INSERT INTO testing (Place,Location,Time,Info) So I changed your code $keys = implode(",", array_keys($entryarray));
Good catch, I've updated my answer.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.