I am trying to trieve a list of files where a field ARTICLE_NO is a certain number. At the moment, I have a files table, with columns ARTICLE_NO, FILENAME and USERNAME. There is one record, with values 1, x.txt and user respectively. $pk is assigned to 1 in my php code. However, the following code only produces NULL, and I am unsure why.
$filesQuery = "SELECT FILENAME FROM FILES WHERE ARTICLE_NO = ?";
if ($getFiles = $con->prepare($filesQuery)) {
$getFiles->bind_param("s", $pk);
$getFiles->execute();
$getFiles->bind_result($FILENAME);
$files = array();
while ($getFiles->fetch()) {
$filenames = array(
'FILENAME' => $FILENAME,
);
$files[] = $filenames;
}
}
var_dump($files['FILENAME']);
foreach ($files as $filenames)
{
$filesList = '<p><a href="./files/'. $files['FILENAME'] .'">'. $files['FILENAME'] .'</a>' . "
";
}
You're accessing the array you built up wrongly. When dealing with 1 result row from the database, $files is an array containing 1 other array looking like this:
$files = array ( 0 => array ( 'FILENAME' => 'x.txt' ) );
So, to access the value under FILENAME, you need to use:
var_dump($files[0]['FILENAME']);
or
foreach($files as $file_data) { echo $file_data['FILENAME']; }