RWS RWS - 1 month ago 9
PHP Question

array_merge() issue with PDO

I have a function which should return me an array like this

Array
(
[company1] => position1
[company2] => user2
)


I have a proper SQL query which fetches me the required data just fine (tested in MySQL workbench and by dumping the data.

The function that does the thing (see the comment in CAPS at the line with issue):

function check_user_status ($db){
try {
$log = new PDO("mysql:host=".$db['server'].";dbname=".$db['db'], $db['mysql_login'], $db['mysql_pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
// set the PDO error mode to exception
$log->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare sql and bind parameters
$stmt=$log->prepare ("select a.companyname,b.role from companies a, roles b where a.companyid=b.companyid and (b.uid = :uid and b.suspended = 0);");

$stmt->bindParam(":uid", $_SESSION['uid'], PDO::PARAM_INT);
$stmt->execute();
$count=$stmt->rowCount();
//echo "<br>count = $count<br>"; //outputs the numbner of resulting rows for debuging
if($count >=1) {
unset ($_SESSION['status']); //purge any previous user_status
$_SESSION['status'] = array();
while ($userRow = $stmt->fetch(PDO::FETCH_ASSOC)) {
//echo "<br>{$userRow['companyname']} => {$userRow['role']}<br>"; outputs the data for debuging
array_merge ($_SESSION['status'], array($userRow['companyname'] => $userRow['role']));// THIS DOESN'T WORK FOR SOME REASON
}
return true;
}
else
{
//return false;
}

}
catch(PDOException $e) {
return false;
echo 'error: '. $e->getMessage();
}

}


Now this:

check_user_status($db);
var_dump ($_SESSION['status']);


Outputs me empty array:

array(0) { }


array_merge_recursive()
doesn't work either. Notices are enabled, no notice is thrown. Any help would be highly appreciated.

Answer

RTFM: http://php.net/array_merge

Return Values: Returns the resulting array.

You have:

array_merge ($_SESSION['status'], array($userRow['companyname'] => $userRow['role']));
// THIS DOESN'T WORK FOR SOME REASON

"for some reason" = you're completely IGNORING the return value, which is your merged array.