-4

I have an array come back from a query but I want to change it to a string for another db query

$test = $go->get_stuff();
$test = array(
    'ONE',
    'TWO',
    'THREE',
    'FOUR'
)

// expected outcome
$sql .= "(table.col IN ('ONE', 'TWO', 'THREE', 'FOUR') OR table.col IS NULL)";
John Conde
  • 217,595
  • 99
  • 455
  • 496
Pierce McGeough
  • 3,016
  • 8
  • 43
  • 65
  • 2
    http://php.net/manual/en/function.implode.php – Sebas Oct 02 '14 at 14:36
  • 3
    Please, please, please: use prepared statements. Don't just string together queries: Injection is very real, and very common – Elias Van Ootegem Oct 02 '14 at 14:39
  • It also sounds like what you REALLY want is to join two tables together - unning a query, getting an array, and then running another query on that array - just use a JOIN in your SQL. – TML Oct 02 '14 at 14:41
  • Seems to me like you could use a `JOIN` here rather than creating two queries? – George Oct 02 '14 at 14:41
  • This is an accident waiting to happen. As someone else already pointed out; prepare your queries. Don't just blatantly put text straight into your queries. – Coreus Oct 02 '14 at 14:53

6 Answers6

2

Use implode() but also be sure to preppend and append a single quote as well:

$string = "'" . implode("','", $test) . "'";
// 'ONE', 'TWO', 'THREE', 'FOUR'
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

This question has been answered before here: How to convert array to a string using methods other than JSON?

Essentially, you will need to use the implode function for your data set.

$test = $go->get_stuff();
$test = array(
    'ONE',
    'TWO',
    'THREE',
    'FOUR'
)

// Implode array to string
$string = "'" . implode("','", $test) . "'";
// Deliver desired output
$sql .= "(table.col IN (".$string.") OR table.col IS NULL)";
Community
  • 1
  • 1
Baraa
  • 1,341
  • 11
  • 8
0

Implode the array:

$str = "'" . implode("', '", $test) . "'";

Then you can add it to your SQL:

$sql .= "(table.col IN ($str) OR table.col IS NULL)";
danmullen
  • 2,556
  • 3
  • 20
  • 28
0

Use implode(). Try this..

$in = "'".implode("','", $test)."'";
$sql .= "(table.col IN (".$in.") OR table.col IS NULL)";
MH2K9
  • 11,951
  • 7
  • 32
  • 49
0

Another way would be to foreach and rtrim: foreach($test as $v) { $str .= "'$v',"; } $str = rtrim($str, ',');

TML
  • 12,813
  • 3
  • 38
  • 45
0

You can do that with "implode" function.

Try this:

$test = $go->get_stuff();
$test = array(
    'ONE',
    'TWO',
    'THREE',
    'FOUR'
)

// expected outcome
$sql .= "(table.col IN ('".implode("','", $test)."') OR table.col IS NULL)";
Rodrigo Techera
  • 251
  • 1
  • 9