0

I have an array that looks like:

$frmData = array([name]=>Abhi[cell]=>050000000[email]=>[email protected][address]=>1/2 South Road)

Now I want to insert data into my mysql db from the array, and use the array key [name][cell][email][address] as table column and values as column value.

I tried several times any ways but not sure how to do it. Any help is greatly appreciated.

3
  • Can you post your attempt? Commented Sep 27, 2013 at 8:01
  • 4
    "I tried several times any ways" Care to show us what you have tried? Commented Sep 27, 2013 at 8:02
  • Here, have some hints: array_keys() and array_values() Commented Sep 27, 2013 at 8:09

2 Answers 2

2

You can try this :

$columns = array_keys($frmData);
$values = array_values($frmData);

$query = "INSERT INTO your_table (" . implode(", ", $columns) . ") VALUES ('" . implode("', '", $values) . "')";

OR if you want to make make calculation on values you can loop through your array with foreach ($frmData as $column => $value)

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

Comments

0

It should be something like:

$cols = array();
$vals = array();
foreach($frmData as $key => $val){
    $cols[]= $key;
    $vals[]= "'" . mysqli_real_escape_string($val) . "'";
}
$query = 'insert into your_table(' .implode(',', $keys) . ') values (' . implode(',', $vals) . ')';

1 Comment

I was about to +1 but then i realized that this is totally injection vulnerable :P And your edit only works with strin values.

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.