Retrieving Image from folder using codeigniter - html

I want to retrieve image from folder and rest of data from database using CodeIgniter.
Right now I am able to retrieve data only from database.
Can anyone explain how to get an image from any folder and display it in a web page.

Follow this procedure:
Model
function getDataByID ($user_id)
{
$q = $this->db->query("SELECT name, image FROM tbl_user WHERE user_id = $user_id");
if ($q->num_rows() > 0) {
$d = $q->row_array();
if ($d['image'] != '') {
$temp = $d['image'];
$d['image'] = "http://domain.com/myimages/".$temp;
} else {
$d['image'] = '';
}
return $d;
} else {
return array();
}
}
Controller
function user_detail($user_id)
{
$dt = $this->code_model->getDataByID($user_id);
$display['user_data'] = $dt;
$this->load->view('user_view',$display);
}
View
if(isset($user_data) && !empty($user_data)) {
extract($user_data);
} ?>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-6">
<?php echo $name; ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Image</label>
<div class="col-lg-6">
<img src="<?=$image?>">
</div>
</div>

I am not sure how you are constructing the page, but the easiest way to add an image is to set the data to a variable in PHP and adding it to the <img> tag:
<img src="{base_url}_assets/_images/folder/<?=$productData[0]->Image1?>" />

Related

How can I store an image to the database from modal?

I want to store an Image through a modal, usually, I store images this way. But it never stores, it stores null on the database, like the file wasn't even uploaded. Everything else on the modal stores perfectly, except the image.
This is the code for the image on my controller.
if($request->hasFile('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time() .'.'.$extension;
$file->move('uploads/event/',$filename);
$event->image = $filename;
}
In my view, this is how I upload the image.
<div class="text-center">
<img src='http://ssl.gstatic.com/accounts/ui/avatar_2x.png' width="300px" height="300px" class="avatar img-circle img-thumbnail" alt="avatar" name="image" >
</div><hr>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="image" >
<label class="custom-file-label">Upload picture</label>
</div>
</div>
For the code I had, the only problem was that I didn't use the enctype="multipart/form-data". After looking for options, I found this and wrote it on the form of action and form-group div. It worked, the image stores and it also updates.
<form action="{{action('CalendarController#store')}}" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="modal-body">
<div class="form-group" enctype="multipart/form-data">
Since I got this working I will start implementing other codes for better performance and start to learn about the Storage in laravel. Thanks to all of you!
Try this on your Controller:
use Image;
public function store(CreateRequest $request)
{
$file = $request->file('image');
$imagename = $file->getClientOriginalName();
$imageext = $file->getClientOriginalExtension();
$path = 'upload/image/'.time().'.'.$imageext;
$image = Image::make($file);
$image->save($path);
$input = $request->all();
$input['image'] = $path;
$user = $this->userRepository->create($input);
return redirect(route('users.index'));
}
do the same with update() function
The file will store in /public/upload/image folder
You can also try and use the 'Intervention\Image' and File class:
composer require intervention/image
<?php
...
use File;
use Intervention\Image\Facades\Image
...
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'image.'.$image->getClientOriginalExtension();
$save_path = storage_path().'uploads/event/';
$path = $save_path.$filename;
$public_path = 'uploads/event/'.$filename;
// Make the user a folder and set permissions
File::makeDirectory($save_path, $mode = 0755, true, true);
// Save the file to the server
Image::make($image)->resize(300, 300)->save($save_path.$filename);
// Save the public image path
$event->image = $public_path;
$event->save();
}
return response()->json(['path' => $path], 200);
} else {
return response()->json(false, 200);
}

How to insert and update multiple selected values with codeigniter?

So I have a problem with many to many relationships.
Currently, I have surat and surat_user table.
How do I insert data into surat and at the same time insert multiple values from select2 multiple forms into surat_user table and how to get data so I can update it.
UPDATE :
I solve the insert problem please see answer below
But now i have no idea how to update those values.
For example
surat_user
id_surat | id_user
1 | 1
1 | 2
How to update surat_user (in controller and model) if i want to remove one of id_user where 'id_surat = 1`
At the moment i don't know how to fetch the multiple values into select2 form edit so here is mu uncomplete codes :
Controller
public function edit_sm($id_surat){
$this->load->view('template/header');
$this->load->view('template/sidebar');
$where = array('id_surat' => $id_surat);
//$data=array('id_status'=> $this->M_sm->get_option());
$data['surat'] = $this->M_sm->edit_sm($where,'surat')->result();
$this->load->view('v_edit_surat',$data);
$this->load->view('template/footer');
}
public function edit_sm_proses() {
$data = array(
'id_surat'=>$this->input->post('id_surat'),
'no_surat'=>$this->input->post('no_surat'),
'id_status'=>$this->input->post('id_status'),
'id_user'=>$this->input->post('id_user')
);
$where = array(
'id_surat' => $id_surat
);
$this->M_sm->edit_sm_proses($where,$data,'surat');
redirect('SuratMasuk');
}
Model:
public function edit_sm($where,$table){
$this->db->join('status_surat', 'status_surat.id_status = surat.id_status');
return $this->db->get_where($table,$where);
}
public function edit_sm_proses($where,$data,$table){
$this->db->where($where);
$this->db->update($table,$data);
}
View
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box box-solid box-primary"">
<div class="box-header with-border">
<h3 class="box-title">Default Box Example</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<?php foreach ($surat as $key) { ?>
<form method="post" action="<?php echo base_url()."SuratMasuk/edit_sm_proses" ?>" enctype="multipart/form-data" />
<input type="hidden" name="id_surat" value="<?=$key->id_surat?>">
<div class="form-group">
<label class="control-label col-lg-2">No Surat</label>
<div class="col-lg-5">
<input type="text" name="no_surat" class="form-control no_surat" placeholder="Masukkan Nomor Surat" value="<?=$key->no_surat?>">
<span class="help-block"></span>
</div>
</div>
<br>
<br>
<div class="form-body">
<div class="form-group">
<label class="control-label col-lg-2">Status</label>
<div class="col-lg-5">
<select class="form-control select2 id_status" name="id_status" style="width: 100%;">
<option value="<?=$key->id_status;?>" selected="<?=$key->id_status;?>"><?php echo $key->status;?></option>
<?php foreach ($id_status as $row) { ?>
<option value="<?php echo $row->id_status; ?>"> <?php echo $row->status; ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
<br>
<br>
<div class="form-body">
<div class="form-group">
<label class="control-label col-lg-2">Disposisi</label>
<div class="col-lg-5">
<select class="form-control select2 id_user" name="id_user[]" style="width: 100%;">
<option value="<?=$key->id_user;?>" selected="<?=$key->id_user;?>"><?php echo $key->nama;?></option>
<?php foreach ($id_user as $row) { ?>
<option value="<?php echo $row->id_user; ?>"> <?php echo $row->nama; ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-danger" type="reset" value="reset">Reset</button>
<button class="btn btn-info">Update</button><br>
Kembali
</form>
<?php
}
?>
</div>
<!-- box-footer -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
Current Result :
result from codes above
Manage to solve the problem by my self.
i change my controller to this:
public function add_sm_proses(){
$data = array(
'no_surat'=>$this->input->post('no_surat'),
'id_status'=>$this->input->post('id_status')
);
$insert = $this->M_sm->trans_surat_user($data);
if($insert=1){
redirect('SuratMasuk');
} else {
echo "<h2>Gagal menambahkan data</h2>";
}
}
change my model to this :
public function trans_surat_user($data){
$this->db->trans_start();
$this->db->insert('surat', $data);
$id_surat = $this->db->query('SELECT surat.id_surat FROM surat ORDER BY id_surat DESC limit 1');
foreach ($id_surat->result() as $row) {
$id_surat_result = $row->id_surat;
}
$id_user = $_POST['id_user'];
foreach ($id_user as $data2) {
array_push($id_user, $data2);
$this->db->query('INSERT INTO surat_user (id_surat,id_user) VALUES ('.$id_surat_result.','.$data2.')');
}
$this->db->trans_complete();
}
class SuratMasuk extends CI_Controller {
public function add_sm_proses(){
$data = array(
'no_surat'=>$this->input->post('no_surat'),
'id_status'=>$this->input->post('id_status'),
);
Select MAX ID from table like this
$id_surat = $this->db->query('SELECT MAX(surat.id_surat) AS maxid FROM surat')->row()->maxid;
Update:-
$id_surat will give MAX ID present in the table. Don't use for next record.
First, Increment it by value 1 and then use it
$id_surat = $id_surat + 1;
$id_user = $this->input->post('id_user') ? $this->input->post('id_user') : array();
First, check if $id_user have values or not otherwise foreach loop will give e error
if(count($id_user) > 0){
foreach ($id_user as $u){
$data_values = array('id_surat' => $id_surat, 'id_user' => $u);
$this->db->insert('surat_user', $data_values);
}
}
$insert = $this->M_sm->add_sm($data);
$insert will not always return 1. So, only check if value exists
if($insert){
redirect('SuratMasuk');
} else {
echo "<h2>Gagal menambahkan data</h2>";
}
}
}
First, Show all record from DB and for each record add a button to edit the record.
Note:- Don't use <form> inside the loop
<a class="btn btn-warning btn-sm" href="<?= base_url('SuratMasuk/edit_sm/'.$row->id_surat)?>"><i class="fa fa-pencil-square-o" aria-hidden="true"></i>Edit</a>
Controller for Edit
I'm just adding backend code here
where and table is reserved word for DB. It is better to not use it or use in another way.
public function edit_sm($id_surat){
$condition_array = array('id_surat' => $id_surat);
$data['surat'] = $this->M_sm->edit_sm($condition_array ,'surat');
}
Model for Edit
Get the record for edit
This function is getting only one record from DB so use row()
public function edit_sm($condition_array ,$record_in){
$this->db->join('status_surat', 'status_surat.id_status = surat.id_status');
return $this->db->get_where($record_in, $condition_array )->row();
}
Now, Form for will show with data populated in it.
Getting updated data from Controller
public function edit_sm_proses() {
$data = array(
'id_surat'=> $this->input->post('id_surat'),
'no_surat'=>$this->input->post('no_surat'),
'id_status'=>$this->input->post('id_status'),
'id_user'=>$this->input->post('id_user')
);
$condition_array = array(
'id_surat' => $this->input->post('id_surat')
);
$this->M_sm->edit_sm_proses($condition_array, $data, 'surat');
redirect('SuratMasuk');
}
Updating data in Model
public function edit_sm_proses($condition_array, $data, $record_in){
$this->db->where($condition_array);
return $this->db->update($record_in, $data);
}

Align loop output in one row

I have this code in which the image output $check or $uncheck and title $val_c are inside a loop, what i want is to output everything in one row using <div class="col-sm-12"> but what i always get is a column. what i want is like this
image_title_______________image_title________________image_title
what im getting is like this...
image
title
image
title
image
title
heres is the code
<div class="panel-body">
<div class="col-sm-12">
';
$funcs->viewSurvey();
$array4 = $funcs->viewSurvey();
$searchengine = $array4['searchengine'];
$sum = $array4['sum'];
$searches = explode(',', $searchengine);
$searchesa = array("google","yahoo","bing");
$check = '<img src="images/checked.png" height="40px" width="40px">';
$uncheck = '<img src="images/unchecked.png" height="40px" width="40px">';
foreach ($searchesa as $key_a => $val_c) {
$found = false;
foreach ($searches as $key_b => $val_d) {
if ($val_c == $val_d) {
echo ''.$check.'<h3 class="head8">'. $val_c.'</h3>' ;
$found = true;
}
}
if (!$found)
echo ''.$uncheck.'<h3 class="head8">'. $val_c.'</h3>' ;
}
echo '
</div>
</div>
Use this style
h3 {
display:inline;
}
I already solved it. i just placed the <div class="col-sm-12"> inside the first foreach.

Organizing database content with jquery mobile using php

So I have this code :
<div data-role="content" class="ui-widget-content" align="justify">
<div class="ui-grid-a">
<div class="ui-block-a" id="clients"><strong>Clients</strong></div>
<div class="ui-block-b" id="freelancers"><strong>Freelancers</strong></div>
<?php
$sql = "SELECT * FROM users";
$query =mysqli_query($link,$sql) or die(mysqli_error($link));
$checkuser= mysqli_num_rows($query);
if ($checkuser > 1) {
while($row = mysqli_fetch_assoc($query)) {
extract($row);
if ($usertype == 'client') {
echo '<div class="ui-block-a" align="justify"> '.ucfirst($username).'</div>';
}
if ($usertype == 'freelancer') {
echo '<div class="ui-block-b" align="justify"> '.ucfirst($username).'</div>';
}
}
}
mysqli_close($link);
?>
</strong></div>
And it gives out this result :
Can someone help me understand why the second column freelancers displays the data spaced like that and what I need to change in my code to make it look like the first column, without that vertical spacing ?

How To Display Error Messages With Wufoo API V3?

I am using the Wufoo API V3 to submit data from a form hosted on my website to my Wufoo account. I followed the example on the [Entries POST API][1] page, and I was able to successfully the data to my account.
I was wondering how I am able to check for error messages, and display the ErrorText for each text input field using PHP?
For example, if someone does not provide their email address in a required email field.
Here is the code I have so far:
<?
function submit() {
$ref = curl_init('https://myname.wufoo.com/api/v3/forms/xxxxxx/entries.json');
curl_setopt($ref, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
curl_setopt($ref, CURLOPT_POST, true);
curl_setopt($ref, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ref, CURLOPT_POSTFIELDS, getPostParams());
curl_setopt($ref, CURLOPT_USERPWD, 'XXXX-XXXX-XXXX-XXXX');
curl_setopt($ref, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ref, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ref, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ref, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ref, CURLOPT_USERAGENT, 'Wufoo.com');
$response = curl_exec($ref);
echo $response;
}
function getPostParams() {
return array( 'Field4' => "you#company.com");
}
submit();
?>
UPDATE (Nov 12, 2011):
MinisterOfPower,
Thanks for [the reply and advice][2] about the Wufoo PHP API Wrapper. I am now using the API Wrapper and it rocks. I am having some challenges integrating the code you provided with my form.
For example, if I have a form on index.php (see below) with an email required field. How would I be able to set up the API wrapper to display an error next to the appropriate input field after the form is submitted?
Here's the code for index.php:
<? require_once('my-wrapper.php'); ?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form1" name="form1" autocomplete="off" enctype="multipart/form-data" method="post" action="">
<div>
<label id="email" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg"/>
</div>
<div>
<label id="name" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg"/>
</div>
<input type="submit" name="saveForm" value="Submit" id="submit" class="submit" />
<input type="hidden" id="idstamp" name="idstamp" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" />
</form>
</body>
</html>
Here's the code for my-wrapper.php:
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('XXXXXX', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
UPDATE (Nov 20, 2011):
I am now able to display the error messages with the help of MinisterofPower's code and the Wufoo API wrapper. I have a couple of follow up questions:
I was wondering how I do set up the form below with PHP so that it posts the entries upon pressing the submit button?
Is it possible to do this using AJAX so the page does not refresh?
Here's the code:
<?
// API
require_once('WufooApiExamples.php');
// Wufoo
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
// Post Entries
$postArray = array();
foreach ($this->postValues as $key => $value) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('xxxxxx', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
$fieldError[$value->ID] = $value->ErrorText;
}
}
} catch (Exception $e) {
//Read the error message.
}
// Add Errors
function addErrors($fieldName, $fieldError, $add){
if($fieldError[$fieldName] != ''){
if ($add == 'message') return '<p class="errors">'.$fieldError[$fieldName].'</p>';
else if ($add == 'class') return 'class ="errors"';
}
}
?>
<!--Begin Form-->
<div <? echo addErrors('Field4', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field4', $fieldError, 'message')?>
</div>
<div <? echo addErrors('Field6', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field6', $fieldError, 'message')?>
</div>
<!--End Form-->
The process of retrieving the response is outlined in the API docs. Also, the markup for field errors in found the Dealing With Failure section.
Is is worth nothing that Wufoo offers API Wrappers for PHP and many other languages. I highly suggest using one of those since they make the process so much easier.
Using the Wufoo API, you'd search for a Success value of 0 in the response object and then parse the Field Errors node, as shown here:
$wrapper = new WufooApiWrapper($this->apiKey, $this->subdomain, 'wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost($this->formHash, $postArray);
if (!$result->Success) {
foreach ($result->FieldErros as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
A followup question was posted above, so I'll add my answer here.
You asked how to display an error next to the form in question. You could do this with either javascript or php. I'll show you the PHP way only.
Using PHP, you could redirect back to the form with a value in the GET param of the URL, enumerating the error fields and messages. So, for example, you could do this:
for($result->FieldErrors as $name => $value) {
$str.="$name=$value&";
}
if($str) {
$str = '?errors=true&'.$str;
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/$str");
exit;
}
Then, you'd wrap the above code in this if statement to check for error values on postback, like so:
if($_GET['errors']) {
require_once('my-wrapper.php');
else
//Your HTML HERE
endif
After that, add some PHP conditions which append class names to your fields if they contain errors. For example:
<label id="Field4" class="icons <?php if ($_GET['Field4']) echo 'error'; ?>" for="Field4">Email</label>
Finally, add some CSS to call out the error fields with a color or other indicator.
The other way to do this is with javascript.
Use the same logic as above, but add the following script to your page (grabbed from here and here.)
<script type="text/javascript" charset="utf-8">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return 'error';
}
}
}
function changeClass (elementID, newClass) {
var element = document.getElementById(elementID);
element.setAttribute("class", newClass); //For Most Browsers
element.setAttribute("className", newClass); //For IE; harmless to other browsers.
}
changeClass('Field4', 'error');
</script>
Then use this markup instead:
<label id="Field4" class="icons" for="Field4">Email</label>
Good luck.
PS: This code was written here in SO, so it will probably contain syntax errors. But you can get the point...