Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.