When a MySQL column contains multiple comma-separated values, PHP can process them using explode(), trim() and a foreach loop. However, problems arise when values contain unexpected whitespace, related database records are missing or SQL queries are constructed without prepared statements.
The immediate solution is to split the string, trim each value and use prepared queries to retrieve and insert the corresponding records. For applications that process large amounts of data, a better long-term solution is to store each value in a separate database row and use SQL JOIN operations instead of nested PHP loops.
This guide explains both approaches using native PHP, PDO and MySQL.
Understanding the original problem
Consider a payment-processing application with three database tables.
The pay_post table contains payment records and associated filenames. The commission table contains information associated with each filename. The paycor table receives the processed commission information.
Originally, each payment record contained only one filename.
For example:
text
pay_post
id | fnms
---|------------------------
1 | 1526124534
2 | 1526256355
The application could retrieve a filename, find its matching commission record and insert the commission information into the destination table.
However, some payment records now contain multiple filenames:
text
pay_post
id | fnms
---|------------------------
1 | 1526124534
2 | 1526256355, 1523659978
The second record contains two values separated by a comma.
The developer needs to process both filenames before moving to the next payment record.
A logical first attempt is:
<?php
$filenames = explode(',', $row['fnms']);
foreach ($filenames as $filename) {
// Find and process the related commission record.
}This approach is not inherently wrong. In fact, it works for straightforward comma-separated values.
The problem in the original case was unexpected whitespace introduced during a CSV import.
1. Why explode() sometimes appears not to work
PHP's explode() function divides a string into an array using a specified separator.
For example:
<?php
$filenames = explode(',', '1526256355, 1523659978');
print_r($filenames);The resulting array contains:
text
Array
(
[0] => 1526256355
[1] => 1523659978
)
Notice the leading space before the second filename.
If the application searches MySQL using the value exactly as returned by explode(), that additional space can prevent an exact match.
For example, the following two strings are different:
text
1523659978
1523659978
The first contains ten digits. The second begins with a space.
This explains why processing a single filename might work while processing a comma-separated list produces missing records.
The immediate fix: trim each value
Use trim() after splitting the string:
<?php
$filenames = explode(',', '1526256355, 1523659978');
foreach ($filenames as $filename) {
$filename = trim($filename);
if ($filename === '') {
continue;
}
echo $filename . PHP_EOL;
}
The output becomes:
text
1526256355
1523659978The trim() function removes surrounding whitespace, including ordinary spaces, tabs and line breaks.
This is particularly useful when processing values imported from CSV files, spreadsheets or third-party systems.
The original Stack Overflow discussion confirmed that a leading space introduced by a CSV import caused the reported problem.
2. Why the original SQL queries are unsafe
A common implementation constructs SQL statements by inserting PHP variables directly into query strings.
For example:
<?php
$sql = "SELECT client, mlo FROM commission WHERE filename = '$filename'";This is unsafe when filename can contain untrusted data.
If an attacker can influence the input, directly inserting it into SQL can introduce SQL injection vulnerabilities.
Unexpected quotes and other characters can also cause query failures even when no malicious input is involved.
Use prepared statements instead.
With PDO:
<?php
$stmt = $pdo->prepare(
'SELECT client, mlo FROM commission WHERE filename = ?'
);
$stmt->execute([$filename]);
$commission = $stmt->fetch(PDO::FETCH_ASSOC);PDO sends the filename as a parameter rather than treating it as part of the SQL statement.
Prepared statements should also be used for INSERT and UPDATE operations.
See the PHP PDO prepared statements documentation for further details.
3. Handle missing commission records correctly
Another issue occurs when a filename does not exist in the commission table.
A database query can execute successfully while returning no rows.
If the application immediately accesses the returned record without checking it, PHP may produce warnings or use invalid values.
Always check the result:
<?php
$stmt->execute([$filename]);
$commission = $stmt->fetch(PDO::FETCH_ASSOC);
if ($commission === false) {
error_log('Commission record not found for filename: ' . $filename);
continue;
}
$client = $commission['client'];
$mlo = $commission['mlo'];The continue statement skips the missing commission record and proceeds to the next filename.
Whether missing records should be skipped or cause the entire operation to fail depends on the application's business rules.
For financial processing, silently ignoring missing commission records may be unacceptable. A production system should record these exceptions and provide a way to investigate and reconcile them.
4. Create a repeatable database processing example
The following example demonstrates how to process multiple filenames using PDO.
It also addresses another important issue: running the same import twice should not automatically create duplicate destination records.
For a new implementation, the following database structure provides the necessary information.
sql
CREATE TABLE pay_post (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
paid_on DATE NOT NULL,
fnms TEXT NOT NULL,
INDEX idx_paid_on (paid_on, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE commission (
filename VARCHAR(100) PRIMARY KEY,
client VARCHAR(150) NOT NULL,
mlo VARCHAR(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE paycor (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
pay_post_id BIGINT UNSIGNED NOT NULL,
item_position INT UNSIGNED NOT NULL,
filename VARCHAR(100) NOT NULL,
client VARCHAR(150) NOT NULL,
mlo VARCHAR(150) NOT NULL,
UNIQUE KEY uq_paycor_source (
pay_post_id,
item_position
),
CONSTRAINT fk_paycor_post
FOREIGN KEY (pay_post_id)
REFERENCES pay_post(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
This is an illustrative schema for a new database. Do not replace an existing production schema without reviewing its relationships, data and migration requirements.
The item_position column records the original position of a filename within its payment record.
The unique constraint prevents the same source position from being inserted repeatedly when the processing script runs again.
Add some sample data
sql
INSERT INTO pay_post (paid_on, fnms) VALUES
('2026-09-14', '1526124534'),
('2026-09-14', '1526256355, 1523659978');
INSERT INTO commission (filename, client, mlo) VALUES
('1526124534', 'Client A', 'MLO A'),
('1526256355', 'Client B', 'MLO B'),
('1523659978', 'Client C', 'MLO C');
The second payment record deliberately contains a space after the comma to demonstrate the whitespace problem.
5. Complete PHP PDO processing script
Save the following code as process-commissions.php outside your public web directory.
The script requires PHP 8 or later, the PDO MySQL extension and an existing database containing the tables described above.
Configure DB_DSN, DB_USER and DB_PASS through your server environment. Do not place production credentials directly in the script.
<?php
declare(strict_types=1);
if (PHP_SAPI !== 'cli') {
http_response_code(403);
exit('This script must run from the command line.');
}
$dsn = getenv('DB_DSN');
$user = getenv('DB_USER');
$password = getenv('DB_PASS');
if ($dsn === false || $dsn === '' ||
$user === false || $user === '' ||
$password === false) {
throw new RuntimeException('Database configuration is missing.');
}
$pdo = new PDO($dsn, $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
]);
$today = $argv[1] ?? date('Y-m-d');
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $today);
if ($date === false || $date->format('Y-m-d') !== $today) {
throw new InvalidArgumentException('Use a date in YYYY-MM-DD format.');
}
$selectPosts = $pdo->prepare(
'SELECT id, fnms
FROM pay_post
WHERE paid_on = ?
ORDER BY id'
);
$selectCommission = $pdo->prepare(
'SELECT client, mlo
FROM commission
WHERE filename = ?'
);
$insert = $pdo->prepare(
'INSERT INTO paycor
(pay_post_id, item_position, filename, client, mlo)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
filename = ?,
client = ?,
mlo = ?'
);
$processed = 0;
$missing = 0;
try {
$pdo->beginTransaction();
$selectPosts->execute([$today]);
while ($post = $selectPosts->fetch()) {
$filenames = explode(',', $post['fnms']);
foreach ($filenames as $index => $rawFilename) {
$filename = trim($rawFilename);
if ($filename === '') {
continue;
}
$selectCommission->execute([$filename]);
$commission = $selectCommission->fetch();
$selectCommission->closeCursor();
if ($commission === false) {
$missing++;
error_log(
'Missing commission for post ' .
$post['id'] . ', filename ' . $filename
);
continue;
}
$insert->execute([
$post['id'],
$index + 1,
$filename,
$commission['client'],
$commission['mlo'],
$filename,
$commission['client'],
$commission['mlo'],
]);
$processed++;
}
}
$selectPosts->closeCursor();
$pdo->commit();
} catch (Throwable $exception) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $exception;
}
echo 'Processed: ' . $processed . PHP_EOL;
echo 'Missing commission records: ' . $missing . PHP_EOL;Run the script with the sample date:
php process-commissions.php 2026-09-14With the sample data, the expected output is:
text
Processed: 3
Missing commission records: 0
The processed count represents successfully matched entries, including existing destination entries that were updated. It is not necessarily the number of newly inserted rows.
The SQL transaction keeps the destination database changes together. If an unexpected database error occurs, the transaction is rolled back.
For large batches, use smaller transactions and a durable checkpoint instead of holding one transaction open across the entire dataset.
6. Preserving the original processing order
SQL does not guarantee row ordering unless an ORDER BY clause is used.
The example selects payment records using:
sql
SELECT id, fnms
FROM pay_post
WHERE paid_on = ?
ORDER BY id;
This ensures that payment records are processed in ascending ID order.
Within each payment record, explode() preserves the sequence of comma-separated values.
For example:
text
1526256355,1523659978,1526124534
The foreach loop processes these values in the same sequence.
The item_position column records that position in the destination table.
However, database rows themselves have no guaranteed physical order. When reading the processed records later, explicitly request their order:
sql
SELECT filename, client, mlo
FROM paycor
ORDER BY pay_post_id, item_position;
If the source requires a different ordering rule, such as payment timestamp followed by record ID, implement that rule explicitly.
7. Preventing duplicate records during repeated imports
Financial and administrative imports should generally be safe to repeat.
A script that blindly inserts records every time it executes can create duplicate entries when a cron job is retried or an administrator reruns an import.
The example uses a unique constraint on pay_post_id and item_position.
It also uses ON DUPLICATE KEY UPDATE to update the corresponding destination record when the same source position is processed again.
This prevents duplicate rows for the same source position.
It does not automatically remove destination rows if a source list becomes shorter. It also does not distinguish an intentionally repeated filename from an accidental duplicate inside the same source record.
If imported payment records can change after processing, introduce explicit reconciliation rules, source versioning or immutable import batches.
For accounting-related data, consider retaining an audit history rather than silently replacing previously processed values.
8. The database design problem: Comma-separated values
Although explode() works, storing multiple filenames in a single database column creates avoidable complications.
Consider:
text
pay_post
id | fnms
---|-------------------------
1 | 1526124534
2 | 1526256355,1523659978
The database cannot efficiently treat each filename as an independently indexed relationship.
Searching for individual values requires string processing, and enforcing foreign-key relationships becomes difficult.
The structure also complicates validation, updates, reporting and duplicate detection.
A more maintainable design stores each filename in a separate related table.
9. Normalise the database structure
Instead of storing multiple filenames in pay_post.fnms, create a child table.
sql
CREATE TABLE pay_post_filename (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
pay_post_id BIGINT UNSIGNED NOT NULL,
item_position INT UNSIGNED NOT NULL,
filename VARCHAR(100) NOT NULL,
UNIQUE KEY uq_post_position (
pay_post_id,
item_position
),
INDEX idx_filename (filename),
CONSTRAINT fk_filename_post
FOREIGN KEY (pay_post_id)
REFERENCES pay_post(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
The original data becomes:
text
pay_post_filename
pay_post_id | item_position | filename
------------|---------------|------------
1 | 1 | 1526124534
2 | 1 | 1526256355
2 | 2 | 1523659978
Each filename is now stored independently.
This makes it easier to validate values, find related records and use ordinary SQL JOIN operations.
The original comma-separated column can eventually be removed after a carefully tested migration.
10. Replace nested PHP queries with a SQL JOIN
Once the data is normalised, the database can retrieve all related commission records in a single query.
sql
SELECT
p.id AS pay_post_id,
pf.item_position,
pf.filename,
c.client,
c.mlo
FROM pay_post AS p
INNER JOIN pay_post_filename AS pf
ON pf.pay_post_id = p.id
INNER JOIN commission AS c
ON c.filename = pf.filename
WHERE p.paid_on = '2026-09-14'
ORDER BY p.id, pf.item_position;
The JOIN connects payment records to their individual filenames and then matches those filenames against the commission table.
This eliminates the need to execute a separate commission lookup for every filename.
For a production application, use a prepared parameter for the date rather than hardcoding it.
When copying results into the destination table, the same relationships can be used with INSERT INTO ... SELECT, together with the destination table's uniqueness rules.
Why this is more efficient
The nested PHP approach executes additional database queries for each filename.
For example, processing 1,000 filenames can require roughly 1,000 individual commission lookups, plus the destination writes.
A properly indexed JOIN allows MySQL to perform the matching within the database engine instead of repeatedly communicating with PHP.
The exact performance improvement depends on database size, indexes, execution plans and server conditions. Measure real workloads before claiming a specific speed increase.
11. What about MySQL FIND_IN_SET()?
If changing the database structure is not immediately possible, MySQL provides FIND_IN_SET().
For example:
sql
SELECT
p.id,
c.filename,
c.client,
c.mlo
FROM pay_post AS p
INNER JOIN commission AS c
ON FIND_IN_SET(c.filename, p.fnms) > 0
WHERE p.paid_on = '2026-09-14';
This can match individual values against a comma-separated column.
However, it has important limitations.
Whitespace can still cause matching problems because a value containing a leading space is not the same as the trimmed filename.
FIND_IN_SET() also cannot use an ordinary index on the comma-separated column to efficiently locate individual list members.
It becomes increasingly expensive as the number of records grows.
The query also does not preserve the original filename sequence unless ordering is handled explicitly.
FIND_IN_SET() can be useful as a temporary solution for legacy data, but it should not be the preferred design for a new application.
See the MySQL string functions documentation for details.
12. Common problems to check
If a comma-separated value processing script is not producing the expected records, inspect the input before rewriting the loops.
Check whether values contain leading or trailing spaces, whether imported data contains blank entries, and whether the filename exists in the related table.
Confirm that queries use prepared statements and that the database connection reports errors rather than silently ignoring them.
Check whether the source query needs an ORDER BY clause and whether repeated execution can create duplicate destination records.
Also confirm whether filenames may contain commas themselves. Simple explode() parsing is appropriate only when commas are guaranteed separators and cannot occur inside individual values. For correctly quoted CSV records, use an appropriate CSV parser such as fgetcsv() or str_getcsv().
Final recommendations
For an existing PHP application with comma-separated values, explode() followed by trim() is a reasonable immediate solution.
Use PDO prepared statements, check for missing records and explicitly define the processing order.
For recurring imports, protect the destination table against duplicate processing and maintain sufficient source information to investigate failures.
For new applications or systems handling substantial amounts of data, avoid comma-separated database columns altogether. Store each related value in its own row and use indexed SQL JOIN operations.
The original issue illustrates an important debugging principle: when a nested loop appears to fail, inspect the actual data before assuming the loop structure is incorrect.
For further reading, consult the PHP explode() documentation, PHP trim() documentation, PHP PDO documentation and the original Stack Overflow discussion.
