Distinct and like in codeigniter - mysql

I am using auto complete, here problem is repeating same tuples.
Have to use Distinct with like in my code.
Here is my Model code:
public function get_products()
{
if(!isset($_REQUEST['term']))
exit;
$data=trim($_REQUEST['term']);
$this->db->like('Name',$data);
$result=$this->db->get('eezy_product');
if($result->num_rows()>0)
{
foreach($result->result_array() as $row)
{
$result_array[] = array(
'label' => $row['Name'],
'value' => $row['Name'],
'keyid' =>$row['ProductID'],
);
}
}
else
{
$result_array=false;
}
return $result_array;
}
Here is my view file :
<link href="<?php echo base_url();?>/css/jquery-ui-1.8.2.custom.css" rel="stylesheet">
<script type="text/javascript" src="<?php echo base_url()?>js/jquery1.7.1.js"></script>
<script type="text/javascript" src="<?php echo base_url()?>js/jquery-ui-1.8.2.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#keyword').autocomplete({
source:'<?php echo base_url()?>index.php/search/get_products', minLength:2,
});
});
</script>
<div class="col-lg-2 search">
<form class="form-vertical" role="form" method="post" action="<?php echo base_url()?>index.php/search/product">
<div class="col-lg-12">
<input type="text" name='keyword' id='keyword' class="form-control" placeholder='Keyword'>
</div><!-- /.col-lg-12 -->
<input type="submit" value="Search">
</form>
</div>
Here in text box am getting repeated values also as auto suggest, but I want to remove duplicates

Try this:
$data=trim($_REQUEST['term']);
$this->db->distinct();
$this->db->like('Name',$data);
$result=$this->db->get('eezy_product');

$data=trim($_REQUEST['term']);
$this->db->select('Name, ProductID');
$this->db->distinct('Name');
$this->db->like('Name',$data);
$result=$this->db->get('eezy_product');

Try to group by name like this
$data=trim($_REQUEST['term']);
$this->db->select("Name, ProductID");
$this->db->like('Name',$data);
$this->db->group_by("Name");
$result=$this->db->get('eezy_product');

Related

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

jQuery toggle on a <div> not working

<script>
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").toggle("slow");
});
});
</script>
I use this code to show and hide an div but I can only click at the first div the second wont work.
This is the div:
<?php
foreach($result as $tile)
{?>
<div id="music">
<?php echo $tile['Onderwerp']?>
</div>
<div id="musicinfo">
<?php echo $tile['Omschrijving']?>
</div>
<?php }?>
I am trying to put information out of an mysql into 2 divs , 1 for the heading and 1 for information which you can see when you click on the heading div.
You are using same id's in loop, that is wrong and all events only apply for first ID, while others are ignored.
foreach ($result as $title) { ?>
<div class='wrapper'>
<div class='music'></div>
<div class='musicInfo'></div>
</div>
<?php } ?>
jQuery function than will looks like this:
$('.music').click(function() {
$(this).parent().find('.musicInfo').toggle();
});

Keeping a checkbox checked after refreshing the page

I have some checkboxes in my php page.when ever i check some of them,some divs get hidden,some get visible.but when i refresh the page,checkboxes get unchecked.and all div s are visible then.
How to keep checkboxes checked even after refreshing the page..?
I tried code as below
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="http://code.jquery.com/qunit/qunit-1.10.0.js"></script>
<script src=".jquery.cookie.js"></script>
<script src="tests.js"></script>
<script type="text/javascript">
$(function(){
var cookieChecked = $.cookie("cookieChecked");
if(cookieChecked){
$(cookieChecked).trigger("click");
}
})
</script>
</head>
<body>
<label for="sitecheck">
<span style="font-weight:bold;">close site temp:</span>
</label>
<input name="" type="checkbox" id="sitecheck" onclick="validateSitec()" /><span style="font-weight:bold;">close site and add message</span><br>
<input type="text" name="closedmsg" id="closedmsg" style="width:440px;height:120px;display:none;" value="<?php echo $data['csitemsg']; ?>" />
<script type="text/javascript">
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
$.cookie("cookieChecked", "#sitecheck");
}else if(document.getElementById('closedmsg').checked){
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
$.cookie("cookieChecked", "#closedmsg");
} else {
$.cookie("cookieChecked","");
}
}
</script>
</body>
</html>
checboxes wont stay ticked on page refresh by default but you can check out the jquery cookie plugin or check out keep checkbox ticked page
Use this Sample code from there
javascript
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
$.cookie("cookieChecked", "#sitecheck");
}else if(document.getElementById('closedmsg').checked){
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
$.cookie("cookieChecked", "#closedmsg");
} else {
$.cookie("cookieChecked","");
}
}
and on page load
$(function(){
var cookieChecked = $.cookie("cookieChecked");
if(cookieChecked){
$(cookieChecked).trigger("click");
}
})
well as you are not showing any of your code we actually shouldn't post any answer cause everything is just a guess.
If you don't want to save it in a cookie you could save it in a session, which is better cause it is server side.
So with this solution you have to check the checkboxes and click on the submit button. If you don't like that you could change that to an ajax call. Also you have to change some stuff if you wan't to have it work if your user is leaving your page and coming back....
So this is just to give you an idea how your PHP could be looking:
-lets say your checkboxes come from an array. in the example the array is called $valuesForInput[]
<?php
session_start();
if(isset($_POST['check'])) {
$_SESSION['check'] = $_POST['check'];
} else {
unset($_SESSION['check']);
session_destroy();
}
$valuesForInput[] = "one";
$valuesForInput[] = "two";
$valuesForInput[] = "three";
$html = '
<form action="test.php" method="post">
<div>';
foreach($valuesForInput as $k => $v) {
if(is_array($_SESSION['check'])) {
$check = in_array($v, $_SESSION['check']) ? ' checked' : '';
}
$html.='
<input type="checkbox" name="check[]" value="'.$v.'"'.$check.'>
<label for="check1">'.$v.'</label>
';
} $html.='
</div>
<input type="submit" value="submit" />
</form>
';
echo $html;
?>
have fun coding
Try this one i think this one will work.we can keep the check box after refreshing the page also
<?php
$val= $_POST['checkbox1'];
?>
<li> <input type="checkbox" name="checkbox1[]" value="sradha" <?php if (strpos($val, "sradha") !== false) { ?> checked="checked" <?php } ?> />
<label>sradha</label></li>
It should work

How do I get codeIgniter 2, Bradley - SignaturePad and DomPDF to work correctly

Hello: I am using signaturePad [http://thomasjbradley.ca/lab/signature-pad/]and have created a short web form in codeIgniter 2, located here: [http://gentest.lfwebz.com/crd/open_form3], that requires the users to actually sign the form.
I have also installed mPDF and domPDF and I have them working, sort of, but not quite the way I want it to.
The functionality I want is this: User opens web form, fills it out, signs it,
using signPad mentioned above. I then want to click a button that runs mPDF/domPDF and
captures the page and of course the embedded signature.
When I run mpdf/domPDF and pass it the view that houses the form, I think I have figured out it is just grabbing a fresh view, one without the signature, but several parts
of the form are missing. So after digging around, I think I have determined that I have to use image conversion of the signaturePad - this is where I am stuck. I have the code in, using the reference here: Signature pad and dompdf, but it does not work.
If you go to my page here: http://gentest.lfwebz.com/crd/open_form3, sign the page, click the "I accept" button
Here is my view
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../assets/jquery.signaturepad.css" media="screen">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="../jquery.signaturepad.min.js"></script>
</head>
<body>
<?php echo base_url(); ?>
<form method="post" action="<?php echo base_url(); ?>pdf.php" class="sigPad">
<label for="name">Print your name</label>
<input type="text" name="name" id="name" class="name">
<p class="typeItDesc">Review your signature</p>
<p class="drawItDesc">Draw your signature</p>
<ul class="sigNav">
<li class="typeIt">Type It</li>
<li class="drawIt">Draw It</li>
<li class="clearButton">Clear</li>
</ul>
<div class="sig sigWrapper">
<div class="typed"></div>
<canvas class="pad" width="198" height="55"></canvas>
<input type="text" name="output" class="output">
<input type="text" name="imgOutput" class="imgOutput">
</div>
<br /><br /><br />
<button type="submit">I accept the terms of this agreement.</button>
</form>
<script>
var sig;
$( document ).ready( function ( ) {
sig = $('.sigPad').signaturePad({defaultAction:'drawIt'});
} );
$( '.sigPad' ).submit( function ( evt ) {
$( '.imgOutput' ).val( sig.getSignatureImage( ) );
} );
</script>
</body>
</html>
here is the controller or the pdf.php mentioned above:
<?php
if(isset($_POST['imgOutput'])){$img_output = $_POST['imgOutput'];}
echo "position 1";
$bse = preg_replace('#^data:image/[^;]+;base64,#', '', $img_output );
echo "position 2";
echo $bse;
if ( base64_encode( base64_decode( $bse) ) === $bse ) {
require_once 'dompdf/dompdf_config.inc.php';
$html = '<!DOCTYPE html><html><head></head><body><p>Your signature:</p><br /><img src="'. $img_output .'"></body></html>';
$dompdf = new DOMPDF;
$dompdf->load_html( $html );
$dompdf->render( );
$dompdf->stream("test.pdf");
}
else{
echo ("ERROR !");
}
?>
What am I missing here? Please could some one point me in the right direction?
Let me know if you need more info.
Thank you in advance.

Displaying unnecessary HTML when showing content from MySQL database

My homepage pulls in content from my MySQL database to create a blog. I've got it so that it only displays an extract from the posts. For some reason it displays HTML tags as well rather than formatting it using the tags (See picture below).
Any help is appreciated.
Homepage:
<html>
<head>
<title>Ultan Casey | Homepage</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<div class="wrapper">
<div id="upperbar">
Home
About Me
Contact Me
Twitter
<form id="search-form" action="/search" method="get">
<input type="text" id="textarea" size="33" name="q" value=""/>
<input type="submit" id="submit" value="Search"/>
</form>
</div>
<div id="banner">
<img src="images/banner.jpg">
</div>
<div class="sidebar"></div>
<div class="posts">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
$sql = "SELECT * FROM php_blog ORDER BY timestamp DESC LIMIT 5";
$result = mysql_query($sql) or print ("Can't select entries from table php_blog.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", $row['timestamp']);
$title = stripslashes($row['title']);
$entry = stripslashes($row['entry']);
$id = $row['id'];
?>
<?php echo "<p id='title'><strong>" . $title . "</strong></p>"; ?><br />
<div class="post-thumb"><img src="thumbs/<?php echo $id ?>.png"></div>
<?php echo htmlspecialchars(substr($entry, 0, 1050)) ?>...
<br>
<hr><br />
Posted on <?php echo $date; ?>
</p>
</div>
</div>
</p
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
Image:
You're passing your post through htmlspecialchars, which encodes < as < and > as >, among other things. This means they display as < and > instead of being parsed as html tags.
The whole point of htmlspecialchars is to produce text that's inert in HTML... to make it display as-is.
A better way to do this is to NOT store <br /> (or any other html) in your post. Instead, use regular line breaks, and echo nl2br(htmlspecialchars($text)) into your page.
If you absolutely need to allow html, you might consider something like HTML Purifier to handle escaping nasty stuff, in which case you'd skip the htmlspecialchars call. Just beware: It's not a good idea to write your own filter to stop malicious code when displaying user-supplied HTML.
echo substr($entry, 0, 1050)