I'm very new to PHP and PDO and was playing around with fetching records from a simple database. I created and managed to successfully do it, but for some odd reason, when I fetchAll()
of my records and add a <br>
tag in the echo
statement, it's adding an extra <br>
at a random position in my output. I'm not sure why this is happening. Is this because of the extra white space in my db?
I tried looking online and other topics on SO for a solution; maybe I'm not looking in the right place for my issue.
I have a feeling it's a problem with whitespace and maybe I need to use trim
for this?
Here is my code:
// Set all fetch requests as an object by default
$dbo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$admin = 'ADMIN';
$adminLive = 'ADMIN-live';
$adminType = 'ADMIN_US_Type';
$customusDomestic = 'US_domestic';
$adminChina = 'China_admin';
$adminIndia = 'India_admin';
$adminCustom = 'ADMIN_custom';
$customusaustinCulver = 'US_Austin_Culver';
$customuschinaTokyo = 'US_China_Tokyo';
$customcorkuaeBayarea = 'Cork_UAE_BayArea';
$customchinashanghaiBeijing = 'China_Shanghai_Beijing';
$adminselfMoves = 'ADMIN_selfmoves';
$adminmilanVienna = 'ADMIN-milan-vienna';
$custombayareaSeattle = 'Bayarea_Seattle_admin';
// Prepare the query
$sql = 'SELECT DISTINCT usergroup
FROM plus_signup
WHERE usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?
AND usergroup != ?';
$stmt = $dbo->prepare($sql);
// Execute the query
$stmt->execute([$admin,$adminLive,$adminType,$customusDomestic,$adminChina,$adminIndia,$adminCustom,$customusaustinCulver,$customuschinaTokyo,$customcorkuaeBayarea,$customchinashanghaiBeijing,$adminselfMoves,$adminmilanVienna,$custombayareaSeattle]);
$usergroups = $stmt->fetchAll();
foreach($usergroups as $locations) {
// This works fine but my output is adding an extra br in some occurances of the loop
echo $locations->usergroup . "<br/>";
}
Untested but the logic should ring true:
$dbo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_NUM); // fetch as indexed array
$dbo->setAttribute(PDO::NULL_TO_STRING: NULL); // nulls to empty strings
$nots = [
'',
$admin,
$adminLive,
$adminType,
$customusDomestic,
$adminChina,
$adminIndia,
$adminCustom,
$customusaustinCulver,
$customuschinaTokyo,
$customcorkuaeBayarea,
$customchinashanghaiBeijing,
$adminselfMoves,
$adminmilanVienna,
$custombayareaSeattle
];
$placeholders = implode(',', array_fill(0, count($nots), '?'));
$sql = "SELECT DISTINCT usergroup FROM plus_signup WHERE usergroup NOT IN ($placeholders)";
try {
$stmt = $dbh->prepare($sql);
$stmt->execute($nots);
$usergroups = $stmt->fetchAll();
echo implode('<br>', $usergroups);
} catch (PDOException $e) {
echo $e->getMessage(); // not to be shown publicly
}
This should eliminate your empty/null values from being part of the resultset.