I have table SubjectTutor who has column id, subject_id, tutor_id, province_id, city_id, school_id, state_private and status. I want to insert data into SubjectTutor table but the error is
province_id, city_id, school_id and state_private will not
saved into table SubjectTutor, but id, subject_id, and tutor_id
will be saved.
this is controller. I also set province_id, city_id, school_id and state_private value.
public function admin_add_pack($standard_id=null)
{
$this->loadModel('Plan');
$this->loadModel('SubjectTutor');
$this->loadModel('Standard');
$this->loadModel('Province');
$this->loadModel('City');
$this->loadModel('School');
$this->loadModel('User');
$standard_data = $this->Standard->find('first',array('conditions'=>array('Standard.id'=>$standard_id)));
$province_id = 32;
$city_id = 44;
$school_id = 1855;
$this->set('title_for_layout','Subject');
if(!empty($this->request->data))
{
if (!isset($this->request->params['_Token']['key']) || ($this->request->params['_Token']['key'] != $this->request->params['_Token']['key']))
{
$blackHoleCallback = $this->Security->blackHoleCallback;
$this->$blackHoleCallback();
}
//validate user data
$this->SubjectTutor->set($this->request->data['SubjectTutor']);
$this->SubjectTutor->setValidation('add');
if ($this->SubjectTutor->validates())
{
// $this->request->data['Subject']['user_id'] = $this->Auth->user('id');
$userdata = $this->request->data['SubjectTutor'];
$this->SubjectTutor->save($userdata,false);
$subject_tutor_id = $this->SubjectTutor->id;
$this->SubjectTutor->school_id = 1855;
$this->SubjectTutor->province_id = 32;
$this->SubjectTutor->city_id = 44;
$this->SubjectTutor->state_private = 1;
$this->Session->setFlash("Record has been added successfully", 'admin_flash_good');
$this->redirect(array('controller'=>'standards', 'action'=>'subject_list',$standard_id));
}
else
{
$this->Session->setFlash("Record has not been created", 'admin_flash_bad');
}
}
$tutors = $this->User->getStandardTutorList($standard_id);
$subjects = $this->Subject->getStandardSubjectList($standard_id);
$standards = $this->Standard->getStandardList();
$provinces = $this->Province->getProvinceList();
$cities = $this->City->getCityList();
$schools = $this->School->getSchoolList();
$this->set(compact('provinces'));
$this->set(compact('standards','standard_id','province_id','city_id','school_id','standard_data','tutors','subjects','provinces','cities','schools','tutor_id'));
}
this is ctp file:
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1"> Select Tutor </label>
<?php echo($this->Form->input('SubjectTutor.tutor_id', array('options'=>$tutors,'div'=>false, 'label'=>false, "class" => "form-control",'empty'=>'Select Tutor')));?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1"> Select Standard </label>
<?php echo ($this->Form->input('Subject.standard_id2', array('options'=>$standards,"div"=>false,"default"=>$standard_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">Select Subject </label>
<?php echo ($this->Form->input("SubjectTutor.subject_id", array('empty'=>'--Select Subject--', 'options'=>$subjects,"div"=>false,"label"=>false,"class"=>"form-control",'disabled'=>false))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">Province </label>
<?php echo ($this->Form->input("SubjectTutor.province_id", array('empty'=>'--Select Province--', 'options'=>$provinces,"div"=>false,"default"=>$province_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">City </label>
<?php echo ($this->Form->input("SubjectTutor.city_id", array('empty'=>'--Select City--', 'options'=>$cities,"div"=>false,"default"=>$city_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">School </label>
<?php echo ($this->Form->input("SubjectTutor.school_id", array('empty'=>'--Select School--', 'options'=>$schools,"div"=>false,"default"=>$school_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
When you use the 'disabled' option for a field in a view, that field doesn't get set when the form data is saved.. Either use 'readonly' option instead, or set those values in the controller before you save (since you don't need user input anyway). Or display the value to the user without pretending they have any input, and use hidden fields to pass the correct data.
Related
I'm so tired of thinking how to solve this case. already search by internet and never solved.
straight to the point
this is my Controller of Product.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\Model_product;
use App\Models\Model_category;
use App\Models\Model_status;
use App\Models\Model_supplier;
class Product extends Controller
{
protected $helpers = [];
public function __construct()
{
helper(['form']);
$this->model_category = new Model_category();
$this->model_product = new Model_product();
$this->model_status = new Model_status();
$this->model_supplier = new Model_supplier();
}
public function index()
{
$data['tbproduct'] = $this->model_product->getProduct();
return view('product/index', $data);
}
public function create()
{
$all = [
'tbproduct' => $this->model_product->getProduct(),
'tbcategory' => $this->model_category->getCategory(),
'tbstatus' => $this->model_status->getStatus(),
'tbsupplier' => $this->model_supplier->getSupplier()
];
return view('product/create', $all);
}
public function store()
{
$validation = \Config\Services::validation();
$data = array(
'prod_name' => $this->request->getPost('prod_name'),
'prodcat_id' => $this->request->getGet('cat_id'),
'prod_serial' => $this->request->getPost('prod_serial'),
'prod_barcode' => $this->request->getPost('prod_barcode'),
'prodstat_id' => $this->request->getPost('stat_id'),
'prodsup_id' => $this->request->getPost('sup_id'),
'prod_image' => $this->request->getPost('prod_image')
);
if ($validation->run($data, 'product') == FALSE) {
session()->setFlashdata('inputs', $this->request->getPost());
session()->setFlashdata('errors', $validation->getErrors());
return redirect()->to(base_url('product/create'));
} else {
$model = new Model_product();
$simpan = $model->insertProduct($data);
if ($simpan) {
session()->setFlashdata('Success', 'Product has been created');
return redirect()->to(base_url('product'));
}
}
}
}
this is my Models Model_product.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class Model_product extends Model
{
protected $table = 'tbproduct';
public function getProduct($id = false)
{
if ($id === false) {
return $this->table('tbproducts')
->join('tbcategory', 'tbproduct.prodcat_id = tbcategory.cat_id', 'left')
->join('tbstatus', 'tbproduct.prodstat_id = tbstatus.stat_id', 'left')
->join('tbsupplier', 'tbproduct.prodsup_id = tbsupplier.sup_id', 'left')
->get()
->getResultArray();
} else {
return $this->table('tbproducts')
->join('tbcategory', 'tbproduct.prodcat_id = tbcategory.cat_id', 'left')
->join('tbstatus', 'tbproduct.prodstat_id = tbstatus.stat_id', 'left')
->join('tbsupplier', 'tbproduct.prodsup_id = tbsupplier.sup_id', 'left')
->where('tbproduct.prod_id', $id)
->get()
->getRowArray();
}
}
public function insertProduct($data)
{
return $this->db->table($this->table)->insert($data);
}
public function updateProduct($data, $id)
{
return $this->db->table($this->table)->update($data, ['prod_id' => $id]);
}
public function deleteProduct($id)
{
return $this->db->table($this->table)->delete(['prod_id' => $id]);
}
}
and this is my Views create.php
<?php echo view('_partials/header'); ?>
<?php echo view('_partials/sidebar'); ?>
<div class="content-wrapper">
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Create New Product</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Create New Product</li>
</ol>
</div>
</div>
</div>
</div>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<form action="<?php echo base_url('product/store'); ?>" method="post">
<div class="card">
<div class="card-body">
<?php
$inputs = session()->getFlashdata('inputs');
//$inputs_cat = isset($inputs['cat_id']) == null ? '' : $inputs['cat_id'];
$errors = session()->getFlashdata('errors');
if (!empty($errors)) { ?>
<div class="alert alert-danger" role="alert">
Whoops! There is something wrong, that is:
<ul>
<?php foreach ($errors as $error) : ?>
<li><?= esc($error) ?></li>
<?php endforeach ?>
</ul>
</div>
<?php } ?>
<div class="form-group">
<label for="">Product Name</label>
<input type="text" class="form-control" name="prod_name" placeholder="Enter product name" value="<?php echo isset($inputs['prod_name']); ?>">
</div>
<div class="form-row">
<div class="col mb-3">
<label for="">Category</label>
<select class="form-control" name="cat_name" id="cat_name">
<?php foreach ($tbcategory as $row) {
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
} ?>
</select>
</div>
<div class="col mb-3">
<label for="">Serial Number</label>
<input type="text" class="form-control" name="prod_serial" placeholder="Enter product serial number" value="<?php echo isset($inputs['prod_serial']); ?>">
</div>
<div class="col mb-3">
<label for="">Barcode</label>
<input type="text" class="form-control" name="prod_barcode" placeholder="Enter product barcode" value="<?php echo isset($inputs['prod_barcode']); ?>">
</div>
</div>
<div class="form-row">
<div class="col mb-3">
<label for="">Status</label>
<select class="form-control" name="stat_name" id="stat_name">
<?php foreach ($tbstatus as $row) {
echo '<option value="' . $row['stat_id'] . '">' . $row['stat_name'] . '</option>';
} ?>
</select>
</div>
<div class="col mb-3">
<label for="">Supplier</label>
<select class="form-control" name="sup_name" id="sup_name">
<?php foreach ($tbsupplier as $row) {
echo '<option value="' . $row['sup_id'] . '">' . $row['sup_name'] . '</option>';
} ?>
</select>
</div>
</div>
</div>
<div class="card-footer">
Back
<button type="submit" class="btn btn-primary float-right">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<?php echo view('_partials/footer'); ?>
i want to insert new data from Controller Product function store.
i've this problem, i cannot change string value into integer value for this
$data = array(
'prod_name' => $this->request->getPost('prod_name'),
'prodcat_id' => $this->request->getGet('cat_id'), ---->>> this is the problem
'prod_serial' => $this->request->getPost('prod_serial'),
'prod_barcode' => $this->request->getPost('prod_barcode'),
'prodstat_id' => $this->request->getPost('stat_id'), ---->>> and this
'prodsup_id' => $this->request->getPost('sup_id'), ---->>> and also this
'prod_image' => $this->request->getPost('prod_image')
);
if you see in the create.php Views, there is $row['***_id'] for all three tables.
and i want to grab that three ids into store.
and this is the Error shown:
mysqli_sql_exception #1048
Column 'prodcat_id' cannot be null
Your problem is that you are sending the cat_name field not the cat_id field from the form. Fix the names of the fields and will works.
The below will works
<?php
$data = array (
'prod_name' => $this->request->getPost('prod_name'),
'prodcat_id' => $this->request->getPost('cat_name'), // ---->>> name fixed **
'prod_serial' => $this->request->getPost('prod_serial'),
'prod_barcode' => $this->request->getPost('prod_barcode'),
'prodstat_id' => $this->request->getPost('stat_name'), // ---->>> and this **
'prodsup_id' => $this->request->getPost('sup_name'), // ---->>> and also this**
'prod_image' => $this->request->getPost('prod_image'),
);
Update:
Since this appears to be simple, but really this could be deceitful, i recommend the next steps to solve it:
Ensures that the form field names match with the named used on the php script
Ensure that you are sending data to the server. You can check the super globals. Something like print_r($_POST) is enough.
Ensure collect the data from the right source: get or post
In this case, the error comes from mysql. To mitigate this you can:
sets default values on columns if required
fill $data array conditionally. If there are no a cat_id, don't put an index 'cat_id' without value (or null)
thank you for helping me before.
i found the answer.
here is the correct code where i can get the cat_id, stat_id and sup_id.
in the View create.php
change this code
<select class="form-control" name="cat_name" id="cat_name">
into this
<select class="form-control" name="cat_id" id="cat_id">
this mean you will get the cat_id value from the database, instead of cat_name.
change the stat_name into stat_id, then sup_name into sup_id.
when all of that changed, you can insert the database with the correct id number when you selected the value from the dropdown box.
this is the answer of my problem, thank you for helping me.
I have a strange issue i have come accross on a few sites i have built, but i am unable to find the problem, it seems so simple, when a user logs in to the site i update the timestamp for the column "member_login" to NOW() which works great, the only issue is, it also updates the "member_joined" column to the exact same time as the "member_login" timestamp but NOWHERE in the code do i tell it to update the "member_joined" column! the entire login script is fairly simple:
login.php
<?php
session_start();
include('includes/db_connection.php');
include('includes/functions.php');
?>
<?php
if (isset($_POST['submitLogin'])) {
$username = trim(strtolower($_POST['username']));
$password = trim(strtolower($_POST['password']));
if (empty($username) || empty($password)) {
include('includes/header.php');
include('includes/navbar.php');
stderr('Please fill in <b>both</b> login fields.');
include('includes/footer.php');
}
$memberInfo = DB::getInstance()->selectOne(
'
SELECT DISTINCT member_username, member_fees_paid, member_fees_paid_on
FROM `membership`
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
if (!count($memberInfo)) {
include('includes/header.php');
include('includes/navbar.php');
stderr('Sorry, username <b>and/or</b> password combination not found.');
include('includes/footer.php');
} else {
$_SESSION['member'] = $username;
if ($memberInfo['member_fees_paid'] === 'N') {
$payedOn = new \DateTime($memberInfo['member_fees_paid_on']);
$payedOn->setTime(0, 0, 0);
$monthAgo = new \DateTime('28 days ago');
$monthAgo->setTime(0, 0, 0);
if ($monthAgo > $payedOn) {
try {
DB::getInstance()->execute(
'
UPDATE `membership`
SET `member_fees_paid`= \'N\'
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
header('Location: my-account.php');
} catch (Exception $e) {
include('includes/header.php');
include('includes/navbar.php');
stderr($e->getMessage());
include('includes/footer.php');
}
}
}
try {
DB::getInstance()->execute(
'
UPDATE `membership`
SET `member_login` = NOW()
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
header('Location: my-account.php');
} catch (Exception $e) {
include('includes/header.php');
include('includes/navbar.php');
stderr($e->getMessage());
include('includes/footer.php');
}
}
}
?>
<?php
include('includes/header.php');
include('includes/navbar.php');
?>
<div class="panel panel-primary">
<div class="panel-heading">Login to your account.</div>
<div class="panel-body">
<form action="login.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Username:</label>
</div>
<div class="col-sm-6">
<input type="text" name="username" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Password:</label>
</div>
<div class="col-sm-6">
<input type="password" name="password" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label" style="display: inline-block;"> </label>
</div>
<div class="col-sm-6 text-right">
<button type="submit" name="submitLogin" class="btn btn-primary">Login</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Forgot <b>your password</b>? recover it here.</div>
</div>
<?php
include('includes/footer.php');
On a successful login we just update the timestamp for the "member_login" and redirect to the "my-account.php" page, which works as it should, but it keeps updating the "member_joined" colums the same as the "member_login" i cannot figure out why it is doing this, any help would be appreciated!
If your column member_joined is type timestamp, you might want to check that on update CURRENT_TIMESTAMP isn't being used - you can check this in a database reader such as phpMyAdmin, SequalPro, Heidi etc.
This will automatically update the datestamp to the current date/time.
Once the user login into site unable to fetch the data from database getting blank page if i write foreach condition here is my code.Fetching username and login verification is workig fine.
Controller:
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
}
else{
$this->load->view('welcome');
}
}
Model:
function getprofiledata($id)
{
$this->db->select('profile_details.*');
$this->db->from('profile_details');
$this->db->where(array('profile_details.profile_id'=>$id));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<?php if(isset($records) && is_array($records) && count($records)>0): ?>
<?php foreach($records as $r):?>
<form action="<?php echo base_url();?>profile/updateprofile" role="form" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<?php
echo form_hidden('profile_id',$r->profile_id);
?>
<div class="form-group">
<label class="control-label col-sm-2 " for="name">Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="name" placeholder="Enter name" value="<?php echo $r->first_name;?>" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="profilename">Profile Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="profile_name" placeholder="Enter Profile name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="designation">Designation:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="designation" placeholder="Enter Designation">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
<?php endforeach;endif;?>
You chose the wrong segment number on line $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));.
Take notice that segment counting starts with zero, so segment no 3 is actually the 4th one in the uri.
If you keep the user id inside your session, you should replace $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3)); with $records = $this->profile_model->getprofiledata($this->session->userdata('profile_id'));. And you're done.
add a new session when you login process like bellow in your login model :
<?php
public function login_user($user_name = '', $password=''){
$userdetails = array(
'email' => $user_name,
'password' => md5($password),
'status'=>1,
);
$this->db->where($userdetails);
$query = $this->db->get('profile_details');
if($query->num_rows()):
$user = $query->result();
$sess_arry = array(
'profile_id' => $user[0]->profile_id, // add new session profile_id
'first_name' => $user[0]->first_name
);
$this->session->set_userdata('admin_logged_in', $sess_arry); //add admin details to session
return true;
else:
return false;
endif;
}
?>
And some change your index method like bellow :
<?php
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['country'] = $this->signup_model->getcountry();
$data['states'] = $this->profile_model->getstates();
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id);
$data['records']= $records;
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
$this->load->view('templates/sidebar',$data);
}
else{
$this->load->view('welcome');
}
}
?>
I have added new 3 line because i thinks you are no getting profile id properly in $this->uri->segment(3)
So,
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id);
$data['records']= $records;
Validate function
function validate(add_app_form){
var valid = true;
var userTxt = document.getElementById("patient_name").value;
var dateTxt = document.getElementById("app_date").value;
var timeTxt = document.getElementById("app_time").value;
var oldName = document.getElementById("select_old").value;
if(userTxt == "" && dateTxt == "" && timeTxt == "" && oldName == "choose")
{
//$("#lblTxt").text("Username and Password are required!");
$('#patient_name').css('border-color', 'red');
$('#app_date').css('border-color', 'red');
$('#app_time').css('border-color', 'red');
$('#select_old').css('border-color', 'red');
$("#add_app_lbl").text("Please Fill all the form");
valid = false;
}
if(userTxt == "" && oldName == "choose")
{
$('#patient_name').css('border-color', 'red');
$("#add_app_lbl").text("Please Add Patient Name Or select an old patient");
valid = false;
}
if(dateTxt == "")
{
$('#app_date').css('border-color', 'red');
$("#add_app_lbl").text("Please Add a Date");
valid = false;
}
return valid;
}
EDITED CODE
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
EDITED CODE 2
<form class="form-horizontal" id="add_app_form" method="post" action="add_appoint.php" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" id="add_app_btn" name="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
I have a php code that take values from a form and add them into MySQL database.
First part of the PHP code, see if the admin choose an already exist patient from drop list, then add a date and time of an appointment with a reason.
Then values are posted into PHP code where we see if we have already an appointment in those date and time. If not ($appExistStmtCount == 0) then go and insert an appointment.
The problem is that nothing added to database and can't see any PHP errors echoed.
Here is the PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
And here the HTML form:
<form class="form-horizontal" id="add_app_form" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submi;" id="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
PS
Values can be seen in the URL but the page just refresh and nothing added
Your form has no method, so it's passing data through get. You need to add method="post" to your form.
Edit. As #u_mulder mentioned, you need to add name attribute to your button for the check in your php if the button is clicked.
I Have a profile page and admin can edit profile users,
all process on one page done,How i can refresh and update value form data after success query update ?
User.class file :
class User {
...
public function updateUser($id, $firstname, $lastname, $phone, $birthday, $managerid)
{
$con = $this->DBconnect();
$id = (int)$id;
$managerid = $this->checkParam($managerid);
$firstname = $firstname;
$lastname = $lastname;;
$mobile = $phone;
$birthday = $this->checkParam($birthday);
$query = "UPDATE `users` SET `manager_id` = :manager_id,`firstname` = :firstname,`lastname` = :lastname,`birthday` = :birthday,`mobile` = :mobile WHERE `id` = :id";
$result = $con->prepare($query);
$result->BindParam(':id', $id, PDO::PARAM_INT);
$result->BindParam(':manager_id', $managerid, PDO::PARAM_INT);
$result->BindParam(':firstname', $firstname);
$result->BindParam(':lastname', $lastname);
$result->BindParam(':birthday', $birthday);
$result->BindParam(':mobile', $mobile);
$check = $result->execute();
return true;
}}
profile.php file :
<?php
if (isset($_GET['id'])) {
$id = (int)$_GET['id'];
}
$user = new User();
$user_info = $user->getuser($id);
while ($info = $user_info->fetch(PDO::FETCH_ASSOC)) {
$firstname = $info['firstname'];
$lastname = $info['lastname'];
$mobile = $info['mobile'];
$birthday = $info['birthday'];
$managerid = $info['manager_id'];
}
$manager_ob = new Manager();
$managers = $manager_ob->getAllManager();
$managers_name = array();
while ($manager = $managers->fetch(PDO::FETCH_ASSOC)) {
$managers_list[] = $manager;
}
if (isset($_POST['edit-profile'])) {
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
}
?>
<form method="post" action="#" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">ID</label>
<div class="col-sm-10"><input type="text" readonly class="form-control" name="user_id" id="user_id" value="<?php echo check_param($id); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_firstname" value="<?php echo check_param($firstname); ?>" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_lastname" value="<?php echo check_param($lastname); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_mobile" value="<?php echo check_param($mobile); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label" for="birthday">Birthday
</label>
<div class="col-sm-10"><input id="birthday" type="text" class="form-control" name="user_birthday"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Manager</label>
<div class="col-sm-10"><select class="form-control m-b" name="manager_id">
<?php foreach ($managers_list as $managers_n) { ?>
<option <?php if ($managers_n['id'] == $managerid) {
echo 'selected';
} ?>
value="<?php echo $managers_n['id']; ?>"> <?php echo $managers_n['name']; ?></option>;
<?php }
?>
</select>
</div>
</div>
<input type="submit" name="edit-profile" class="btn btn-block btn-w-m btn-success"
value="Edit profile">
</form>
i load profile data after submit edit :
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
only display message Profile Edited but must be refresh page for renew data
I must fetch again query for update values? or have better way ?
I suggest you use Ajax for this this is probably the best way to change the data without refreshing. More info about (jQuery) ajax http://api.jquery.com/jquery.ajax/
Your other option is to force a refresh after the submit. You can do this in PHP like so:
Header('Location: '.$_SERVER['PHP_SELF']);
I would suggest choosing ajax to tackle this problem though.
Good luck :)