OOP PHP taking content from forms created by a loop - php

I'm using OOP PHP right now, and I created a few functions that pass data from a form and insert them into the database. I know all those functions work properly, but the forms in a loop wont seem to be pass.
Here's an example of how it looks:
//Input class://
<?php
class Input{
public static function exists($type='post'){
switch($type){
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_POST)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($item){
if(isset($_POST[$item])){
return $_POST[$item];
}else if(isset($_GET[$item])){
return $_GET[$item];
}
return '';
}
}
?>
//----------------------------------//
<?php $user = new User();
$user_id = $user->data->id; ?>
//some html//
<?php
foreach($products->results() as $row){
$pid = $row->id;
$product = $row->product;
$days = $row->days_default;
$description = $row->description;
$img = $row->img_address;
$category = $row->category;
$x++;
?>
<h4 class="item-title"><?php echo $product . $pid?></h4>
<h5 class="item-subtitle"><?php echo $category ?></h5>
<span class="timing"><?php echo $days . " days" ?></span>
<div class="itme-description"><?php echo $description ?></div>
<div>
<form action="" method="post">
<input type="hidden" name="product_id" id="product_id" value= "<?php $pid ?>">
<input type="hidden" name="days" id="days" value="<?php $days ?>">
<input type="hidden" name="user_id" id="user_id" value="<?php $user_id ?>">
<input type="submit">
</form>
</div>
<?php
if(Input::exists()){
$reminder = new Reminder();
try{
$reminder->create(
array( 'product_id'=>Input::get('product_id'),
'days'=>Input::get('days'),
'user_id'=> Input::get('user_id')));
}catch(exception $e){
die($e->getMessage());}
}
}
?>
I can't figure out how to pass the individuals forms to the server when the user hits submit.

Related

Can´t show message after form submit with header("location:")

I've search the forum for the same situation that I have but still couldn't find the solution. It's probably a piece of cake but I can't figure it out why my $_GET[] doesn't work.
I've created a product page and when I add something to the cart I want to display a message. I've made it work with the url in the form action but then my cart counter in the header stops working properly.
If it's possible I don't want to add any extra in the url like a "?success" because then it just keeps adding ?success to the url if I add more to the cart, that works in action but not with header() ?
Here is my code for the product page:
<?php include_once '../header.php';
$message = "";
$product = New Product;
$cart_data = [];
// if the variables are set - run the following statement
if(isset($_POST["addtocart"])) {
if(isset($_COOKIE["cart"])) {
// Removes backlashes and dont replace previous item, gives every item a new row.
$cookie_data = stripslashes($_COOKIE['cart']);
$cart_data = json_decode($cookie_data, true);
}
// Returns the productid and Size in the array
$item_list = array_column($cart_data, 'ProductsId');
$size_list = array_column($cart_data, 'Size');
// Returns the value if the statement is true
if(in_array($_POST["ProductsId"], $item_list) && in_array($_POST['selectedSize'], $size_list)) {
// A foreachloop that repeats the array value of the selected key variable.
foreach($cart_data as $keys => $values) {
if($cart_data[$keys]["ProductsId"] == $_POST["ProductsId"] && $cart_data[$keys]["Size"] == $_POST["selectedSize"]) {
$cart_data[$keys]["quantity"] = $cart_data[$keys]["quantity"] + $_POST["quantity"];
}
}
}
else {
$item_array = array(
'Img' => $Img = filter_var($_POST["Img"], FILTER_SANITIZE_STRING),
'ProductName' => $ProductName = filter_var($_POST["ProductName"], FILTER_SANITIZE_STRING),
'Size' => $Size = filter_var($_POST['selectedSize'], FILTER_SANITIZE_STRING),
'ProductsId' => $ProductsId = filter_var($_POST["ProductsId"], FILTER_SANITIZE_NUMBER_INT),
'Price' => $Price = filter_var($_POST["Price"], FILTER_SANITIZE_NUMBER_INT),
'quantity' => $quantity = filter_var($_POST["quantity"], FILTER_SANITIZE_NUMBER_INT),
);
$cart_data[] = $item_array;
}
$item_data = json_encode($cart_data);
setcookie('cart', $item_data, time() +(3600),'/');
header("location: product-detail.php?product=".$_GET['product']."?success");
}
if(isset($_GET['success'])) {
$message = "Varan lades till i varukorgen";
};
var_dump($message);
?>
<main id="product-content">
<section>
<form method="post" name="cartCount" action="">
<!-- product-detail.php?product=<?php echo $_GET['product']; ?> -->
<?php if(isset($_GET['product'])) {
$product->ProductsId = $_GET['product'];
$product->ProductId = $_GET['product'];
$product->ProductsId = $_GET['product'];
} else {
$product->ProductsId = $_POST['ProductsId'];
}
$result = $product->get_product();
$test = $product->get_productvariation();
while ($row = $result->fetch()) { ?>
<div class="product-card-detail">
<div class="product-image-wrapper">
<img class="product-image" src="../<?php echo $row['Img'];?>" >
<input type ="hidden" name="Img" value="<?php echo $row['Img'] ?>">
<?php $results = $product->get_images();
$Images = $results->fetch();
if(isset($Images['Image'])) { ?>
<img class="product-image" src="../<?php echo $Images['Image'];?>">
<?php } ?>
</div>
<div class="product-details-text">
<h2 class="title"><?php echo $row['ProductName']; ?></h2>
<input type ="hidden" name="ProductName" value="<?php echo $row['ProductName'] ?>">
<span class="price"><?php echo $row['Price'];?> SEK</span>
<input type ="hidden" name="Price" value="<?php echo $row['Price'] ?>">
<span class="select-title">Storlek</span>
<select class="size" name="selectedSize">
<?php while ($sizeRow = $test->fetch()) { ?>
<option>
<?php echo $sizeRow['Size']; ?>
</option>
<?php } ?>
</select>
<input type="hidden" name="quantity" value="1" />
<input type="submit" class="addtocart-btn" name="addtocart" value="Lägg i varukorgen"/>
<div><?php echo $message ?></div>
<input type ="hidden" name="ProductsId" value="<?php echo $row['ProductsId'] ?>">
<span class="title-description">Beskrivning</span>
<p class="description"><?php echo $row['Description']; ?></p>
</div>
</div>
<?php } ?>
</form>
</section>
</main>
<?php include_once "../footer.php";?>
I've made a test page that works exactly as expected so I can only think that is has to be something about the url?
Test code:
<?php
$message ="";
if(isset($_POST['submit'])) {
header("location: index.php?success");
}
if(isset($_GET['success'])) {
$message = "hello";
}
var_dump($message);
?>
<form method="post" action="">
<input text name="name" value="">
<input type="submit" name="submit" value="submit">
<?php echo $message ?>
</form>
Glad if anyone can see why it doesn't work!
You have made a mistake:
header("location: product-detail.php?product=".$_GET['product']."?success");
See the above line and notice that you are appending param success with ?.
Make it & as:
header("location: product-detail.php?product=".$_GET['product']."&success");

Populating checkboxes from database using PHP - only last option is getting checked

I am trying to populate checkboxes with the data from my mysql database but for some reason only the last checkbox is being checked (for example if automotive, carpentry and hand tools should be checked, only hand tools is being checked) and I can't figure out why. The mysql statement is running correctly and giving me the correct information. Here is the relevant code.
<?php
require_once('../../private/initialize.php');
require_login();
if(!isset($_GET['id'])) {
redirect_to(url_for('/members/show_member_tools.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$tool = [];
$tool['tool_ID'] = $id;
$tool['serial_number'] = $_POST['serial_number'] ?? '';
$tool['tool_name'] = $_POST['tool_name'] ?? '';
$tool['tool_description'] = $_POST['tool_description'] ?? '';
$tool['tool_picture'] = $_POST['tool_picture'] ?? '';
$category =[];
$category = $_POST['category_ID'];
$result = update_tool($tool, $category);
//get info for checkboxes
global $db;
if($result === true) {
$_SESSION['message'] = "The tool has been updated sucessfully";
redirect_to(url_for('/members/show_tool.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$tool = find_tool_by_id($id);
if(isset($_GET['id'])){
$id=$_GET['id'];
$sql = "select category_name from category INNER JOIN tool_category ON category.category_ID = tool_category.category_ID where tool_category.tool_id=$id";
$query = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($query)) {
// $str = "";
$str = $row['category_name'];
echo $str;
if (strpos($str , "automotive")!== false){
$checked1 ="checked";
echo "made it to automotive";
} else {
$checked1 ="";
}
if (strpos($str , "carpentry")!== false){
$checked2 ="checked";
echo "made it to carpentry";
} else {
$checked2 ="";
}
if (strpos($str , "home maintenance")!== false){
$checked3 ="checked";
echo "made it to home maintenance";
} else {
$checked3 ="";
}
if (strpos($str , "plumbing")!== false){
$checked4 ="checked";
} else {
$checked4 ="";
}
if (strpos($str , "yard and garden")!== false){
$checked5 ="checked";
} else {
$checked5 ="";
}
if (strpos($str , "hand tools")!== false){
$checked6 ="checked";
} else {
$checked6 ="";
}
}//end while loop
} //end if
} //end else
$tool_set = find_all_tools();
$tool_count = mysqli_num_rows($tool_set);
mysqli_free_result($tool_set);
?>
<?php $page_title = 'Edit Tool'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<div id="content">
<div class="center">
« Back to My Tools
<h2>Edit Tool</h2>
</div>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/members/edit_tool.php?id=' . h(u($id))); ?>" method="post">
<fieldset class="form">
<img src ="<?php echo h($tool['tool_picture']); ?>" alt="<?php echo h($tool['tool_picture']); ?>"width="150"><br>
<label for="serial_number">Serial Number</label><br>
<input type="text" name="serial_number" value="<?php echo h($tool['serial_number']); ?>" ><br>
<label for="tool_name">Tool Name</label><br>
<input type="text" name="tool_name" value="<?php echo h($tool['tool_name']); ?>" ><br>
<label for="tool_description">Tool Description</label><br>
<input type="text" name="tool_description" value="<?php echo h($tool['tool_description']); ?>" ><br>
<label for="category_ID">Tool Category: </label><br>
<input type="checkbox" name="category_ID[]" value="1" <?php echo $checked1; ?>> <label for="1">Automotive</label> <br>
<input type="checkbox" name="category_ID[]" value="2" <?php echo $checked2; ?>> <label for="2">Carpentry</label> <br>
<input type="checkbox" name="category_ID[]" value="3" <?php echo $checked3; ?>> <label for="3">Home Maintenance</label> <br>
<input type="checkbox" name="category_ID[]" value="4" <?php echo $checked4; ?>> <label for="4">Plumbing </label><br>
<input type="checkbox" name="category_ID[]" value="5" <?php echo $checked5; ?>> <label for="5">Yard and Garden</label> <br>
<input type="checkbox" name="category_ID[]" value="6" <?php echo $checked6; ?>> <label for="6">Hand Tools</label> <br>
<input type="submit" value="Edit Tool" >
<a class="block" href="<?php echo url_for('/members/delete_tool.php?id=' . $id); ?>">Delete Tool</a>
</fieldset>
</form>
<div class="push"></div>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
You're looping over your results. This means with every loop you're setting one variable to "checked" and the rest to an empty string. So only the last one will be checked. The band-aid fix is to set unchecked as the default outside of the loop, and then change to checked only when it's needed.
But the real fix is to be pulling this info from the database and working with it instead of manually mapping database IDs to labels. By moving your condition into the join, you pull all the categories. The rows that have a tool ID are checked, and the others are not. You're also pulling the category names and IDs so you can programmatically build your checkboxes.
See here for DB sample: http://sqlfiddle.com/#!9/20b223/14/0
$tool = find_tool_by_id($id);
$tool["categories"] = [];
$sql = "SELECT c.category_name, c.category_ID, tc.tool_id
FROM category c
LEFT JOIN tool_category tc ON c.category_ID = tc.category_id
AND tc.tool_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_GET["id"]);
$result = $stmt->execute();
while($row = $stmt->fetch_assoc()) {
$id = $row["category_ID"];
$name = $row["category_name"];
$checked = $row["tool_id"] ? "checked" : "";
$tool["categories"][$id] = ["name" => $name, "checked" => $checked];
}
Now later on you can do this to automatically build all your checkbox inputs:
<?php foreach ($tool["categories"] as $id=>$category): ?>
<input type="checkbox" name="category_ID[]" id="category_<?=$id?>" value="<?=$id?>" <?=$category["checked"]?>>
<label for="category_<?=$id?>">
<?=htmlspecialchars($category["name"])?>
</label><br/>
<?php endforeach ?>

Can't insert data to Database with PHP

Can't make basic things. The connection to database is good, cause it shows list, deletes data lines. Also after submiting, it doesn't show any errors, but it doesn't show in database...I am still a beginner in PHP, I searched thoroughly but I can't find out what's wrong in code
This is my model class:
<?php
class abonimentas {
private $abonimentas_lentele = '';
public function __construct() {
$this->abonimentas_lentele = config::DB_PREFIX . 'abonimentas';
}
public function getAbonimentasListCount() {
$query = " SELECT COUNT(`{$this->abonimentas_lentele}`.`id`) as `kiekis`
FROM `{$this->abonimentas_lentele}`";
$data = mysql::select($query);
return $data[0]['kiekis'];
}
public function getAbonimentas($id) {
$query = " SELECT *
FROM `{$this->abonimentas_lentele}`
WHERE `id`='{$id}'";
$data = mysql::select($query);
return $data[0];
}
public function insertAbonimentas($data) {
$query = " INSERT INTO `abonimentas`
(
`pavadinimas`,
`aprasymas`,
`papildomos_salygos`,
`kaina`
)
VALUES
(
'{$data['pavadinimas']}',
'{$data['aprasymas']}',
'{$data['papildomos_salygos']}'
'{$data['kaina']}'
)";
mysql::query($query);
return mysql::getLastInsertedId();
}
public function updateAbonimentas($data) {
$query = " UPDATE `abonimentas`
SET `pavadinimas`='{$data['pavadinimas']}',
`aprasymas`='{$data['aprasymas']}',
`papildomos_salygos`='{$data['papildomos_salygos']}',
`kaina`='{$data['kaina']}'
WHERE `id`='{$data['id']}'";
mysql::query($query);
}
}
This is creation class:
<?php
include 'libraries/abonimentas.class.php';
$abonimentasObj = new abonimentas();
$formErrors = null;
$data = array();
$required = array('pavadinimas', 'aprasymas', 'papildomos_salygos', 'kaina');
$maxLengths = array (
'pavadinimas' => 40,
'aprasymas' => 200,
'papildomos_salygos' => 200
);
if(!empty($_POST['submit'])) {
// nustatome laukų validatorių tipus
$validations = array (
'pavadinimas' => 'anything',
'aprasymas' => 'anything',
'papildomos_salygos' => 'anything',
'kaina' => 'price');
include 'utils/validator.class.php';
$validator = new validator($validations, $required, $maxLengths);
if($validator->validate($_POST)) {
$dataPrepared = $validator->preparePostFieldsForSQL();
$dataPrepared['id'] = $abonimentasObj->insertAbonimentas($dataPrepared);
$abonimentasObj->updateAbonimentas($dataPrepared);
header("Location: index.php?module={$module}&action=list");
die();
} else {
$formErrors = $validator->getErrorHTML();
$data = $_POST;
}
}
include 'templates/abonimentas_form.tpl.php';
?>
This is template for input:
<ul id="pagePath">
<li>Pradžia</li>
<li>Abonimentai</li>
<li><?php if(!empty($id)) echo "Abonimento redagavimas"; else echo "Naujas abonimentas"; ?></li>
</ul>
<div class="float-clear"></div>
<div id="formContainer">
<?php if($formErrors != null) { ?>
<div class="errorBox">
Neįvesti arba neteisingai įvesti šie laukai:
<?php
echo $formErrors;
?>
</div>
<?php } ?>
<form action="" method="post">
<fieldset>
<legend>Abonimento informacija</legend>
<p>
<label class="field" for="pavadinimas">Pavadinimas<?php echo in_array('pavadinimas', $required) ? '<span> *</span>' : ''; ?></label>
<input type="text" id="pavadinimas" name="pavadinimas" class="textbox textbox-200" value="<?php echo isset($data['pavadinimas']) ? $data['pavadinimas'] : ''; ?>">
<?php if(key_exists('pavadinimas', $maxLengths)) echo "<span class='max-len'>(iki {$maxLengths['pavadinimas']} simb.)</span>"; ?>
</p>
<p>
<label class="field" for="aprasymas">Aprašymas<?php echo in_array('aprasymas', $required) ? '<span> *</span>' : ''; ?></label>
<textarea id="aprasymas" name="aprasymas" class=""><?php echo isset($data['aprasymas']) ? $data['aprasymas'] : ''; ?></textarea>
<?php if(key_exists('aprasymas', $maxLengths)) echo "<span class='max-len'>(iki {$maxLengths['aprasymas']} simb.)</span>"; ?>
</p>
<p>
<label class="field" for="papildomos_salygos">Papildomos sąlygos<?php echo in_array('papildomos_salygos', $required) ? '<span> *</span>' : ''; ?></label>
<textarea id="papildomos_salygos" name="papildomos_salygos" class=""><?php echo isset($data['papildomos_salygos']) ? $data['papildomos_salygos'] : ''; ?></textarea>
<?php if(key_exists('papildomos_salygos', $maxLengths)) echo "<span class='max-len'>(iki {$maxLengths['papildomos_salygos']} simb.)</span>"; ?>
</p>
<p>
<label class="field" for="kaina">Kaina<?php echo in_array('kaina', $required) ? '<span> *</span>' : ''; ?></label>
<input type="number" id="kaina" name="kaina" class=""><?php echo isset($data['kaina']) ? $data['kaina'] : ''; ?></input>
<?php if(key_exists('kaina', $maxLengths)) echo "<span class='max-len'>(iki {$maxLengths['kaina']} simb.)</span>"; ?>
</p>
</fieldset>
<p class="required-note">* pažymėtus laukus užpildyti privaloma</p>
<p>
<input type="submit" class="submit button" name="submit" value="Išsaugoti">
</p>
<?php if(isset($data['id'])) { ?>
<input type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
</form>
</div>

Add-to-cart coding is that correct with form?

<?php
session_start();
include("conn.php");
$action = $_POST['action'];
$user = $_SESSION['username'];
if(empty($user)){
echo"<script>alert('Please log in!');window.location='Log In.php';</script>";
exit;
}
if($action == 'add'){
$cart_arr = array(
'foodID'=>$_POST['foodID'],
'order_num'=>$_POST['order_num'],
'food_type'=>$_POST['food_type'],
);
$cart_session = $_SESSION['cart_'.$user];
if(empty($cart_session)){
$cart_session[$cart_arr['foodID']] = $cart_arr;
} else if(!empty($cart_session[$cart_arr['foodID']])){
$cart_session[$cart_arr['foodID']]['order_num']+=$cart_arr['order_num'];
} else {
echo $cart_session[$cart_arr['foodID']] = $cart_arr;
}
$_SESSION['cart_'.$user] = $cart_session;
} else if($action == 'clear'){
$_SESSION['cart_'.$user]=array();
echo"<script>alert('Shopping cart is empty, return home!');window.location='homepage.php';</script>";
exit;
} else if($action == 'change'){
$temp_cart = $_SESSION['cart_'.$user];
foreach($temp_cart as $k=>$v){
if($_POST['goods_'.$k]!= $v['order_num']){
$temp_cart[$k]['order_num'] = $_POST['goods_'.$k];
}
if($_POST['goods_'.$k] == 0){
unset($temp_cart[$k]);
}
}
$_SESSION['cart_'.$user] = $temp_cart;
}
if(empty($_SESSION['cart_'.$user])){
echo"<script>alert('Shopping cart is empty, please add some orders!');window.location = 'homepage.php';</script>";
exit;
}
$goods_id = array();
$cart = $_SESSION['cart_'.$user];
$v['food_type'] = $_POST['food_type'];
foreach($cart as $k=>$v){
$goods_id[$v['foodID']] = $v['foodID'];
}
$goods_id_str = implode(",",$goods_id);
mysql_query("set names utf8");
$sql = "select * from foodmenu where foodID IN (".$goods_id_str.")";
$query = mysql_query($sql);
$cart_goods = array();
while($arr = mysql_fetch_array($query)){
$cart_goods[$arr['foodID']] = $arr;
}
foreach($cart as $k=>$v){
$cart[$k]['food_name'] = $cart_goods[$k]['food_name'];
$cart[$k]['food_img'] = str_replace("../","",$cart_goods[$k]['food_img']);
$cart[$k]['food_price'] = $cart_goods[$k]['food_price'];
$cart[$k]['food_description'] = $_POST['food_description'];
}
?>
May I know is that this coding correct?
Because it shows blank page when it click on the button on previous php for add-to-cart purpose and it just shows normal header at the top.
I will attach form to access this php.
<div class="detailtop">
<?php
$result = mysql_query("SELECT * FROM foodmenu where foodID = '$foodID'");
while($row=mysql_fetch_array($result)){
?>
<dl>
<dt>
<img src="<?php echo $row["food_img"];?>" /> </dt>
<dd>
<form action="order.php" method="get" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<h3><?php echo $row["food_name"];?></h3>
<div class="detailtips">
<?php echo $row["food_description"];?>
</div>
<p><span>Restaurant:</span><strong><?php echo $row["restaurant_name"];?></strong></p>
<p><span>Type :</span><strong><?php echo $row["food_type"];?></strong></p>
<p><span>Price :</span>RM <strong><?php echo $row["food_price"];?><input name="num" type="hidden" class="num" value="<?php echo $row["food_price"];?>" /></strong></p>
<div class="order" style=" padding-top:20px; padding-left:20px;">
<input name="id" type="hidden" value="<?php echo $row["foodID"];?>" />
<input name="" type="submit" value="" class="ordersubmit" style=" margin-left:30px; margin-top:20px;">
</div>
</form>
</dd>
</dl>
<?php }?>
</div>

Can't update data in database with Codeigniter

I can't update data in a record in CodeIgniter . Instead of updating it's adding new record in database table.'hotelres_id' is the primary key of my table.
I have posted the code below:-
Controller code for update:-
function edit($id){
$this->load->model('hotel_reservation','mb');
$data['message'] = '';
$data['object'] = $this->mb->find_by_id($id);
if($data['object']){
$this->form_validation->set_rules('roomno', 'Room Number', 'required|is_unique[hotel_reservation.roomno]');
$this->form_validation->set_rules('checkin', 'Check In', 'required|is_unique[hotel_reservation.checkin]');
$this->form_validation->set_rules('checkout', 'Check Out', 'required|is_unique[hotel_reservation.checkout]');
if ($this->form_validation->run() == TRUE){
$this->mb->eventreg_id = $_POST['hotelres_id'];
$this->mb->eventreg_id = $_POST['eventreg_id'];
$this->mb->eventhotel_id = $_POST['eventhotel_id'];
$this->mb->roomno = $_POST['roomno'];
$this->mb->checkin = $_POST['checkin'];
$this->mb->checkout = $_POST['checkout'];
$this->mb->comment = $_POST['comment'];
$this->mb->update();
$data['message'] = 'Details updated successfully';
$data['object'] = $this->mb;
}
$this->load->view('core/hotel_reservation/edit',$data);
}
else{
$data['message'] = 'No details available!! Fill It!!';
$this->load->view('core/hotel_reservation/save',$data);
}
}
View Code :-
<html>
<head>
<title>Hotel Reservation</title>
</head>
<body>
<h2>Hotel Reservation</h2>
<?php if(isset($message)&&$message!='') echo "<span class=\"message\">{$message}</span>"; ?>
<form action="<?php echo site_url('core/hotel_re/edit/'.#$object->hotelres_id); ?>" method="POST" >
<table class="formtable">
<tr><td>hotelres_id</td><td><input type="text" name="hotelres_id" id="hotelres_id" class="textbox" value="<?php echo #$object->hotelres_id; ?>" readonly></td></tr>
<tr><td>eventreg_id</td><td><input type="text" name="eventreg_id" class="textbox" value="<?php echo #$object->eventreg_id; ?>" readonly></td></tr>
<tr><td>eventhotel_id</td><td><input type="text" name="eventhotel_id" class="textbox" value="<?php echo #$object->eventhotel_id; ?>" readonly></td></tr>
<tr><td>Room Number</td><td><input type="text" name="roomno" value="<?php echo #$object->roomno; ?>" class="textbox" ></td></tr>
<tr><td>Check In</td><td><input type="text" name="checkin" value="<?php echo #$object->checkin; ?>" class="textbox"></td></tr>
<tr><td>Check Out</td><td><input type="text" name="checkout" value="<?php echo #$object->checkout; ?>" class="textbox"></td></tr>
<tr><td>Comment</td><td><textarea type="text" name="comment" value="<?php echo #$object->comment; ?>" class="textarea" ></textarea></td></tr>
<tr><td> </td><td><input type="submit" name="submit" value="Update" class="submitbutton"></td></tr>
</table>
</form>
<span class="validation-errors"><?php echo validation_errors(); ?></span>
</body>
</html>
Model code:-
<?php
class hotel_reservation extends CI_Model{
var $hotelres_id;
var $eventreg_id;
var $eventhotel_id;
var $roomno;
var $checkin;
var $checkout;
var $comment;
static $tablename = 'hotel_reservation';
static $tableid = 'hotelres_id';
function find_by_id($id)
{
$tableid = self::$tableid;
$resultset = $this->db->get_where(self::$tablename,array($tableid=>$id),1);
if($resultset->num_rows()==1)
return array_shift($resultset->result(get_class($this)));
return false;
}
function find_all()
{
$resultset = $this->db->get(self::$tablename);
return $resultset->result(get_class($this));
}
function save()
{
$tableid = self::$tableid;
if(isset($this->$tableid)&&$this->$tableid!=''&&$this->$tableid!=0)
$this->update();
else
$this->insert();
}
private function insert()
{
$this->db->insert(self::$tablename,$this);
}
function update()
{
$tableid = self::$tableid;
$this->db->where($tableid,$this->$tableid);
$this->db->update(self::$tablename,$this);
}
function delete()
{
$tableid = self::$tableid;
$this->db->where($tableid,$this->$tableid);
$this->db->delete(self::$tablename);
}
}
The mistake is here!!
In your controller, you have done this...
$this->mb->eventreg_id = $_POST['hotelres_id'];
$this->mb->eventreg_id = $_POST['eventreg_id'];
This should be this
$this->mb->hotelres_id = $_POST['hotelres_id'];
$this->mb->eventreg_id = $_POST['eventreg_id'];
And like i Said, the update term should be written like this...
$this->db->where($tableid,$this->hotelres_id);
Solved?
From what i can see, i think your issue is with this line:
$this->db->update(self::$tablename,$this);
As you should pass the update function an array with matching keys to your TB columns and values to be updated, with you send the whole object ($this), doesn't also send tableid and tablename?
According to your code ($this->mb->update();), it is calling mb model. But you have provided code for hotel_reservation model. May be some mismatch there.

Categories