2

I have one array that is filled by mysql_query. Values that are in this array I want to put into one continuous string for example:

$array = array(1, 2, 3, 4, 5);

INSERT INTO 'new_slovmas'.'$tabulka'('$array[0]', '$array[1]', '$array[3]') 
       VALUES ('$r_1', '$r_2', '$r_3')";

Sense in one table is over 50 columns I do not want to fill it manually, but by WHILE or FOR. So I was thinking about putting values into one string like this:

$array = array("'1',", "'2',", "'3',", "'4',", "'5',");

so now I have this:

echo $array[2]; => '3',

By the cycle I wont to achieve having multiple entries in one variable.

$str = $array[0], $array[1] ... $array[xy];

INSERT INTO 'new_slovmas'.'$tabulka'('$str') 
       VALUES ('$r_1', '$r_2', '$r_3')";

3 Answers 3

5

Use implode()

$string = implode(',', array(1, 2, 3, 4, 5));  // $string = 1,2,3,4,5
Sign up to request clarification or add additional context in comments.

9 Comments

ok, what about this array $stlpec[] = $row['column_name']; i do not know values in it. How it will look with function implode? It does not take implode(',', $stlpec[$i]);
Since arrays are not stored in database columns you would not actually be working with an array. You would need to determine what kind of data that is before you can actually plan to do anything with it.
well i already have data in array, but I do not know in witch form to write implode, i want something similar to this, but it is wrong implode(',', $stlpec[$i]);
That definitely means you are not passing an array to implode. Are you 100% sure you are working with an array?
when I type echo $stlpec[1]; I get result
|
3

PHP's implode function will unpack an array into a string for use in Javascript. Try this:

$str = implode(',',$array);

Comments

0

Use:

join(",", $array);

Also, be sure to escape your values before you insert them into the database. You do this in case that one of your values has a single quote (') or something worse in it (like valid SQL), which would crash your query. You can use mysql_real_escape_string(...) or mysqli_real_escape_string(...) for this

1 Comment

join() is an alias of implode()

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.