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.
Related
I am importing rims from an csv file to a webshop project. nothing for sell, just a personal project for learning how importers work.
I am trying to map my $EANColumn variable to the first row field name in my csv.
So currently i have a csv with the following fields :
EAN;Brand;...and-more-comming
1234-WB;WheelBrand...and-more-comming
5678-BW;BrandWheel...and-more-comming
At the moment in my importer, it works when i map:
$EANColumn = str_replace('’', '', $importData_arr["EAN"]);
And inserting it to my database through an array :
foreach($importData_arr as $importData){
// var_dump($importData);
$insertData = array(
"EAN" =>$EANColumn);
RimsUpload::insertData($insertData);
My complete code for this part is here :
if ($request->input('submit') != null ){
$file = $request->file('file');
// File Details
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$tempPath = $file->getRealPath();
$fileSize = $file->getSize();
$mimeType = $file->getMimeType();
// Valid File Extensions
$valid_extension = array("csv");
// 2MB in Bytes
$maxFileSize = 2097152;
// Check file extension
if(in_array(strtolower($extension),$valid_extension)){
// Check file size
if($fileSize <= $maxFileSize){
// File upload location
$location = 'uploads';
// Upload file
$file->move($location,$filename);
// Import CSV to Database
$filepath = url($location."/".$filename);
// Reading file
$file = fopen($filepath,"r");
$importData_arr = array();
$i = 0;
while (($filedata = fgetcsv($file, 1000, ";")) !== FALSE) {
$num = count($filedata );
$EANColumn = str_replace('’', '', $importData_arr["EAN"]);
$BrandColumn = $importData_arr["Brand"];
// Skip first row (Remove below comment if you want to skip the first row)
if($i == 0){
$i++;
continue;
}
for ($c=0; $c < $num; $c++) {
$importData_arr[$i][] = $filedata [$c];
}
$i++;
}
fclose($file);
dump($importData_arr);
// Insert to MySQL database
foreach($importData_arr as $importData){
// var_dump($importData);
$insertData = array(
"EAN" =>$EANColumn,
"Brand"=>$BrandColumn,
"Name"=>$importData[2],
"Size"=>$importData[3],
"PCD"=>$importData[4],
"Offset"=>$importData[5],
"Bore"=>$importData[6],
"Color"=>$importData[7],
"Price"=>$importData[8],
"Stock"=>$importData[9],
"ImageURL"=>$importData[10]);
RimsUpload::insertData($insertData);
}
Session::flash('message','Import Successful.');
}else{
Session::flash('message','File too large. File must be less than 2MB.');
}
}else{
Session::flash('message','Invalid File Extension.');
}
}
// Redirect to index
// return redirect()->action("RimsUploadController#index", [$request]);
return response()->redirectToAction('App\Http\Controllers\RimsUploadController#index', [$request]);
}
But the real problem is that i do not want to map my columns like [0],[1],[2],[3]...
I would like to take them from the first row colum name : ["EAN"],["Brand"],["Name"],["Size"]...
So if EAN is column 1 or column 7, it wont make a difference, since it will detect it by name and not by row number.
So it will then be able to handle files with different column orders.
When trying to do this, i get the error :
Undefined index: EAN on $EANColumn = str_replace('’', '', $importData_arr["EAN"]);
The whole point is to make an easy way to import data from suppliers through csv into mysql. then display it to the webshop site.
Before your while loop, extract the field names from the first row of your csv:
$file = fopen($filepath,"r");
$keys = fgetcsv($file, 1000, ';');
Then, fetch the data lines and combine the $keys array with the data into an associative array:
$importData_arr = [];
while ($line = fgetcsv($file, 1000, ';')) {
$data = array_combine($keys, $line);
// Do something with the data
$data['EAN'] = str_replace('’', '', $data['EAN']);
$importData_arr[] = $data;
}
fclose($file);
You can now access all data fields by their name, independent of the order in the CSV:
foreach($importData_arr as $importData){
echo $importData['EAN'];
}
As long as the field names stay intact, you don't have to change your import code when the field order or count changes.
Here is some simple proposal how to map your data to an array with given keys.
while ($row = fgetcsv($fp, 100, ',')) {
$columnName = ['a','b','c','d','e','f'];
$myRow = array_combine($columnName,$row);
....
I have a variable $a='san-serif' and an array Font_list[] now I want only the arrays whose category is 'san-serif' will be filtered. I tried a lot of codes nothing seems working here is my code:-
public function filterFont() {
$a = $_POST['key'];
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=''";
$result = json_decode(file_get_contents( $url ));
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
$filter = filter($font_list);
print_r(array_filter($font_list, $filter));
}
Please help me :-(
What i understood according to that you want something like below:-
<?php
$a='san-serif'; // category you want to search
$font_list=Array('0'=>Array('font_name' => "sans-sherif",'category' => "san-serif"),'1'=>Array('font_name' => "times-new-roman",'category' => "san-serif"),'2'=>Array('font_name' => "sans-sherif",'category' => "roman"));
// your original array seems something like above i mentioned
echo "<pre/>";print_r($font_list); // print original array
$filtered_data = array(); // create new array
foreach($font_list as $key=>$value){ // iterate through original array
if($value['category'] == $a){ // if array category name is equal to serach category name
$filtered_data[$key] = $value; // assign that array to newly created array
}
}
echo "<pre/>";print_r($filtered_data); // print out new array
Output:- https://eval.in/597605
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"
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);
}
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']; }