Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting array using cURL in Terminal

I'm trying to build a webservice for an app, so the data stores in an online database I have. I'm currently building the php document, and I'm curious as to how I can POST an array using cURL in the Terminal Mac app.

You see, the application will send an array consisting of strings to the webservice. For example something like this ["String 1", "String 2", "String 3"]. But to test if the code I have for inserting these values into the database works, I need to pass this data to the webservice somehow. Up until now I've been using the Mac Terminal app and posted like this curl -F "user_id=1" localhost/test/webservice.php", but I don't know how to pass an array.

What I have so far is this:

curl -F "user_id=1" -F "title=Random title 123" -F "num_items=2" -F "items[]=[Item 1, Item 2]" localhost/test/webservice.php

But I don't think that's the correct way to pass an array, because I believe the code I have in my php document is correct, but the value that's stored in my database is literally the word array. I believe items[] is the correct way to start it, but I'm not so sure about what comes after the =-sign.

Anyone know the correct way to do this?

If this happens to be correct, then there's something wrong with how I store the data in my array. I'm using stmt and the bind_param() keyword like this:

$items = $_POST["items"]; // This is the array

$stmt = $this->db->prepare('INSERT INTO items (item_id, user_id, title) VALUES (?, ?, ?)');
$stmt->bind_param('iis', $item_id, $user_id, $items);
$stmt->execute();
$stmt->close();

What I'm trying to achieve is basically posting all the values fron the array into the database with one insert statement. If that's wrong, what is the correct way to do it?

All help is appreciated!

Thanks.

like image 663
Aleksander Avatar asked Mar 30 '14 03:03

Aleksander


Video Answer


1 Answers

First make sure you want to do -F(for multipart/form-data) or the -d(for application/x-www-form-urlencoded). In either case, here is how you should pass the array:

-F "items[]=Item 1" -F "items[]=Item 2"

or using -d

-d "items[]=Item 1" -d "items[]=Item 2"

Your server will receive the data as following format:

[items] => Array
    (
        [0] => Item 1
        [1] => Item 2
    )
like image 146
Sabuj Hassan Avatar answered Sep 21 '22 03:09

Sabuj Hassan