Xavier
Xavier

Reputation: 8362

Convert array and post to sql database

here is my array:

Array ( [0] => Natural Chlid 1 [1] => Natural Chlid 2 [2] => Natural Chlid 3 )

How would i do the following:

a) convert the data so that it could be recalled via a php query and inserted into db

b) add the data to only ONE FIELD of the database (in this case a field called 'children')

Upvotes: 1

Views: 1114

Answers (1)

Saul
Saul

Reputation: 18041

You probably need serialize() and unserialize():

$data = array(
    0 => 'Natural Chlid 1',
    1 => 'Natural Chlid 2',
    2 => 'Natural Chlid 3'
);

// To save

$link = mysqli_connect('hostname', 'user', 'password', 'dbname');

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$serialized = mysqli_real_escape_string($link, serialize($data));

$result = mysqli_query($link, "INSERT INTO table ('id', 'children') VALUES (123, '$serialized')");

if (!$result) {
    printf("Error message: %s\n", mysqli_error());
}

// To retrieve

$result = mysqli_query("SELECT * FROM table WHERE id=123");
$row = mysqli_fetch_assoc(result);

$data = unserialize($row['children']);

Upvotes: 3

Related Questions