2

I am getting values in an array like this:

 Array
(
    [0] => English
    [1] => Arabic
)

I am having 2 columns in database like below.

lanuage1 language2

I want to insert the first array [0] => English to language1 column and [1] => Arabic to language2 ,can any one suggest how can I do that? Thanks.

I tried like this:

$data = explode( ',', $language ) ;

print_r($data);

INSERT INTO contact(lanuage1 ,language2) VALUES ($data [0], $data [1]);

but its not working...

2
  • -1 what did you try so far? Show us your trials, efforts etc Commented May 10, 2014 at 6:26
  • 1
    Try enclosing $data[0] and $data[1] inside ' (single quote) Commented May 10, 2014 at 6:30

3 Answers 3

1
<?php
$languages = array(
'0' => 'English',
'1' => 'Arabic'
);

mysqli_query($connection,"INSERT INTO contact(lanuage1 ,language2) VALUES ('$languages[0]', '$languages[1]')");
?>
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to insert new record you must give every column its value , not just language1, language2

Maybe some columns has default values in DB, if it is, you can skip theme in sql statment.

Try this:

INSERT INTO table_name
VALUES (value1, value2, value3,...)

Or visit this page maybe help you: http://www.w3schools.com/php/php_mysql_insert.asp

Comments

1

If you want your array values to be properly formatted, you could just use implode(). Consider this example:

$values = array('English', 'Arabic');
$statement = 'INSERT INTO contact (`language1`, `language2`) VALUES ("' . implode('", "', $values) . '")';
echo $statement;

Sample Output:

INSERT INTO contact(`language1`, `language2`) VALUES ("English", "Arabic")

Important Note: You must remember that column count must have the same count as the values inside your query or else it will not work (count of columns must match the number of elements inside the array or you will have a mismatch).

1 Comment

If the values are coming from a form submission, make sure to iterate over those $values to escape the strings before you insert them to the DB.

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.