0

We have an Array Name valArray which is something like this :

$valArray = array (
             name => 'Rahul',
             Address => 'New Delhi',
             Pass => '1234',
             class => '10th',
             School => 'DPS',
             Roll => '134567',
           )

which generates dynamicaly, So, Actually we want is to run this type of sql query,

$query = "insert into table_name set
          foreach($valArray as $key => $value) {
            $key = "$value",
          }
         ";

and Statically which should be something like this :

$query = "insert into table_name set
              name = 'Rahul',
              Address = 'New Delhi',
              Pass = '1234',
              class = '10th',
              School = 'DPS',
              Roll = '134567'
        ";

I Know this is syntactically wrong but is there any way to perform this type of action.

1
  • 1
    be uber careful if these are raw user imputed values Commented Jun 13, 2015 at 3:48

1 Answer 1

2
 $sql = "insert into $table(" . implode(',', array_keys($valArray)) . " values('" . implode("','", array_values($valArray)) . "')";

the call to array_values isn't necessary, but better illustrates the idea I think

edit: quoted values; they should be escaped too

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

2 Comments

only thing missing is the values should be quuoted
@twentylemon What will be happen when we will use sql update command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.