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;
}
Related
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
I'm trying to select one contract from the dropdown list, but it looks like the Ajax call is returning information for all contracts instead of just the id being sent. Bare in mind that I'm very new to ZF2.
// view.phtml
<script>
function loadContractId(id)
{
$.getJSON('<?php echo $this->basePath();?>/ajax/getId/'+id+'', function(data) {
$("#ctrid").text(data["arr"][0].ctr_id);
$("#ctrspec").text(data["arr"].ctr_spec);
$("#ctrnutype").text(data["arr"].ctr_nu_type);
$("#ctrlocationcity").text(data["arr"].ctr_location_c);
$("#ctrlocationstate").text(data["arr"].ctr_location_s);
$.each(data["arr"], function (index, item) {
console.log(item);
});
});
$("#contact_holder").css('visibility','visible');
}
</script>
<div id="loc_placement_panel" class="p0pup">
<form name="loc_placement_form" method="post" action="<?php echo $this->basePath(); ?>/booking/view/add">
<input type="hidden" name="ph_id" value="<?php echo $ar["ph_id"]; ?>">
<input type="hidden" name="pres_status" value="2">
<input type="hidden" name="ph_name" value="<?php echo $ar["ctct_name"]; ?>">
<!--<input type="hidden" name="addon" value="see below">-->
<strong>Placements</strong><br/><br/>
<label><strong>Contract:</strong></label>
<select name="contactlist" id="contactlist" onchange="loadContractId($('#contactlist').val())">
<?php
foreach ($ctrLT as $row=>$ar_contracts)
{
echo "<option value='".$ar_contracts['ctr_id']."'>";
echo $ar_contracts['ctr_no'];
echo "</option>";
}
?>
</select>
<div id="contact_holder" style="visibility: hidden">
<strong>Ctr id: </strong><span id="ctrid" ></span><br/>
<strong>Spec: </strong><span id="ctrspec" ></span><br/>
<strong>Nurse Type: </strong><span id="ctrnutype" ></span><br/>
<strong>City: </strong><span id="ctrlocationcity" ></span><br/>
<strong>State: </strong><span id="ctrlocationstate" ></span><br/>
</div>
<label><strong>User Name:</strong></label>
<input type="text" name="loc_location" id="loc_location" value="<?php echo $ar["ctct_name"]; ?>" />
<label><strong>$ltcontracts:</strong></label>
<textarea id="txtArea" rows="10" cols="100" name="loc_location" id="loc_location" value=""><?php '<pre>'; print_r($ltcontracts); '</pre>';?></textarea>
<br/><br/>
<!-- <input type="submit" value="Submit" id="loc_placement_submit_btn" name="loc_placement_submit_btn" /> -->
<input type="button" value="Cancel" id="loc_placement_cancel_btn" />
</form>
</div>
// AjaxController.php
// LT contracts
public function getId($id) {
$id = (int) $id;
return $this->getResortObject('retainedResort',$id);
}
// LT contracts
public function getIdAction() {
$result = new \stdClass();
$arr = $this->getContractsTable()->selectLtContracts($id);
$result->code = Response::STATUS_CODE_200;
$result->arr = $arr;
$json = Json::encode($result);
$response = $this->getResponse(); //new Response();
$response->setStatusCode($result->code);
$response->getHeaders()->addHeaders(array('Content-Type'=>'application/json'));
$response->setContent($json);
return $response;
}
// ContractTable.php
I tried also with selected id, ( $select->where('ctr_id = ?', $id); ) but it didn't work.
public function selectLtContracts($id = 0, array $ar = null) {
$this->table='allcontracts';
$select = new Select($this->table);
$select->where->like('ctr_no', '%LT');
$resultSet = $this->selectWith($select);
$ar = array();
if($resultSet)
{
$i=0;
foreach ($resultSet as $row) {
$ar[$i]['ctr_id']=$row->ctr_id;
$ar[$i]['ctr_no']=$row->ctr_no;
$ar[$i]['ctr_spec']=$row->ctr_spec;
$ar[$i]['ctr_nu_type']=$row->ctr_nu_type;
$ar[$i]['ctr_location_c']=$row->ctr_location_c;
$ar[$i]['ctr_location_s']=$row->ctr_location_s;
$ar[$i]['ctr_nurse']=$row->ctr_nurse;
$ar[$i]['ctr_type']=$row->ctr_type;
$ar[$i]['ctr_marketer']=$row->ctr_marketer;
$ar[$i]['ctr_recruiter']=$row->ctr_recruiter;
$i+=1;
}
}
return $ar;
}
This is what I'm getting from my console when I select a single contract from the dropdown list:
Any idea?
Basically I forgot to include in getIdAction() the single 'id' parameter from route:
$id = (int) $this->params()->fromRoute('id', 0);
and in the ContractsTable.php I needed to add equalTo() predicate:
...
if($id!='' && $id > 0)
$where->equalTo('ctr_id', $id);
$select->where($where);
...
How can I pass a variable from the model to the controller?
Here is my model:
public function edititem($id){
$query = $this->db->query('SELECT * FROM tblitem WHERE item_id = "$id"');
foreach ($query->result() as $row){
$name = $row->item_name;
$description = $row->item_description;
$price = $row->item_price;
}
And here is my controller
public function editItem(){
$this->load->helper('form');
$this->load->model('ItemModel');
$this->ItemModel->edititem($this->input->get('id'));
$name = $this->input->post('name');
$description = $this->input->post('description');
$price = $this->input->post('price');
$data['items'] = $this->ItemModel->itemlist();
$this->load->view('item/item_edit',$data);
}
In which when the user clicks "Edit Item", it will populate the form with the selected row.
<form action="<?php echo base_url().'item/edititem' ?> " method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="name" class="form-control" id="name" name="name" placeholder="Name" value="<?php echo set_value('name'); ?>">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="3" name="description"><?php echo set_value('description'); ?></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="price">Amount (in pesos)</label>
<div class="input-group">
<div class="input-group-addon">Php</div>
<input type="text" class="form-control" name="price" id="price" placeholder="Amount" value="<?php echo set_value('price'); ?>">
<div class="input-group-addon">.00</div>
</div>
</div>
<button type="submit" class="btn btn-primary">EDIT ITEM</button>
</form>
If it is from model to controller, You can make an array and store that 3 fields. (I assume there is only single row returned by your query since you are using id as where).
$result = array();
foreach ($query->result() as $row)
{
$result['name'] = $row->item_name;
$result['description'] = $row->item_description;
$result['price'] = $row->item_price;
}
return $result;
You can access it in the controller using:
$data['items']['name'];
$data['items']['description']
$data['items']['price']
Or in your view as
$items['name'];
$items['description'];
$items['price'];
Here your model looks like this
public function edititem($id){
$query = $this->db->query('SELECT * FROM tblitem WHERE item_id = "$id"');
if ($query->num_rows() > 0) {
$row = $query->row_array(); // row_array return single row and result_array return multiple row
return $row['dt'];
And your controller looks like this
public function editItem(){
$this->load->helper('form');
$this->load->model('ItemModel');
$item_details=$this->ItemModel->edititem($this->input->get('id'));
here you use foreach loop
foreach ($item_details as $key=>$value){
//do this in $data array
} //now you can use the specific data to your view.
$this->load->view('item/item_edit',$data);
}
Your Model:
This may useful if your want to return a specific 1 row without using result()
public function edititem($id){
$this->db->select('*');
$this->db->from('tblitem ');
$this->db->where('item_id ',$id);
return $query = $this->db->get()->custom_row_object(0, 'ItemModel');
}
Your Controller: Call the edititem($id) from ItemModel (your model)
public function editItem(){
$item_id=$this->uri->segment(3); //added this
$this->load->helper('form');
$this->load->model('ItemModel');
$item_details=$this->ItemModel->edititem($item_id); //added this
$data['item_name'] = $item_details->name;
$data['item_desc'] = $item_details->description;
$data['item_price'] = $item_details->price;
//now you can use the specific data to your view.
$this->load->view('item/item_edit',$data);
}
In your view, you can use the variable like:
$item_name;
$item_desc;
$item_price;
eg:
<input type="text" name="item_name" value="<?php echo $item_name;?>" />
I am doing some practicing with OOP in PHP, and am having issues with submitting form data involving subclasses.
What I am trying to do: submit form data based on the type of product it is (generic, tool, or electronic). My concern comes from not being able to submit a form that can differentiate between the different product types.
Here's the Product Class (the base class):
<?php
require_once('connectvars.php');
// Base class!!
class Product {
// Inheritable properties
protected $title;
protected $description;
protected $price;
// Getters
public function getTitle() {
return $this->title;
}
public function getDescription() {
return $this->description;
}
public function getPrice() {
return $this->price;
}
// Setters
public function setTitle($title) {
$this->title = $title;
}
public function setDescription($description) {
$this->description = $description;
}
public function setPrice($price) {
$this->price = $price;
}
public function insertProduct() {
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);
$query = "INSERT INTO addedProducts VALUES (0,'$this->title', '$this->description', '$this->price', '', '', '')";
mysqli_query($dbc, $query)
or die("Error adding to database");
mysqli_close($dbc);
}
}
?>
Here's a subclass I made called Tools:
<?php
require_once('connectvars.php');
require_once('Product.php');
class Tools extends Product {
// Defined properties specific to Tools class
private $shipper;
private $weight;
// Getters
public function getShipper() {
return $this->shipper;
}
public function getWeight() {
return $this->weight;
}
// Setters
public function setShipper($shipper) {
$this->shipper = $shipper;
}
public function setWeight($weight) {
$this->weight = $weight;
}
public function insertTool() {
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);
$query = "INSERT INTO addedProducts VALUES (0,'$this->title', '$this->description', '$this->price', '$this->shipper', '$this->weight', '')";
mysqli_query($dbc, $query)
or die("Error adding to database");
mysqli_close($dbc);
}
}
?>
This is where I am running into problems:
<!DOCTYPE html>
<html>
<head>
<title>Product Entry</title>
</head>
<body>
<select name="prodType" id="prodType">
<option value="" selected="selected">Select...</option>
<option value="general">General</option>
<option value="tools">Tools</option>
<option value="electronics">Electronics</option>
</select>
<br/><br/>
<?php
//require_once('connectvars.php');
require_once('Product.php');
require_once('Electronics.php');
require_once('Tools.php');
$product = new Product();
$tool = new Tools();
$electronic = new Electronics();
if (isset($_POST['submit']) && (isset($_POST['prodType']) == 'general')) {
$product_form = false;
$product->setTitle($_POST['title']);
$product->setDescription($_POST['description']);
$product->setPrice($_POST['price']);
$product->insertProduct();
/*$tool->setTitle($_POST['title']);
$tool->setDescription($_POST['description']);
$tool->setPrice($_POST['price']);
$tool->setShipper($_POST['shipper']);
$tool->setWeight($_POST['weight']);
if (!empty($tool->getTitle()) && !empty($tool->getDescription()) && is_numeric($tool->getPrice()) && !empty($tool->getShipper()) && !empty($tool- >getWeight())) {
echo 'Tool submitted <br/>';
//echo 'Go Back';
$tool->insertTool();
}
} else {
$product_form = true;
}
if ($product_form) {
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="title"><strong>Product Title</strong></label>
<br/>
<input type="text" id="title" name="title" value="<?php echo $product->getTitle();?>"/>
<br/><br/>
<label for="description"><strong>Description</strong></label>
<br/>
<input type="text" id="description" name="description" value="<?php echo $product->getDescription();?>"/>
<br/><br/>
<label for="price"><strong>Price</strong></label>
<br/>
<input type="text" id="price" name="price" value="<?php echo $product->getPrice();?>"/>
<br/><br/>
<!--For Tools -->
<label for="shipper"><strong>Shipper Info</strong></label>
<br/>
<select name="shipper" id="shipper">
<option value="none" selected="selected">--</option>
<option value="usps">USPS</option>
<option value="fedex">FedEx</option>
<option value="ups">UPS</option>
</select>
<br/><br/>
<label for="weight"><strong>Weight</strong></label>
<br/>
<input type="text" id="weight" name="weight" value="<?php echo $tool->getWeight();?>"/>
<br/><br/>
<!--For Electronics -->
<label for="recyclable"><strong>Recyclable?</strong></label>
<br/>
<select name="recyclable" id="recyclable">
<option value="none" selected="selected">--</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<br/><br/>
<input type="submit" id="submit" name="submit" value="Submit Product"/>
</form>
<?php
}
?>
</body>
</html>
I'm sure there's a fairly straightforward solution, but I'm no longer thinking about this correctly anymore -_-. Any suggestions?
I would do the following:
Move all of your calculations to the top of the file.
Move your prodType into the form.
I am displaying the form always. In 1 instance it is to edit, in another it is to create. But you will want to add a hidden input for the "product_id"
Like this:
<?php
require_once('Product.php');
require_once('Electronics.php');
require_once('Tools.php');
$product = new Product();
$tool = new Tools();
$electronic = new Electronics();
if (isset($_POST['submit'])){
$prodType = $_POST['prodType'];
if($prodType == 'general') {
$product_form = false;
$product->setTitle($_POST['title']);
$product->setDescription($_POST['description']);
$product->setPrice($_POST['price']);
$product->insertProduct();
} else if($prodType == 'tools') {
} else if ($prodType == 'elecronics') {
} else {
// echo this message in the form.
$msg = 'Invalid product type';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product Entry</title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="prodType" id="prodType">
<option value="" selected="selected">Select...</option>
<option value="general">General</option>
<option value="tools">Tools</option>
<option value="electronics">Electronics</option>
</select>
<br/><br/>
<label for="title"><strong>Product Title</strong></label>
<br/>
<input type="text" id="title" name="title" value="<?php echo $product->getTitle();?>"/>
<br/><br/>
<label for="description"><strong>Description</strong></label>
<br/>
<input type="text" id="description" name="description" value="<?php echo $product->getDescription();?>"/>
<br/><br/>
<label for="price"><strong>Price</strong></label>
<br/>
<input type="text" id="price" name="price" value="<?php echo $product->getPrice();?>"/>
<br/><br/>
<!--For Tools -->
<label for="shipper"><strong>Shipper Info</strong></label>
<br/>
<select name="shipper" id="shipper">
<option value="none" selected="selected">--</option>
<option value="usps">USPS</option>
<option value="fedex">FedEx</option>
<option value="ups">UPS</option>
</select>
<br/><br/>
<label for="weight"><strong>Weight</strong></label>
<br/>
<input type="text" id="weight" name="weight" value="<?php echo $tool->getWeight();?>"/>
<br/><br/>
<!--For Electronics -->
<label for="recyclable"><strong>Recyclable?</strong></label>
<br/>
<select name="recyclable" id="recyclable">
<option value="none" selected="selected">--</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<br/><br/>
<input type="submit" id="submit" name="submit" value="Submit Product"/>
</form>
</body>
</html>
Note: You should use and learn composer. It is a must have tool to autoload your class files.
So this has been bugging me for sometime, I want to pass a calculation which I have stored in a function onto another page, I can pass field entries no problem (sorry im newish at PHP) but how do i pass my calculation from:
// calculation section (calculator.php) - this is a include on every page
The calculation is made by a users entries which is in a include on every page
// The thank-you.php page outputs a thank you comment and sends the email
I receive all the other info fine but the function won't come through in my email.
The output from the calculation is also stored in calculator.php which is the include but it outputs to the screen fine just not to my email :(.
Am I missing something?
Sorry (edit) here is my code:
<?php
error_reporting(E_ALL);
if(isset($_POST['name']) && isset($_POST['to'])){
ini_set('date.timezone', 'Europe/Madrid');
$now = date("H:i");
$cutoff = "06:00";
$higherthan = "22:00";
$name = $_REQUEST['name'];
$telephone = $_REQUEST['telephone'];
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$date = $_REQUEST['date'];
$returndate = $_REQUEST['returndate'];
$people = $_REQUEST['people'];
$return = $_REQUEST['return'];
$myemail = $_REQUEST['myemail'];
include_once('includes/config.php');
$settingsSql = mysql_query("SELECT * FROM transfers_in WHERE location='$to' AND no_passengers='$people'");
$settings = mysql_fetch_assoc($settingsSql);
echo "From: ".$from." To: ".$settings['location']."<br />";
echo "Number of passengers: ".$settings['no_passengers']."<br />";
ini_set('date.timezone', 'Europe/Madrid');
$now = date("H:i");
$cutoff = "06:00";
$higherthan = "22:00";
echo "Time cost: ".$settings['price']." euros<br /><hr />Total: ";
function timeCost() {
$to = $_REQUEST['to'];
$people = $_REQUEST['people'];
$return = $_REQUEST['return'];
include_once('includes/config.php');
$settingsSql = mysql_query("SELECT * FROM transfers_in WHERE location='$to' AND no_passengers='$people'");
$settings = mysql_fetch_assoc($settingsSql);
//echo $return;
if ($return == "No"){
if ((strtotime($now) < strtotime($cutoff)) || (strtotime($now) > strtotime($higherthan))){
echo number_format($settings['price']) + 1.40;
} else {
echo number_format($settings['price']) + 0.00;
}
} elseif ($return == "Yes") {
if ((strtotime($now) < strtotime($cutoff)) || (strtotime($now) > strtotime($higherthan))){
echo number_format($settings['price']) * 2 + 1.40;
} else {
echo number_format($settings['price']) * 2 + 0.00;
}
}
echo " in euros<br /><br />";
}
echo timeCost();
} else { ?>
<form method="POST" action="thank-you.php" name="chooseDateForm" id="chooseDateForm">
<label>Name:</label>
<input type="text" value="" name="name" />
<label>Telephone:</label>
<input type="text" value="" name="telephone" />
<label>Email:</label>
<input type="text" value="" name="myemail" />
<label>From:</label>
<select name="from">
<option selected="selected">Malaga</option>
</select>
<div class="clr"></div>
<label>To:</label>
<select name="to">
<?php foreach ($data as $place => $price){
echo "<option>{$place}</option>\n";
}
echo '</select>
<div class="clr"></div>
<label>Date:</label>
<input type="text" value="dd/mm/yyyy" id="date" name="date" class="date-pick" />
<span id="calendar"></span>
<div id="return-journey">
<label>Return Date:</label>
<input type="text" value="dd/mm/yyyy" id="returndate" name="returndate" class="date-pick" />
<span id="calendar"></span>
</div>
<label>Number of people:</label>
<select id="people" name="people">
<option value="4">4</option>
<option value="6">6</option>
<option value="8">8</option>
</select>
<div class="clr"></div>
<div id="return">
<label>Is this a return<br />journey?</label>
<div class="clr"></div>
<div id="radio-buttons">
<input type="radio" name="return" value="Yes" class="radio returning" />Yes<br />
<input type="radio" name="return" value="No" class="radio" checked />No
</div>
</div>
<div class="clr"></div>
<input type="submit" name="submit" class="fauxButton" />
</form>';
}
?>
If you are using sessions, you can store the variable, results, array -- whatever into a session variable and then retrieve it on a new page.
session_start();
$_SESSION['test_var'] = 'Jake';
Then when I navigate to a new page and retrieve the var:
session_start();
echo $_SESSION['test_var']
// outputs 'Jake'