I need to use a generated string as an array within a MySQL-Loop.
The string/array is built into $argumentarray
from the $rows
arguments and should after be used as the array of multiSQLarray[]
The function is called as:
multiSQL('**id,title,description,link**','menu')
The string gets correctly generated as
array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link'])
But instead of using it as a string for the array it just adds it to the array for every result from the sql
Array ( [0] => array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link']) [1] => array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link']) )
What i expect is the SQL result as the array
Array ( [0] => Array ( [id] => 1 [title] => Customers [description] => Display the Customer Dashboard [link] => index.php ) [1] => Array ( [id] => 2 [title] => Server [description] => Display all Servers [link] => servers.php ) )
My code:
function multiSQL($rows=null,$table=null,$select=null) {
if(is_null($select)) {$filter="";} else { $filter = ' where '.$select; }
global $pdo;
$sql = 'SELECT '.$rows.' FROM '.$table.$filter.'';
$connection =$pdo->prepare($sql);
$connection->execute();
$multiSQLarray = array();
$arguments = explode(',',$rows);
$argumentarray = "";
$argumentscount=count($arguments);
$loopcount = 1;
foreach($arguments as $argument){
if($loopcount==$argumentscount){
$loopcount++;
$argumentarray = $argumentarray.' \''.$argument.'\' => $result[\''.$argument.'\']';
}
else{
$loopcount++;
$argumentarray = $argumentarray.'\''.$argument.'\' => $result[\''.$argument.'\'],';
}
}
$argumentarray = 'array('.$argumentarray.')';
echo $argumentarray.'<br><br>';
while ($result = $connection->fetch(PDO::FETCH_BOTH)) {
//$multiSQLarray[] = array('id' => $result['id'], 'title' => $result['title'], 'description' => $result['description'], 'link' => $result['link']);
$multiSQLarray[] = $argumentarray;
}
print_r($multiSQLarray);
return $multiSQLarray;