I'm working in a ticket system for my company using PHP and Prepared Statement.
When you add a ticket, you're supposed to fill these fields:
Ticket type
Ticket title
Ticket description
Date requested
Hour requested
Company
Type of visit
Priority
Status
Technician assigned
This works:
1. You can select the type of ticket pulled from the database.
2. You can select the company pulled from the database.
3. You can select the type of visit pulled from the database.
4. You can select the technicians pulled from the database.
The issue is that when you press on add ticket, it won't add anything to the database.
Here's my code:
newticket.php
<?php
$projects = ProjectData::getAll();
$priorities = PriorityData::getAll();
$ticket= TicketData::getAll();
$statuses = StatusData::getAll();
$kinds = KindData::getAll();
$users = UserData::getAll();
?>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header" data-background-color="blue">
<h4 class="title">Nuevo Ticket</h4>
</div>
<div class="card-content table-responsive">
<form class="form-horizontal" role="form" method="post" action="./?action=addticket">
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Tipo</label>
<div class="col-lg-10">
<select name="kind_id" class="form-control" required>
<?php foreach($kinds as $p):?>
<option value="<?php echo $p->id; ?>"><?php echo $p->name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Titulo</label>
<div class="col-lg-10">
<input type="text" name="title" required class="form-control" id="inputEmail1" placeholder="Titulo">
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Descripcion</label>
<div class="col-lg-10">
<textarea class="form-control" name="description" required placeholder="Descripcion"></textarea>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Fecha de la Visita</label>
<div class="col-lg-4">
<input name="date_at" id="date_at" class="form-control" type="date">
</div>
<label for="inputEmail1" class="col-lg-2 control-label">Hora de la Visita</label>
<div class="col-lg-4">
<input name="time_at" id="time_at" class="form-control" type="time" />
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Proyecto</label>
<div class="col-lg-4">
<select name="project_id" class="form-control" required>
<option value="">-- SELECCIONE --</option>
<?php foreach($projects as $p):?>
<option value="<?php echo $p->id; ?>"><?php echo $p->name; ?></option>
<?php endforeach; ?>
</select>
</div>
<label for="inputEmail1" class="col-lg-2 control-label">Categoria</label>
<div class="col-lg-4">
<select name="category_id" class="form-control" required>
<option value="">-- SELECCIONE --</option>
<?php foreach(CategoryData::getAll() as $p):?>
<option value="<?php echo $p->id; ?>"><?php echo $p->name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Prioridad</label>
<div class="col-lg-4">
<select name="priority_id" class="form-control" required>
<option value="">-- SELECCIONE --</option>
<?php foreach($priorities as $p):?>
<option value="<?php echo $p->id; ?>"><?php echo $p->name; ?></option>
<?php endforeach; ?>
</select>
</div>
<label for="inputEmail1" class="col-lg-2 control-label">Estado</label>
<div class="col-lg-4">
<select name="status_id" class="form-control" required>
<?php foreach($statuses as $p):?>
<option value="<?php echo $p->id; ?>"><?php echo $p->name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Asignar a</label>
<div class="col-lg-4">
<select name="tecnico_id" class="form-control" required>
<option value="">-- SELECCIONE --</option>
<?php foreach($users as $p):?>
<option value="<?php echo $p->id; ?>"><?php echo $p->name." ".$p->lastname; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default">Agregar Ticket</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
ticketdata.php
<?php
class TicketData {
public static $tablename = "ticket";
public function TicketData(){
$this->name = "";
$this->lastname = "";
$this->email = "";
$this->password = "";
$this->date_at="";
$this->time_at="";
$this->tecnico_id="";
$this->created_at = "NOW()";
}
public function getTicket(){ return TicketData::getById($this->ticket_id); }
public function getProject(){ return ProjectData::getById($this->project_id); }
public function getPriority(){ return PriorityData::getById($this->priority_id); }
public function getStatus(){ return StatusData::getById($this->status_id); }
public function getKind(){ return KindData::getById($this->kind_id); }
public function getCategory(){ return CategoryData::getById($this->category_id); }
public function add(){
$sql = "insert into ticket (title,description,date_at,time_at,category_id,project_id,priority_id,user_id,status_id,kind_id,created_at,tecnico_id) ";
$sql .= "value (\"$this->title\",\"$this->description\",\"$this->date_at\",\"$this->time_at\",\"$this->category_id\",\"$this->project_id\",$this->priority_id,$this->user_id,$this->status_id,$this->kind_id,$this->created_at,$this->tecnico_id)";
return Executor::doit($sql);
}
public static function delById($id){
$sql = "delete from ".self::$tablename." where id=$id";
Executor::doit($sql);
}
public function del(){
$sql = "delete from ".self::$tablename." where id=$this->id";
Executor::doit($sql);
}
// partiendo de que ya tenemos creado un objecto TicketData previamente utilizamos el contexto
public function update(){
$sql = "update ".self::$tablename." set title=\"$this->title\",category_id=\"$this->category_id\",date_at=\"$this->date_at\",time_at=\"$this->time_at\",tecnico_id=\"$this->tecnico_id\",project_id=\"$this->project_id\",priority_id=\"$this->priority_id\",description=\"$this->description\",status_id=\"$this->status_id\",kind_id=\"$this->kind_id\",updated_at=NOW() where id=$this->id";
Executor::doit($sql);
}
public static function getById($id){
$sql = "select * from ".self::$tablename." where id=$id";
$query = Executor::doit($sql);
return Model::one($query[0],new TicketData());
}
public static function getRepeated($pacient_id,$medic_id,$date_at,$time_at){
$sql = "select * from ".self::$tablename." where pacient_id=$pacient_id and medic_id=$medic_id and date_at=\"$date_at\" and time_at=\"$time_at\"";
$query = Executor::doit($sql);
return Model::one($query[0],new TicketData());
}
public static function getByMail($mail){
$sql = "select * from ".self::$tablename." where mail=\"$mail\"";
$query = Executor::doit($sql);
return Model::one($query[0],new TicketData());
}
public static function getEvery(){
$sql = "select * from ".self::$tablename;
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
public static function getEvents(){
$sql = "select * from ".self::$tablename;
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
public static function getAll(){
$sql = "select * from ".self::$tablename." order by created_at desc";
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
public static function getAllPendings(){
$sql = "select * from ".self::$tablename." where status_id=1";
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
public static function getAllByPacientId($id){
$sql = "select * from ".self::$tablename." where pacient_id=$id order by created_at";
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
public static function getAllByMedicId($id){
$sql = "select * from ".self::$tablename." where medic_id=$id order by created_at";
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
public static function getBySQL($sql){
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
public static function getOld(){
$sql = "select * from ".self::$tablename." where date(date_at)<date(NOW()) order by date_at";
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
public static function getLike($q){
$sql = "select * from ".self::$tablename." where title like '%$q%'";
$query = Executor::doit($sql);
return Model::many($query[0],new TicketData());
}
}
?>
UPDATE
Made slight changes to TicketData.php correcting #smith's and #Nick's observations.
They look like this:
class TicketData {
public static $tablename = "ticket";
public function TicketData(){
$this->name = "";
$this->title = "";
$this->description= "";
$this->lastname = "";
$this->email = "";
$this->password = "";
$this->date_at="";
$this->time_at="";
$this->tecnico_id="";
$this->created_at = "NOW()";
}
public function getProject(){ return ProjectData::getById($this->project_id); }
public function getPriority(){ return PriorityData::getById($this->priority_id); }
public function getStatus(){ return StatusData::getById($this->status_id); }
public function getKind(){ return KindData::getById($this->kind_id); }
public function getCategory(){ return CategoryData::getById($this->category_id); }
public function add(){
$sql = "insert into ticket (title,description,date_at,time_at,category_id,project_id,priority_id,user_id,status_id,kind_id,created_at,tecnico_id) ";
$sql .= "values (\"$this->title\",\"$this->description\",\"$this->date_at\",\"$this->time_at\",\"$this->category_id\",\"$this->project_id\",\"$this->priority_id\",\"$this->user_id\",\"$this->status_id\",\"$this->kind_id\",\"$this->created_at\",\"$this->tecnico_id\")";
return Executor::doit($sql);
}
Now, it will save these fields:
Ticket type (kind_id)
Ticket title (title)
Ticket description (description)
Date requested (date_at)
Hour requested (hour_at)
Company (project_id)
Type of visit (category_id)
Priority (priority_id)
Status (status_id)
It won't save this field:
Technician assigned (tecnico_id)
addticket-action.php
<?php
$r = new TicketData();
$r->title = $_POST["title"];
$r->description = $_POST["description"];
$r->category_id = $_POST["category_id"];
$r->project_id = $_POST["project_id"];
$r->priority_id = $_POST["priority_id"];
$r->user_id = $_SESSION["user_id"];
$r->status_id = $_POST["status_id"];
$r->kind_id = $_POST["kind_id"];
$r->date_at = $_POST["date_at"];
$r->time_at = $_POST["time_at"];
$r->tecnico_id = $_POST["tecnico_id"];
$r->created_at = $_POST["created_at"];
$r->add();
Core::alert("Successfully added!");
Core::redir("./index.php?view=tickets");
?>
I want to make everything work before sanitizing and converting to a proper prepared statement.
What do I need to correct/add to make the script save the (date_at) (hour_at) and (tecnico_id) fields?
Providing some logs or backend error messages could be pretty helpful in troubleshooting this issue.
At first glance though, the major thing that jumps out is that you're not actually using a prepared statement. You're basically concatenating a string together to make a SQL statement, which is very bad for a couple reasons:
You're vulnerable to SQL injection. For example, if you put
","",""); DROP TABLE ticket; -- into your title field, someone could nuke your ticket table because your code doesn't check for this.
You need to sanitize your inputs. If title contains a double quote, it will prematurely end your string input, causing your SQL to fail.
This is a pretty big security hole, so plug that up and save yourself some input sanitization headaches at the same time! If you convert to prepared statement and it works, then it was probably a sanitization issue. If it still doesn't work, get some logging statements in there and let's see what you have.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
Related
SO I inputted values through a datetime jquery plugin and now i am inserting the values in my database through mysqli php extension .
But the problem is it is not inserting.It always goes into the else condition. I have my form in scheduler.php page from there i am sending values to allforms.php from there i am calling add method of class Scheduler which resides in user.php page
allforms.php page
$operation = $_POST['operation'];
if($operation == 'add'){
$request = getSchedule();
$scheduler = new Scheduler($request['title'],$request['urgency'],$request['meeting'],$request['minfo'],$request['snooze'],$request['textbox'],$request['datetime']);
$result = $scheduler->add();
echo $result;
}
function getSchedule(){
$request = [];
$request['title'] = isset($_POST['title']);
$request['urgency'] = isset($_POST['urgency'])?$_POST['urgency']:'';
$request['meeting'] = isset($_POST['meeting'])?$_POST['meeting']:'';
$request['minfo'] = isset($_POST['minfo'])?$_POST['minfo']:'';
$request['snooze'] = isset($_POST['snooze'])?$_POST['snooze']:'';
$request['textbox'] = isset($_POST['textbox'])?$_POST['textbox']:'';
$request['datetime'] = isset($_POST['datetime'])?strtotime($_POST['datetime']):'';
$request['datetime'] = date("Y-m-d",$request['datetime']);
return $request;
}
scheduler.php Page
class Scheduler {
public $title;
public $urgency;
public $meeting;
public $minfo;
public $snooze;
public $textbox;
public $datetime;
public function __construct($title,$urgency,$meeting,$minfo,$snooze,$textbox,$datetime){
$this->title =$title;
$this->urgency = $urgency;
$this->meeting = $meeting;
$this->minfo =$minfo;
$this->snooze = $snooze;
$this->textbox = $textbox;
$this->datetime = $datetime;
$connection = new Connection();
$this->connect = $connection->connect();
}
public function add(){
$sql = "INSERT INTO
Meeting (title, urgency, meeting, minfo, snooze, textbox, datetime)
VALUES ('{$this->title}', '{$this->urgency}', '{$this->meeting}', '{$this->minfo}','{$this->snooze}','{$this->textbox}','{$this->datetime}')";
$result = $this->connect->query($sql);
if($result)
{
return $this->title ." has been registered ";
}else {
return "Some error occured and we couldn't add the event";
}
}
}
scheduler.php Page
<form class="form-group" method="POST" action="allforms.php" >
<div>
<label><b>Title</b></label>
<input type="text" placeholder="Enter your title here" name="title" >
</div>
<div>
<label><b>Urgency Level</b></label>
<select name="urgency" class="textbox" >
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="Critical">Critical</option>
</select>
</div>
<div>
<label><b>Meeting Type</b></label>
<select name="meeting" class="textbox">
<option value="Telephonic">Telephonic</option>
<option value="Offline">Offline</option>
<option value="Online">Online</option>
</select>
</div>
<div>
<label><b>Meeting Info</b></label>
<input type="text" name="minfo" placeholder="Enter location name , number or skype id ,etc.">
</div>
<div>
<label><b>Snooze</b></label>
<input type="number" placeholder="Enter Snooze time in minutes" name="snooze" class="textbox">
</div>
<div>
<label><b>Description</b></label>
<textarea name="textbox" class="textbox"></textarea>
</div>
<div class="form-group">
<label><b>Date/Time of the meeting</b></label>
<input type='text' id="datetimepickr" class="form-control" name="datetime">
</div>
<input type="hidden" name="operation" value="add">
<button type="submit" name="add">Submit</button>
</form>
change your datetime format,
function getSchedule(){
$request = [];
$request['title'] = isset($_POST['title']);
$request['urgency'] = isset($_POST['urgency'])?$_POST['urgency']:'';
$request['meeting'] = isset($_POST['meeting'])?$_POST['meeting']:'';
$request['minfo'] = isset($_POST['minfo'])?$_POST['minfo']:'';
$request['snooze'] = isset($_POST['snooze'])?$_POST['snooze']:'';
$request['textbox'] = isset($_POST['textbox'])?$_POST['textbox']:'';
$request['datetime'] = isset($_POST['datetime'])?strtotime($_POST['datetime']):'';
$request['datetime'] = date("Y-m-d H:i",$request['datetime']);
return $request;
}
I have problem, I am trying to create a form with a few checkboxes, each assigned a different value, i just can update value first and last, between not working, can you help me?
Check.php
<div class="top-on">
<div class="top-on1">
<p class="text-center"> <?php echo $row['username'];?></p>
<br>
<select class="form-control col-sm-12" name="edit_level">
<?php
global $pdo;
$sql = $pdo->query("SELECT * FROM level");
while ( $row_c = $sql->fetch(PDO::FETCH_ASSOC) ) {
?>
<option <?php if($row_c["level"]==$row["level"])
{
echo "selected=\"selected\"";
}?>
value="<?php echo $row_c['level']?>"> <?php echo $row_c['name'];?> </opition>
<?php } ?>
</select>
</div>
<label style="float: right;">
<input type="checkbox" class="checkbox" name="idlevel[]" value="<?php echo $row['id'];?>"> </label>
<div class="clearfix"> </div>
</div>
page Control.php
function edit_level(){
global $pdo;
$sql1="SELECT * From user ";
$stmt1 = $pdo->query($sql1);
if(isset($this->btnlevel))
{
for($i=0;$i<$stmt1->rowCount();$i++){
$elve=$this->idlevel[$i];
$sql ="UPDATE user SET level='$this->editlevel' WHERE id='".$elve."'";
$upt = $pdo->prepare($sql);
$upt->execute();
}
}
}
I want to select an option of product categories from dropdown menu and show products that have that specific category.
Here is the form part from my view:
<?php $attributes = array('method'=>"POST", "class" => "myc", "id" => "myc", "name" => "dropdwn");
echo form_open_multipart('frontend/home/display', $attributes); ?>
<div class="form-group">
<div class="col-sm-9">
<select class="form-control" name="category" onchange="this.form.submit();" />
<option value="" <?php echo set_select('category', 'zero', TRUE); ?>>Categories...</option>
<option value="phone" >Phones</option>
<option value="laptops">Laptops</option>
<option value="accessories" >Accessories</option>
</select>
</div>
</div>
<?php echo form_close(); ?>
As you can see I get the option from dropdown through onchange="this.form.submit();
(if it's not a good idea please suggest other way to do, I just didn't want to use ajax, as I'm not so good at it yet, anyhow suggest what seems better).
Then in my controller I get the option and convert it to array, to use it in my model.
controller part:
public function display($sort_by='product_id', $sort_order='asc', $offset = 0)
{
$this->load->model('model_product');
$selected = implode(" ", $this->input->post());
//var_dump($selected);
$results = $this->model_product->fetch($selected, $limit, $offset, $sort_by, $sort_order);
$data['products'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
//and then goes pagination part, I guess no meaning posting it, as it works fine.
}
My model:
function fetch($selected, $limit, $offset, $sort_by, $sort_order)
{
$sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
$sort_columns = array('product_id', 'name', 'description', 'category', 'country', 'price');
$sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'product_id';
//actual results query
$q = $this->db->select('product_id, name, description, category, country, price, img_name, thumb_name')
->from('products')
->where('category', $selected)
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
$ret['rows'] = $q->get()->result();
var_dump($ret['rows']);
die;
//count query
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('products');
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
Here I get no results, probobly because where clause returns no result.
However if I change the where clause such as ->where('category', 'phones') it shows only phones. So how can I pass selected value to the query correctly?
i wil help you.
View file
<div class="box-header">
<h3 class="box-title">Enter Category Details</h3>
</div>
<?php
echo validation_errors(); $attributes = array('id' => 'formCategory','name'=>'formCategory');
?>
<?php echo form_open_multipart(base_url().'moderator/B2BCategory/addcategory'); ?>
<div class="box-body">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="txtcatname">Title of Category :</label>
<input type="text" name="txtcatname" class="form-control" id="txtcatname" placeholder="Category Name " required="required">
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="categorysection">Section of the Category :</label>
<select class="form-control" name="categorysection" required>
<option value="" >----Select------</option>
<option value="1">Laptop</option>
<option value="2">Phone</option>
<option value="3">Accessories</option>
</select>
<input type="submit" name="selsub" class="btn btn-primary">
</div>
</div>
</div>
Controller
public function addcategory() {
$this->load->helper(array('form', 'url'));
$this->load->view('moderator/templates/header');
$this->load->view('moderator/templates/sidebar');
if ($this->input->post('selsub')) {
$data = array('ctg_name' => $this->input->post('categorysection'));
$this->b2bcategory_model->form_insert($data);
}
In Model
public function form_insert($data){
$this->db->insert('jil_category', $data);
}
To display output from table,just use
public function viewall()
{
$this->db -> select('*');
$this -> db -> from('jil_category');
$query = $this -> db -> get();
return $query->result();
}
From
$selected = implode(" ", $this->input->post());
To
$selected = $this->input->post('category');
By the way, echo & var_dump() would be very useful in debugging your controller and/or model.
OK, so I have looked everywhere for a solution to my problem but found none so far.My code looks like this.I have created a dynamic view page in which edit and add views are loaded dynamically.But the problem arises when i try to retain the value of select dropdown during editing.I would be grateful if someone could help me out.
View
<div class="panel-body">
<div class="row">
<div class="col-lg-6">
<?php if(#$patient_info){
echo '<h1 class="page-header">Edit Patient</h1>';
}else{
echo '<h1 class="page-header">Add Patient</h1>';
}
?>
<?php if($this->session->flashdata('error')){ ?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('error'); ?></div>
<?php } ?>
<?php if($this->session->flashdata('erroredit')){ ?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('erroredit'); ?></div>
<?php } ?>
<?php //echo validation_errors('<div class="alert alert-danger">','</div>'); ?>
<form role="form" method="post" action="<?php echo isset($patient_info) ? site_url('home/patient/edit') .'/' .$patient_info->patientID : site_url('home/patient/new'); ?>">
<div class="form-group">
<?php echo form_error('pname', '<div class="alert alert-danger">', '</div>'); ?>
<label for="pname">Patient Name</label>
<input class="form-control" placeholder="Enter Patient Name" name="pname" value="<?php echo isset($patient_info) ? $patient_info->patientName : ''; ?>">
</div>
<!-- Dropdown menu for selecting clinic -->
<div class="form-group">
<label for="select">Select Clinic Name</label>
<select class="form-control" name="selectClinic">
<option value="none">Select Clinic Below</option>
<?php foreach($allclinic as $key=>$clinic){ ?>
<!--<?php //foreach($clinicByPatient as $clin): ?>-->
<option value="<?php $clinic->clinicID; ?>"
<?php if(isset($patient_info)){
echo 'selected="selected"';
}
?>
>
<?php echo $clinic->clinicName; ?>
</option>
<?php //endforeach; ?>
<?php } ?>
</select>
</div>
<!-- Select Clinic ends-->
<div class="form-group">
<label for="select">Select Dentist</label>
<select class="form-control" name="selectDentist">
<option value="">Select Dentist</option>
<?php foreach($dentistdet as $key=>$dentist){ ?>
<option value="<?php echo $did = $dentist->dentistID;?>"><?php echo $dentist->dentistName; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" name="submit" value="<?php echo isset($patient_info) ? 'Update Patient' : 'Add Patient'; ?>" >
</div>
</form>
<div class="form-group">
<input type="submit" class="btn btn-danger btn-lg btn-block" value="Cancel">
</div>
Edit controller
public function edit(){
$id = $this->uri->segment(4);
$this->load->library('form_validation');
$this->load->model('clinic_model');
$this->load->model('dentist_model');
$data['patient_info'] = $this->patient_model->getPatientById($id);
$data['clinicByPatient'] = $this->patient_model->getPatientByClinic();
$data['allclinic'] = $this->clinic_model->getAllClinics();
// $data['clinicdet'] = $this->patient_model->getPatientByClinic();
if($_POST){
$this->form_validation->set_rules('pname', 'Patient Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('paddress', 'Patient Address', 'trim|required|xss_clean');
$this->form_validation->set_rules('pcontact', 'Patient Contact', 'trim|required|xss_clean');
if($this->form_validation->run()== FALSE){
$data['subview'] = 'patient/patient_new';
$this->load->view('includes/layout', $data);
}else{
$patientname = $this->input->post('pname');
$patientaddress = $this->input->post('paddress');
$patientcontact = $this->input->post('pcontact');
$select = $this->input->post('selectClinic');
$option = $this->input->post('selectDentist');
$edited = $this->patient_model->editpatient($id, $patientname, $patientaddress, $patientcontact, $select, $option);
if($edited){
$this->session->set_flashdata('successedit', 'Successfully updated the record');
redirect('home/patient');
}
}
}else{
$data['subview'] = 'patient/patient_new';
$this->load->view('includes/layout',$data);
}
}
Model looks like this
<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
class Patient_model extends CI_Model{
public function countPatients(){
$countPatient = $this->db->count_all('patient');
return $countPatient;
}
public function getallpatients(){
$query = $this->db->get('patient');
if($query->num_rows()>0){
return $query->result();
}
else{
return FALSE;
}
}//getallpatients function ends
public function getPatientByClinic(){
$this->db->select('*');
$this->db->from('patient');
$this->db->join('clinic', 'patient.clinicID = clinic.clinicID', 'left');
$this->db->join('dentist', 'patient.dentistID = dentist.dentistID', 'left');
$query = $this->db->get();
if($query->num_rows>0){
return $query->result();
}
}
public function addPatientByClinic($patientname, $patientadd, $patientcontact, $select, $option){
$data = array(
'patientName' => $patientname,
'patientAddress' => $patientadd,
'patientContact' => $patientcontact,
'clinicID' => $select,
'dentistID' => $option
);
return $this->db->insert('patient',$data);
}// method ends
public function deletePatient($id){
$verifyID = array('patientID' => $id);
// $affRows = $this->db->affected_rows();
// $obj = new Patient_model;
if($verifyID){
$this->db->where($verifyID);
$this->db->delete('patient');
if($this->db->affected_rows()){
return TRUE;
}
}
}
public function editpatient($id, $patientname, $patientaddress, $patientcontact, $select, $option){
$data = array(
'patientName' => $patientname,
'patientAddress' => $patientaddress,
'patientContact' => $patientcontact,
'clinicID' => $select,
'dentistID' => $option
);
$query = $this->db->where('patientID', $id)
->update('patient', $data);
if($query){
return true;
}
}//method ends
public function getPatientById($id){
$query = $this->db->where('patientID', $id)
->get('patient');
return $query->row();
}
}//class ends
?>
In the code for your select box, you aren't actually echoing $clinic->clinicID. Thus, when the form is submitted, the value will be empty.
You also need to be careful with how you are choosing which select element will be selected by default - you aren't comparing with anything that will change within the loop. Should you be checking against $clinic->clinicID?
I'm building my own book library management system using Codeigniter. I get stuck when I want to buil search engine using filtered keyword. I have four tables (books, publisher, category, format) and I use join to retrieve data. But the results were not what I excepted. Below I show my codes:
// TABLE STRUCTURE
Books |book_id, publisher_id, cat_id, format_id, title, author, ... etc|
Publisher |publisher_id, publisher, address|
Category |cat_id, category, description|
Format |format_id, format|
// MODEL
public function findBooks ( $keyword, $publisher, $category, $format, $offset, $limit )
{
$this->db->select('*');
$this->db->join('publisher as p', 'b.publisher_id=p.publisher_id', 'left');
$this->db->join('category as c', 'b.cat_id=c.cat_id', 'left');
$this->db->join('format as f', 'b.format_id=f.format_id', 'left');
if(!empty($keyword)) {
$this->db->like('b.title', $keyword);
$this->db->like('p.publisher', $publisher);
$this->db->or_like('c.category', $category);
$this->db->or_like('f.format', $format);
}
$this->db->order_by('book_id', 'ASC');
$getData = $this->db->get('books as b', $offset, $limit);
if($getData->num_rows() > 0)
{
return $getData->result();
} else {
return NULL;
}
}
public function getPublishers()
{
$query = $this->db->query("SELECT * FROM publisher ORDER BY publisher_id ASC");
return $query;
}
public function getCategories()
{
$query = $this->db->query("SELECT * FROM category ORDER BY cat_id ASC");
return $query;
}
public function getFormat()
{
$query = $this->db->query("SELECT * FROM format ORDER BY format_id ASC");
return $query;
}
// BOOKS CONTROLLER
public function find($keyword='', $offset = '', $limit = 3;)
{
if($this->uri->segment(3) === FALSE){
$offset = 0;
}else{
$offset = ($this->uri->segment(3)-1) * $limit;
}
$keyword = mysql_real_escape_string($this->input->post('term'));
$publisher = $this->input->post('publisher_id');
$category = $this->input->post('cat_id');
$format = $this->input->post('format_id');
$check = $this->adminModel->findBooks( $keyword, $publisher, $category, $format, $offset, $limit );
if($check)
{
$data['message'] = "";
$data['res'] = $check;
$this->load->view('search_result', $data);
} else {
$data['message'] = "<div class='alert alert-warning'>No result. Please try with another keyword.</div>";
$this->load->view('search_result', $data);
}
}
// FORM VIEW
<div>
<h4>Find Books</h4>
<form action="<?php base_url(); ?>books/find" method="POST" class="form-horizontal" role="form">
<div class="input-group input-group col-md-12">
<label for="term" class="sr-only"></label>
<input type="text" class="form-control" name="term" placeholder="Enter Keyword">
</div>
<div class="input-group col-md-12">
<label for="publisher">By Publisher</label>
<select name="publisher" id="publisher" class="form-control">
<option value="0">All</option>
<?php foreach ($pub->result() as $p) { ?>
<option value="<?php echo $p->publisher_id; ?>"<?php echo set_select('publisher_id', $p->publisher_id, (!empty($data) && $data == $p->publisher_id ? TRUE : FALSE )); ?>><?php echo ucwords($p->publisher); ?></option>
<?php ; } ?>
</select>
</div>
<div class="input-group col-md-12">
<label for="category">By Category</label>
<select name="category" id="category" class="form-control">
<option value="0">All</option>
<?php foreach($cats->result() as $cat){ ?>
<option value="<?php echo $cat->cat_id; ?>"<?php echo set_select('cat_id', $cat->cat_id, (!empty($data) && $data == $cat->cat_id ? TRUE : FALSE )); ?>><?php echo ucwords($cat->category); ?></option>
<?php } ?>
</select>
</div>
<div class="input-group col-md-12">
<label for="format">By Format</label>
<select name="format" id="format" class="form-control">
<option value="0">All</option>
<?php foreach ($format->result() as $frm) { ?>
<option value="<?php echo $frm->format_id; ?>"><?php echo set_select('format', $frm->format_id, (!empty($data) && $data == $frm->format_id ? TRUE : FALSE )); ?><?php echo ucwords($frm->format); ?></option>
<?php ; } ?>
</select>
</div>
<div class="input-group col-md-12">
<button type="submit" class="btn btn-success">FIND</button>
</div>
</form>
</div>
Here what I except is, for instance, I search term "Adam" and it might be a name of person, publisher, or part of title. So, if I search the keyword "Adam" and filtered ONLY by publisher, it will show result such as Adam Publishing rather than "History of Adam and Eve" (as book title).
Another question, am I getting wrong in my code? If so, give me direction what it should be.
Best regards