I am trying to build an sql query using an array and add a prefix.
E.g:
$columns = array('column1', 'column2');
"SELECT ". ltrim(implode(", media_", $columns), ', ') . " FROM media WHERE media_id = '{$id}'";
Outputs:
SELECT filename, media_image FROM media WHERE media_id = '3'
What I really want:
SELECT media_column1, media_column2 FROM media WHERE media_id = '3'
Question: How can I: 1. Prefix all items of the array with "media_" 2. Separate more than 1 item with a comma?
why not put "media_" to the front?:
$columns = array('column1', 'column2');
$selectColumns = 'media_' . implode(', media_', $columns);
"SELECT {$selectColumns} FROM media WHERE media_id = '{$id}'";
you can also use array_map:
$columns = array_map(function($column) {
return 'media_' . $column;
}, $columns);
"SELECT " . implode(',', $columns) . " FROM media WHERE media_id = '{$id}'";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With