php current array position and previous/next - php

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);
}

Related

Insert multiple data in one single database row

I have code for uploading multiple images, it is returning the word "ARRAY", not return the content when I make " echo , die;", and in the other ways it return just the first upload and inserted into database.
I want to insert multiple value "IMGE" in single row database.
Controller:
function uploadFile(){
$data = array();
// If file upload form submitted
if($this->input->post('Submit') && !empty($_FILES['files']['name']))
{
$filesCount = count($_FILES['files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
// File upload configuration
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
// Upload file to server
if($this->upload->do_upload('file')){
// Uploaded file data
///////////////////////////////////////////
//HERR I WANT TO RETURN THE - $file[$i] - WITH ALL
//THE IMAGE UPLAD TO INSER IN SINGLE ROW IN DATABASE
///////////////////////////////////////////
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s");
$file[$i] = $uploadData[$i]['file_name'];
return $file[$i];
echo $file[$i] , die; // here it is just return first image upload
}
}
if(!empty($uploadData)){
return $uploadData;
echo $new_array, die;// here it is return word "ARRAY"}}
Model:
function insert_data($data) // from one table
{
$insert = $this->db->insert('tbl_reservations', $data);
}
The die function prints a message and exits the current script, for this reason only the first file is inserted .so remove die .
You can't insert an array o DB field, you have to loop throw it.
function insert_data($data) // from one table
{
// I suppose that $data is multi dimensional array that conatins single 'row' on each item
foreach($data as $item){
$insert = $this->db->insert('tbl_reservations', $item);
}
}
EDIT 2
Ok now i figured out the problem. Tha data array passed to insert_data contains an array with all file names.
REPLACE your insert() whith the below code:
public function insert(){
$uploadedFiles = $this->uploadFile(); // returns the file names array
// Map post data to table field
$data = array(
'visittype' => $this->input->post('visittype'),
'date' => $this->input->post('date'),
'time' => $this->input->post('time'),
'reasons' => $this->input->post('reasons'),
'symptoms' => $this->input->post('symptoms'),
'doctor_id' => $this->input->post('doctorid'),
'user_id' => $this->session->userdata('doctor')[0]->user_id
);
// Loop on file names and insert each one on the db row.
foreach ($uploadedFiles as $file){
$data['file_name'] = $file['file_name'];
$this->Reservation_model->insert_data($data);
}
}
This way yuo will have as many rows as the uploaded file. If you want to have only one row that contains all files you have to store them as json string and decode when needed.
EDIT 3
uploadedFiles() returns something like this:
$uploadedFiles = [
['file_name' => 'file_one.jpg'],
['file_name' => 'file_two.jpg'],
['file_name' => 'file_three.jpg']
];
you can't store an array on a DB row field.
I can suggest you two ways:
1 - Create a Master/Detail structure. tbl_reservations to store master data, the current one and tbl_reservations_files to store file names for each reservation.
2 - Store file name as string, like CSV.
This is the code for solution 2:
public function insert(){
$uploadedFiles = $this->uploadFile(); // returns the file names array
// Map post data to table field
$data = array(
'visittype' => $this->input->post('visittype'),
'date' => $this->input->post('date'),
'time' => $this->input->post('time'),
'reasons' => $this->input->post('reasons'),
'symptoms' => $this->input->post('symptoms'),
'doctor_id' => $this->input->post('doctorid'),
'user_id' => $this->session->userdata('doctor')[0]->user_id
);
// Reduce file list as a CSV string
$data['file_name'] = array_reduce($uploadedFiles, function ($carry, $item) {
// $carry is the value from previews iteration, $item is current array item. see array_reduce on php doc for more.
// ',' can be replaced with any char of your need
return $carry . ($carry === '' ?: ',') . $item['file_name'];
}, '');
// Insert data on DB
$this->Reservation_model->insert_data($data);
}
Change
echo $new_array, die;// here it is return word "ARRAY"}}
To
print_r($new_array);
As $new_array is array, you need to print array using print_r or var_dump. Using echo will show Array as it is an array. Also don't use die, it will stop script and you won't be able to insert second image.

How to compute tf-idf from multiple text files in php?

I'm successfully computing tf-idf from an array. Now I want that tf-idf should be computed from multiple text files as I have multiple text files in my directory. Can anyone please modify this code for multiple text files so that first all the files in the directory should read and then on the basis of these files contents tf-idf computed.. Below is my code thanks...
$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);
Computing tf-idf
$index = $temp;
$docCount = count($index['docCount']);
$entry = $index['dictionary'][$term];
foreach($entry['postings'] as $docID => $postings) {
echo "Document $docID and term $term give TFIDF: " .
($postings['tf'] * log($docCount / $entry['df'], 2));
echo "\n";
}
Have a look at this answer: Reading all file contents from a directory - php
There you find the information how to read all the file contents from a directory.
With this information you should be able to modify your code by yourselve to get it work like expected.

Printing more than the first row of array

The code below scrapes two values from a webpage and adds them to an array. I've got as far as being able to print the first row of that array but I'm unable to get the whole thing.
I presume some sort of loop will be required but my attempts so far have been unsuccessful.
I feel this should be fairly basic. Any idea what I can do to achieve the desired result?
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query("$product_location");
if ($row->length > 0) {
foreach ($row as $location) {
$products['product_url'] = $product_url_root.$location->getAttribute('href');
$products['shop_name'] = $shop_name;
$row = $xpath->query($photo_location);
/* FIND LINK TO IMAGE */
if ($row->length > 0) {
foreach ($row as $location) {
$products['photo_url'] = $photo_url_root.$location->getAttribute('src');
}
}
}
print_r($products);
}
}
EDIT
I should say that I'm hoping to get the array in this format:
Array (
[0] {product_url => 123, shop_name => name, photo_url => abc},
[1] {product_url => 456, shop_name => name, photo_url => def},
[2] {product_url => 789, shop_name => name, photo_url => ghi},
)
The plan is eventually to be able to use the following code in the place of print_r($products) to create an XML file:
$item = $channel->addChild("item");
$item->addChild("product_url", $entry['product_url']);
$item->addChild("shop_name", $entry['shop_name']);
$item->addChild("photo_url", $entry['photo_url']);
You'll need the following details to create the associative array you need:
the product URL
the shop name
the product image URL
Now, in your code, you're looping through the product URLs — and for each product URL, you're looping through the list of product image URLs. This will cause the code inside the nested foreach to be executed n^2 times. You do not want that.
Here's how you should structure your loops:
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i]
);
}
print_r($result);

PHP MySQL multiple image URL fields array

In building a website for a friend the database has a row with 39 fields for images.
In the field is the name of the image (e.g. "my_image.jpg") not the image itself (BLOB).
i.e.: image_01, image_02, image_03 and so forth.
I have PHP generating the while loop and getting the information without problems.
I'm trying to get all the images into one array so I can display the pictures from that one row as a gallery.
I hope someone can offer me a way forward as I've tried without success.
from while loop:
$MEDIA_IMAGE_00 = $row["MEDIA_IMAGE_00"];
$MEDIA_IMAGE_01 = $row["MEDIA_IMAGE_01"];
$MEDIA_IMAGE_02 = $row["MEDIA_IMAGE_02"];
I need to echo out as
["propimages/$MEDIA_IMAGE_00", "", "", "$MEDIA_IMAGE_TEXT_00"],
["propimages/$MEDIA_IMAGE_01", "", "", "$MEDIA_IMAGE_TEXT_01"],
["propimages/$MEDIA_IMAGE_02", "", "", "$MEDIA_IMAGE_TEXT_02"]
for them to display in a gallery.
EDIT:
while($row = mysql_fetch_array($sqlSearch)){
$propid = $row["propid"];
$MEDIA_IMAGE_00 = $row["MEDIA_IMAGE_00"];
$MEDIA_IMAGE_01 = $row["MEDIA_IMAGE_01"];
$MEDIA_IMAGE_02 = $row["MEDIA_IMAGE_02"];
$MEDIA_IMAGE_33 = $row["MEDIA_IMAGE_33"];
$MEDIA_IMAGE_34 = $row["MEDIA_IMAGE_34"];
$MEDIA_IMAGE_35 = $row["MEDIA_IMAGE_35"];
}
I'm assuming that $propid is what identifies the row itself and that 'MEDIA_IMAGE_TEXT' is available in the same row:
$properties = array();
while ($row = mysql_fetch_array($sqlSearch)) {
$propid = $row["propid"];
$images = array();
for ($i = 0; $i <= 35; ++$i) {
$imageId = "MEDIA_IMAGE_" . str_pad($i, 2, '0', STR_PAD_LEFT);
if ($row[$imageId]) {
$images[] = array(
$row[$imageId],
'',
'',
$row["MEDIA_IMAGE_TEXT_" . str_pad($i, 2, '0', STR_PAD_LEFT)],
);
}
}
$properties[] = array(
'id' => $propid,
'images' => $images,
);
echo json_encode($properties);
It generates a list of properties, each having an id and an array of images; each image comprises the location (I guess) and the title / description.
Why don't you build an array of images in your while loop ?
$images = array()
$i = 0;
While(...) {
$images[] = $row["MEDIA_IMAGE_0$i"];
$i++;
[...]
}
The you get an array that you ca use in a foreach and display your row(s). On the principle that should work, i think ;)

Output of a query displaying as null

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

Categories