codeigniter insert many images name into database - php

I am build uploader images and store it into database, I already can upload many images to folder, but I can't insert all images name that uploaded, and I don't know how to insert into database, first I have put commend on my code below when error occur, second I don't know the query to put it in database if the image count is different e.g 1-10 images, last question, if I do query "SELECT id..." and I want to return it, is there method to return it into string or int? If I use row() it will return stdClass object. please help me,
below is my code:
controller :
$this->load->library("myupload", "form_validation");
$this->load->model("testModel");
$barangImage = array();
if($this->input->post("formSubmit")) {
$this->form_validation->set_rules("nama", "Nama", "required|trim");
if($this->form_validation->run()) {
$insertData = array(
"nama" => $this->input->post("nama")
);
if($id = $this->testModel->add($insertData)) {
//print_r($id);
if(isset($_FILES) && $image = $this->myupload->uploadFile($_FILES)) {
//$image here is already fill with all images name
if(isset($image["error"]) && $image["error"]) {
echo $image["error"];
}else {
foreach($image as $img) {
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
//but when i put into barangImage,
//it only stored last image name
print_r($barangImage);
//output `Array ( [gambar] => 2.JPG [barangid] => Array ( [id] => 52 ) )`
}
}
if($id = $this->testModel->add_images($barangImage)) {
echo "SUCCESS !!!";
}else {
echo "FAIL INSERT IMAGES!!!";
}
}else {
echo "FAIL INSERT DATA NAMA";
}
}else {
echo "FAIL VALIDASI RUN";
}
}
model :
public function add($newData){
$this->db->insert("cobabarang", $newData);
$nama = $newData["nama"];
$id = $this->db->query("SELECT id FROM cobabarang WHERE nama = \"$nama\"");
return $id->row_array();
}
public function add_images($newImage) {
//$this->db->insert("cobagambar", $newImage);
$id = $newImage["barangid"]["id"];
$gambar = $newImage["gambar"];
$this->db->query("INSERT INTO cobagambar(barangid, gambar1) VALUES($id, \"$gambar\")");
}

there is an error here:
foreach($image as $img)
{
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
change the $barangImage to $barangImage[]
when you put the images into database i suggest that using json_encode($barangImage), and then json_decode($images-json-string) when you going to use the images.

There is something wrong with your foreach loop
foreach($image as $img) {
$barangImage = array(
"gambar" => $img //might be img['img'] I guess $img is again an array...you hvae to check that
"barangid" => $id //might be $img['id']check on this too..will be $img['id'] I guess
);
}
My guess is that $img is again an array with some keys. You really need to check on that And you can directly call the insert function in that foreach loop itself like this,
foreach($image as $img) {
$barangImage = array(
"gambar1" => $img['img'], //I guess $img is again an array...you hvae to check that
"barangid" => $img['id'] //check on this too..will be $img['id'] I guess
);
$id = $this->testModel->add_images($barangImage));
}
NOTE: The keys in your array barangImage must be column name in the table. i.e
gambar1 and barangid will be your column names. so you can directly use codeIgniter's active records.
Just change your add_images function
public function add_images($newImage) {
$this->db->insert("cobagambar", $newImage);
}

Related

Removing document root from file path Zend Framework 2

I'm trying to display an image but I am running into the error of Not allowed to load local resource: file:///C:/xampp/htdocs/public/images/profile/jimmy/status/boned.jpg in the browser console. What I am trying to do is use the base path provided by Zend Framework 2 but I'm retrieving the images in the model so (as far as I know), I can't use $this->basePath() like I would in the view.
This is my json string I am returning but would like to just be able to return /images/profile/jimmy/status/boned.jpg and whatever other images are in there.
I'm getting all the files outside of the directory 'status'. I am trying to get the files inside the status directory. When I did a var_dump this is what I get string(43) "C:\xampp\htdocs/public/images/profile/jimmy" I'm unclear why it is omitting the status directory after '/jimmy'
json string being returned:
{"feed":{"username":"Timmy","status":["this is jimmy, test"],"images":["videos","status","sithtoon.jpg","sith.jpg","edited_photos","diploma.jpg","current","albums","Screenshot_2016-08-09_21_28_13_361272.jpg","Screenshot_2016-08-05_17_55_48_500802.jpg","515gIIJ-Imgur.png",".htaccess"]}}
Here is the relevant PHP code (in the model):
public function listFriendsStatus()
{
$user_id = $this->getUserId()['id'];
// get the friend ids based on user id
// and then compare the friend id to the id in status table
$friend_query = new Select('friends');
$friend_query->columns(array('friend_id'))
->where(array('user_id' => $user_id));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($friend_query),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
$friend_id = array();
foreach ($query as $result) {
$friend_id[] = $result['friend_id'];
}
$status = new Select('status');
$status->columns(array('status'))
->where(array('id' => $friend_id));
$status_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($status),
Adapter::QUERY_MODE_EXECUTE
);
if ($status_query->count() > 0) {
// check if a image was used
$members = new Select('members');
$members->columns(array('username'))
->where(array('id' => $friend_id));
$image_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($members),
Adapter::QUERY_MODE_EXECUTE
);
if ($image_query->count() > 0) {
foreach ($image_query as $value) {
if (is_dir(getcwd() . '/images/profile/' . $value['username'] . '/status/')) {
$status_dir = pathinfo(getcwd() . '/images/profile/' . $value['username'] . '/status/');
}
}
$images = array();
chdir($status_dir['dirname']);
var_dump($status_dir['dirname']);
// retrieve the image inside the status directory
foreach (array_diff(scandir($status_dir['dirname'], 1), array('.', '..')) as $values) {
$images[] = $values;
}
} else {
throw new FeedException("The user does not exist in the user table.");
}
$status = array();
// get all the statuses
foreach ($status_query as $rows) {
$status[] = $rows['status'];
}
return array('username' => ucfirst($value['username']), 'status' => $status, 'images' => $images); // how to just get the basePath path with zf2
} else {
throw new FeedException("No status was found for your friends.");
}
} else {
throw new FeedException(sprintf("Could not locate any friends for %s", $this->user));
}
}
controller code:
public function getfriendstatusAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
try {
echo json_encode(array('feed' => $this->getStatusService()->listFriendsStatus()));
} catch (FeedException $e) {
echo json_encode(array('fail' => $e->getMessage()));
}
return $view_model;
}
jquery code:
$.getJSON('/members/feed/get-friend-status', function(data) {
$.each(data, function(i, item) {
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('h4').html(data[i].username);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('p').html(data[i].status);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('img').attr('src', data[i].images);
});
}).fail(function(response) {
console.log(response);
});
I've been trying to use other directory functions provided with PHP but if I try anything, I run into the error directory could not be found. Basically what I am trying to do is use the similiar approach of $this->basePath() but in a model.
I hope that is clear enough..
Thanks!
Here is a screenshot of what I'm getting and how I want to get the status directory, not the directory outside of it.
I have an idea.
In your code is:
$status_dir = pathinfo(getcwd() . '/images/profile/' . $value['username'] . '/status/');
// ..............
chdir($status_dir['dirname']);
var_dump($status_dir['dirname']);
Try:
var_dump($status_dir);
I guess 'status' will be in 'basename' and / or in 'filename'
pathinfo gets last segment of argument string path as 'basename'.
Pathinfo only parses string as path and return array info, don't check it for isDir or isFile. Your correct chdir should looks like chdir($status_dir['dirname'] . '/' . $status_dir['basename'] ); if you need use of pathinfo.
In other words: dirname of 'images/profile/jimmy/status' is 'images/profile/jimmy' and its a reason why you don't see status in var_dump($status_dir['dirname']) and why chdir($status_dir['dirname']) not working correctly.

Multiple Insert with dropdown codeigntier

I have3 table with name frm_data_aset,frm_monitor,frm_lokasi
I want if I insert on frm_data_aset column monitor_aset with dropdown from tabel monitor and lokasi from tabel lokasi. on table monitor column lokasi updated with data same at I insert from tabel data_Aset
this my structure :
enter image description here
enter image description here
now I get error :
Unknown column 'frm_monitor' in 'where clause'
UPDATE frm_monitor SET lokasi_monitor = '123' WHERE frm_monitor IS NULL
this my controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id= $this->input->post('kd_monitor', TRUE);
$data = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data);
$this->M_data_aset->insert($data);
redirect(site_url('data_aset'));
}
}
this my model M_monitor
function update_lokasi($id,$data){
$this->db->where('frm_monitor', $id);
$this->db->update('frm_monitor', $data);
}
and this my dropdown monitor at form insert data_aset
<option value="0">Pilih Monitor</option>
<?php
$monitor = $this->db->get('frm_monitor')->result();
foreach ($monitor as $row){
echo "<option value='$row->kd_monitor' ";
echo $row->kd_monitor==$monitor_aset?'selected':'';
echo ">". strtoupper($row->kd_monitor)."</option>";
}
?>
try changing your model query as like this
function update_lokasi($id,$data){
$this->db->where('id_monitor', $id);
$this->db->update('frm_monitor', $data);
}
Before that make sure that the post for 'kd_monitor' in the controller is not null
You should rename the $data variable being passed to $this->M_monitor->update_lokasi() because it will overwrite $data that is going to be passed to $this->M_data_aset->insert() with only 'lokasi_monitor' array on it. Or even better try rename both $data to prevent confusion.
Modify your controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data_aset = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id = $this->input->post('kd_monitor', TRUE);
$data_monitor = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data_monitor);
$this->M_data_aset->insert($data_aset);
redirect(site_url('data_aset'));
}
}
And change 'frm_monitor' to 'kd_monitor' on the conditional query :
function update_lokasi($id,$data){
$this->db->where('kd_monitor', $id);
$this->db->update('frm_monitor', $data);
}

Database error 1452

I'm working on this project that have foreign keys on two tables. By using a form I'm trying to insert a new record to the database. And there's also an image path in the db and I'm inserting the image path via the form. I'm using codeigniter file upload library. Other fields of the database table get updated when i submit the form even the foreign key field. But the image path is not updating. When I submit the form it shows this error.
A Database Error Occurred
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`bfh`.`products`, CONSTRAINT `category_fk` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`))
INSERT INTO `products` (`img`) VALUES ('assets/img//sakya.PNG')
Filename: C:/xampp/htdocs/CI-skeleton/system/database/DB_driver.php
Line Number: 691
Controller
public function add_product()
{
$result = 0;
$cat_id = $this->input->post("category_id");
$type_id = $this->input->post("type_id");
$pname = $this->input->post("p_name");
$images = $this->input->post("images");
$images = $_FILES['images']['name'];
$price = $this->input->post("price");
$this->load->model("Products_Model");
$product_id = $this->Products_Model->add_product( $cat_id, $type_id, $pname, $price);
if ($product_id != 0) {
$result = $this->Products_Model->add_product_images($images);
}
if ($result && $_FILES['images']['name'][0] != "") {
$this->load->model('Image_Upload');
$result = $this->Image_Upload->upload("assets/img");
}
$this->session->set_flashdata('result', $result);
redirect('Products');
}
Model
public function add_product( $cat_id, $type_id, $pname, $price)
{
$result = $this->db->get_where("products", array('name' => $pname));
if ($result->num_rows() != 0) {
return 0; // record already exists
} else {
$data = array(
'category_id' => $cat_id,
'type_id' => $type_id,
'name' => $pname,
'price' => $price
);
if( !$this->db->insert('products', $data)) {
return -1; // error
}else{
return $this->db->insert_id();
}
return 1; // success
}
}
public function add_product_images($images)
{
$path = "assets/img/";
foreach ($images as $image) {
// if no images were given for the item
if ($image == "") {
return 1;
}
$data = array(
'img' => $path."/".$image
);
if ( ! $this->db->insert('products', $data)) {
return 0; // if something goes wrong
}
}
return 1;
}
You should use "update" query on the behalf of insert in add_product_images().
Because "insert" will add a new record of the product and there is no any category id(Foreign Key) with this that's why shows this error.
So try to update image.
you have two variables with the same name and thats the problem.
You need have different variable name.
I hope this will help you.
there are some problems in this script
if model you wrote, function add product. if your query failed, returns -1 otherwise return product Id
but if product was in database it returns 0, then in controller: you check if product_id != 0 then insert images. so you don't care if product didn't exists in database, you failed you insert that in table or not
in add_product_images you check if ($image == "") . I don't understand how you get that image array ($images) is empty if this statement is true. you can check if (sizeof($images) == 0) before foreach to check emptiness of image array ($images)

PDO Update 1 column multiple rows with array

I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}

Only the first IF statement out of 3 is executed within a PHP loop

The following code uploads multiple images no problem. However, I'm trying to get it to update a field in a table based on what iteration the loop is in. PROBLEM: The IF Statement seems to not work when looped. I.e. it only adds the first file_name to the database.
Anyone see what I'm doing wrong here? Much appreciated if so!!!
for ($i = 1; $i < 4; $i++)
{
/* Handle the file upload */
$upload = $this->upload->do_upload('image' . $i);
/* File failed to upload - continue */
if ($upload === FALSE)
continue;
/* Get the data about the file */
$data = $this->upload->data();
$uploadedFiles[$i] = $data;
if ($i == 1)
{
$filenames1 = array(
'product_image_front' => $data['file_name'],
);
$this->db->where('id', $this->db->insert_id());
$this->db->update('products', $filenames1);
}
if ($i == 2)
{
$filenames2 = array(
'product_image_back' => $data['file_name'],
);
$this->db->where('id', $this->db->insert_id());
$this->db->update('products', $filenames2);
}
if ($i == 3)
{
$filenames3 = array(
'product_image_back' => $data['file_name'],
);
$this->db->where('id', $this->db->insert_id());
$this->db->update('products', $filenames3);
}
}
insert_id - Get the ID generated in the last query.
Store it in a variable before the loop.

Categories