Jump to content

INSERT all values of an array in columns


saeed_violinist

Recommended Posts

Dear friends,

 

I want to know if it is possible to INSERT each value of an array in a colomn in a table or not. for example I have an array like this:

 

("apple", "orange", "banana", "watermelone")

 

and I have a table with 4 columns in my database, so I want a code to put the values of array from key #0 to #4 into the table, WITHOUT knowing the column names.

 

Thanks.

You can use

 

SHOW COLUMNS FROM `tablename`; 

OR

DESCRIBE `tablename`;

 

To find what the column name are...then use them in INSERT.

 

But why did you need to insert something in a database without knowing first what the column name are ?

Hey thanks for reply,

 

well I know the column names, and I have the right order of data to be inserted, I just want to insert data from array, that is each value should go to a column, in to the table without getting busy of writing name of columns in my INSERT command.

 

in the other way, is it possible to have some kind ow loop to read each value of an array and insert it in a column and repeat this when columns are finished?

 

Thanks.

$col = (your number of columns);
while($array) {
  $values = array();
  for($i=0;$i<$col;$i++) {
    $values[] = "'" . array_shift($array). "'";
  }
  $valuesForQuery = implode(',',$values);
  $query = "INSERT INTO table values($valuesForQuery)";
  ...execute your insert....
}

 

- One problem is that this works only if the number of values in $array is multiple of the number of columns. If it's not, some adjustment is needed

- Second problem: you'd better execute mysql_real_Escape_string() on every single value to be inserted in the db. Otherwise, a quote contained in a value will generate a sql error.

well I know the column names, and I have the right order of data to be inserted, I just want to insert data from array, that is each value should go to a column, in to the table without getting busy of writing name of columns in my INSERT command.

That's a VERY BAD idea.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.