Output of a query displaying as null - php

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>'. $files['FILENAME'] .'' . "\n";
}

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']; }

Related

PHP - Create multidimensional recursive array from string (Files/folders structure)

Someone asked same question 10 years ago but there is no answer to that
Reference: Trying to create Array from String (file/folder structure)
Update Jan 8, 2022: This is how array and tree should look like:
https://3v4l.org/6ULBZ#v8.1.1
The SQL output should be formed into this array structure from a string.
[
'id' => $key //Increment from foreach loop,
'file' => $row['name'] //Name of folders and files
'parent_id' => 0 // 0 - if no subfolder, $id if there is subfolder
]
I want to return a tree-level multidimensional array from file list stored in database as a string.
For example I store my work related path in database like this:
SELECT name FROM files;
... SQL Output
2021/Dec/File1.doc
2021/Dec/File2.doc
2021/Dec/File3.doc
2021/Nov/File1.doc
2021/Nov/File2.doc
2021/Nov/File3.doc
2021/Nov/File4.doc
2020/Jan/File1.doc
2020/Jan/File2.doc
2020/Jan/File3.doc
... PHP recursive array output should be categorized by folders, subfolders, more subfolders if exists and files on end.
-2021
--Dec
---File1.doc
---File2.doc
---File3.doc
--Nov
---File1.doc
---File2.doc
---File3.doc
---File4.doc
-2020
--Jan
---File1.doc
---File2.doc
---File3.doc
What would be the best way to achieve this performance wise?
What I got so far...
$files = [];
foreach ($sql as $row)
{
// Separate directories
$separator = explode('/', $row['name']);
/* Output:
Array
(
[0] => 2021
[1] => Dec
[2] => file1.doc
)
*/
// Find the file via regex
if (preg_match('/[^\/]*\.(doc|txt)/', $row['name'], $o))
{
$row['name'] = $o[0]; //Output: file1.doc
}
$files[] = $row;
}
... For now I only have a file names, now I need directories as well and then make a multidimensional array from it.
$files = [];
foreach ($sql as $row)
{
// Separate directories
$separator = explode('/', $row['name']);
/* Output:
Array
(
[0] => 2021
[1] => Dec
[2] => file1.doc
)
*/
if (preg_match('/[^\/]*\.(doc|txt)/', $row['name']))
{
$node = &$files;
while (count($separator) > 1) {
$folder = array_shift($separator);
if (!array_key_exists($folder, $node)) {
$node[$folder] = [];
}
$node = &$node[$folder];
}
$node[] = $separator[0];
}
}
I have one solution for you, I hope this will help.
$files="2021/Dec/File1.doc,
2021/Dec/File2.doc,
2021/Dec/File3.doc,
2021/Nov/File1.doc,
2021/Nov/File2.doc,
2021/Nov/File3.doc,
2021/Nov/File4.doc,
2020/Jan/File1.doc,
2020/Jan/File2.doc,
2020/Jan/File3.doc";
$files=explode(',',$files);
foreach($files as $file)
{
$i=1;
$paths=explode('/',$file);
foreach($paths as $path)
{
for($j=0;$j<$i;++$j){
echo '-';
}
echo $path;
echo "<br/>";
++$i;
}
$i=0;
}
You can use your database files. by removing my files constant value and use your.

How to detect changes in directories or file inside that directory using php

I have directory structure like this:
[Products] => Array
(
[Category1] => Array
(
[product1] => Array
(
[documents] => Array
(
[0] => Attachment1.pdf
[1] => Attachment2.pdf
)
)
)
)
if there is any changes in any directory or file inside products directory
like:
product1 changed to product2
new directory added
any changes in file Attachment.pdf
new document added to directory.
What i have tried till now:
$dir="PATH TO PRODUCT DIRECTORY"
$stats = stat($dir);
but $stats['mtime'] detected change in Products children only (Like if change Category1 to Category2 or newly added directory to products) but not in grand children of products (Like if i change product1 to product2) and so on.
Can any one help me to delect any changes in product with children.
Here is my solution i have implemented. By using these function i am able to get a MD5 hash code and i can use this hash code to check if there is any changes in directory structure or in any file.
$dir="PATH TO PRODUCT DIRECTORY";
public function directoryHash($dir, $item_name){
$dirStr=$this->directoryStruture($dir, $separator= DIRECTORY_SEPARATOR, $root='');
$strHash=md5(json_encode($dirStr));
return $strHash;
}
public function directoryStruture($dir, $separator = DIRECTORY_SEPARATOR, $root = '') {
$result = array();
$cdir = scandir($dir);
$result = array();
if ($root === '') {
$root = $dir;
}
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value, array(".", ".."))) {
$current = $dir . $separator . $value;
if (is_dir($current)) {
$result['items'][] = $value;
$result[$value] = $this->directoryStruture($current, $separator, $root);
} else {
$filePath = str_replace($root, '', $current);
$result[] = $filePath.filemtime($current);
}
}
}
return $result;
}
If there is any better approach. Please let me know.
Thanks,
M.

How to get Contents of text files as value in foreach loop in glob function in php?

I am developing a search engine with vector space Model. I successfully computed tf-idf with associative array data already define in code. Now I want that data should be come from directory where I have a folders and in each folder there is a number of text files with dummy data. I have tried alot but stuck at 1 point using glob function because I want all .txt files as key and its contents as value in foreach loop of glob function.... Below is my code.
Tf-idf With Associative Array Data
$collection = array(
1 => 'this string is a short string but a good string',
2 => 'this one isn\'t quite like the rest but is here',
3 => 'this is a different short string that\' not as short'
);
$dictionary = array();
$docCount = array();
foreach($collection as $docID => $doc) {
$terms = explode(' ', $doc);
$docCount[$docID] = count($terms);
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('df' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$docID])) {
$dictionary[$term]['df']++;
$dictionary[$term]['postings'][$docID] = array('tf' => 0);
}
$dictionary[$term]['postings'][$docID]['tf']++;
}
}
$temp = ('docCount' => $docCount, 'dictionary' => $dictionary);
As you see in 1st foreach loop is that $DocID is key and $doc is its contents(value) of collection array. But I don't know how to implement exact same thing when files read from directory. See code below..
Tf-idf With .txt Files and its contents read from directory
foreach (glob("C:\\wamp\\www\\Web-info\\documents\\awd_1990_00\\*.txt") as $file) {
$file_handle = fopen($file, "r");
//echo $file;
$dictionary = array();
$docCount = array();
foreach($file as $docID=> $value) {
echo $value;
$terms = explode(' ', $doc);
$docCount[$docID] = count($terms);
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('df' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$docID])) {
$dictionary[$term]['df']++;
$dictionary[$term]['postings'][$docID] = array('tf' => 0);
}
$dictionary[$term]['postings'][$docID]['tf']++;
}
}
}
$temp = array('docCount' => $docCount, 'dictionary' => $dictionary);
This gives me error on 1st foreach loop that invalid arugument supplied for foreach loop. As I mentioned earlier I want .txt files as a key and its contents as a value in 1st foreach loop. But I got this error Can anybody please Tell me how to do this.. Thanks in advance..
If you want to treat the entire file as one value, you can use file_get_contents() to read the file into a string:
$dictionary = array();
$docCount = array();
foreach (glob("C:\\wamp\\www\\Web-info\\documents\\awd_1990_00\\*.txt") as $docID) {
$value = file_get_contents($docID);
...
}

i have an array in an array that contains 3 items, how do I make it go through every item in both arrays?

I am pulling results from an LDAP query with php. One of the items in the array of results is an array with 3 sets of information. How do I make it display all three sets instead of just the first? See my code below:
if ($ds) { $ds=ldap_connect("ldap-server");
$r=ldap_bind($ds);
$sr=ldap_search($ds, "DC=,DC=co,DC=uk",$search);
$info = ldap_get_entries($ds, $sr)or die('get info fail');
$header = array(
t('Picture'),
t('First Name'),
t('Last Name'),
t('Role'),
t('Email')
);
$rows = array();
for ($i=0; $i<$info["count"]; $i++) {
//Handle Image
if(isset($info[$i]["jpegphoto"][0])){
$tempFile = tempnam(sys_get_temp_dir(), 'image');
file_put_contents($tempFile, $info[$i]["jpegphoto"][0]);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = explode(';', $finfo->file($tempFile));
$jpeg = '<img src="data:' . $mime[0] . ';base64,' . base64_encode($info[$i]["jpegphoto"][0]) . '"/>';
}else{
$path = drupal_get_path('module','search_engine');
$jpeg = '<img src="'.$path.'/images/userImage.jpg" />';
}
$rows[$i] = array(
'picture' => $jpeg,
'first' => $info[$i]["givenname"][0],
'last' => $info[$i]["sn"][0],
'role' => $info[$i]["memberof"][0],
'mail' => $info[$i]["mail"][0],
);
}
ldap_close($ds);
return theme('table', array('header'=>$header,'rows'=>$rows));
I'm showing picture, first, last, role, and email in my table. Role contains an array with 3 items, how do I make it go through every item in the array? I know I can't just throw a foreach into the middle of an array.
I need to display all of these.
If you don't need to do anything with the individual roles in that sub-array, e.g. display it only, then simply implode() it into a string:
$rows[$i] = array(
...
'roles' => implode(',', $info[$i]['memberof'])
...
);
If you do need do some with the individual components, then deal with it separately:
$rows[$i] = array(...normal non-array data here);
foreach($info[$i]['memberof'] as $key => $value) {
$rows[$i]['role'][$key] = $value;
}
Are you looking for something like implode()?
$roles = array("role1","role2","role3");
$imploded = implode(",", $roles);
echo $imploded; //should return "role1,role2,role3"

php current array position and previous/next

I have read through many posts regarding previous/next and I am still very much stuck.
I have a page which shows an image and related data. This is obtained from a database. The images are located within the website folder in folders per album. So an image folder may contain 1, 2 or 100 images.
I have a function as follows for this data:-
function get_images_album($artist_id) {
$artist_id = (int)$artist_id;
$images = array();
$image_query = mysql_query("SELECT `image_album_id`, `member_id`, `artist_id`,
`albumname`, `ext`, `timestamp` FROM `album_images`
WHERE `artist_id`=$artist_id AND `member_id`=".$_SESSION['member_id']);
while ($images_row = mysql_fetch_assoc($image_query)) {
$images[] = array(
'id' => $images_row['image_album_id'],
'album' => $images_row['artist_id'],
'albumname' => $images_row['albumname'],
'ext' => $images_row['ext'],
'timestamp' => $images_row['timestamp']
);
}
return $images;
}
The page shows the correct image and data per the url on localhost. Site/album_view.php?artist_id=4&image_album_id=4.
On the html page the code is:-
$images = get_images_album($artist_id);
if (empty($images)) {
echo 'There are no Images in this album.';
}else{
foreach ($images as $key => $val) {
}
}
?>
I had understood that if I echo $key and current($val) I would get the array index nos. and image id for the current page. In the case above this would be 0 and 4. However I always get the last index details of the array, which happens to be 13 and 2181 for the particular album.
I know all the data is there as I have echoed the array and all seems ok.
I do not know why.
Going on from what I have I cannot work out how to proceed to get the next and previous settings Thank you.
An easier way to go about this might be to change your get_images_album function slightly:
function get_images_album($artist_id) {
$artist_id = (int)$artist_id;
$images = array();
$image_query = mysql_query("SELECT `image_album_id`, `member_id`, `artist_id`,
`albumname`, `ext`, `timestamp` FROM `album_images`
WHERE `artist_id`=$artist_id AND `member_id`=".$_SESSION['member_id']);
While ($images_row = mysql_fetch_assoc($image_query)) {
// $images[] = array(
// instead, make your images array a hash and key it on the album_id
$images[$images_row["image_album_id"]] = array(
'id' => $images_row['image_album_id'],
'album' => $images_row['artist_id'],
'albumname' => $images_row['albumname'],
'ext' => $images_row['ext'],
'timestamp' => $images_row['timestamp']
);
}
return $images;
}
now you can eliminate your foreach loop and just get the album you're looking for:
$images = get_images_album($artist_id);
if (empty($images)) {
echo 'There are no Images in this album.';
}else{
$album_images = $images[$image_album_id];
// do stuff with the $album_images hash
var_dump($album_images);
}

Categories