divHelper11
divHelper11

Reputation: 2208

Conditions in implode function

I am doing an implode on my array:

$values = "('".implode("', '", $array)."')";

It gives me results like this:

('abc', '123', 'apple123', 'hello', '345')

I need it to look like below, so the numbers will not be in quotation marks:

('abc', 123, 'apple123', 'hello', 345)

The problems is that the mysql database doesn't want to import the data properly. It sees the numbers as strings and gives them max possible int value so the imported values do not match what I have.

Is there any way to add some more instructions to implode so it would recognize what is number and what is not?

Upvotes: 0

Views: 310

Answers (1)

RickN
RickN

Reputation: 13500

As mentioned in the comment by @GrafiCode, you can't do what you're asking for.

A quick workaround would be to take advantage of json_encode's behavior that leaves integer values as unquoted (as expected):

$data = array('abc', 123, 'apple123', 'hello', 345);

$insert = trim(json_encode($data), '[]');

// Output is: "abc",123,"apple123","hello",345
// (You can add the round brackets yourself).

However:

It seems you're building a query dynamically. If you were to do something like this:

$placeholders = implode(',', array_fill(0, count($data), '?'));

Then you can use parameterized queries / prepared statements, which are much safer:

$q = $pdo->prepare("INSERT INTO people VALUES ({$placeholders})");
$q->execute($data);
// This is also possible in MySQLi and other database APIs, not just PDO.
// The string would look like this: INSERT INTO people VALUES (?,?,?,?,?)
// Every question mark is replaced by one value from the array 
// when the query is executed.

You send the (dynamic) data after building the query and don't need to concern yourself with quoting.

Prepared statements are also an excellent defense against SQL injections.

Upvotes: 2

Related Questions