Jump to content

Insert Array in MySQL


mactron

Recommended Posts

I'm trying to insert array of posts categories into MySQL. I'm getting category IDs from drop down list..

ERR: Notice: Notice: Array to string conversion in C:\laragon\*********\includes\functions.php on line 477

 

Array

Array
(
    [0] => Array
        (
            [0] => 4
            [1] => 5
        )

)

 

PHP

try {
        $sql = "INSERT INTO posts_category_ids (post_id, category_id) VALUES";

        $insertQuery = array();
        $insertData = array();
        foreach ($filter_category as $row) {
            $insertQuery[] = '(?, ?)';
            $insertData[] = $id;
            $insertData[] = $row;
        }

        if (!empty($insertQuery)) {
            $stmt = $this->conn->prepare($sql);
            $stmt->execute($insertData); //477
        }


         }catch (Exception $e){

            echo $e->getMessage();
}
}

 

Link to comment
Share on other sites

I'm surprised it got past the prepare statement before giving an error.

Where do $id and $row come from?

Are the two sections of code above related in any way?

If, say, you want to add 3 records inserting post_id and category_id into each then the query that gets prepared should look like

"INSERT INTO posts_category_ids (post_id, category_id) VALUES (?,?),(?,?),(?,?)"  

 

Link to comment
Share on other sites

From insert query for posts..

$id = $this->conn->lastInsertId();

I would like something like this..

+----+---------+-------------+
| id | post_id | category_id |
+----+---------+-------------+
| 1  | 2       | 3           |	
| 2  | 2       | 5           |	
| 3  | 3       | 1           |
| 4  | 3       | 2           |
+----+---------+-------------+

The hole problem is inside  my array. 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.