I am creating the BindableCollection class which implements IBindableCollection.
What I want to do is CRUD operations above the collection (array of associative arrays). I have all of the CRUD functionallity, but I lack update function which doesn't work.
Code
public function updateFirstWhere($attr, $value, $updateCallback) {
$i = 0;
foreach($this->value as $data) {
if($data[$attr] == $value) {
call_user_func_array($updateCallback, $this->value[$i]);
return;
}
$i++;
}
}
When I pass the $this->value[$i] (which is all of the data inside collection) to the callback function and I do something like that:
public function deleteThePerson($sender) {
$this->collection->updateFirstWhere("id", $sender->data_id, function(&$data) {
$data["name"] = "durisvk";
});
}
I don't see the change in the data.
I want to set the name to durisvk but I can't.
Any Ideas Please?
</head>
<body>
<?php
// UPDATE CRUD element.
$idc = -1;
$naam = "";
$merk = "";
$typ = "";
$kl = "";
$con = new PDO ("mysql:host=localhost;dbname=cars_database", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_GET["action"])) {
if($_GET["action"] == "edit") {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$statement = $con->prepare("UPDATE cars_assigment SET Name=?, Brand=?, Type=?, Color=? WHERE Id = ?");
$statement->bindValue(1, $_POST["Name"]);
$statement->bindValue(2, $_POST["Brand"]);
$statement->bindValue(3, $_POST["Type"]);
$statement->bindValue(4, $_POST["Color"]);
$statement->bindValue(5, $_POST["Id"]);
$statement->execute();
}
$statement = $con->prepare("SELECT * FROM cars_assigment WHERE Id = ?");
$statement->bindValue(1, $_GET["Id"]);
$statement->execute();
$record = $statement->fetchObject();
if($record != false) {
$idc = $record-> Id;
$naam = $record-> Name;
$merk = $record-> Brand;
$typ = $record-> Type;
$kl =$record-> Color;
}
}
}
?>
<h1> Update </h1>
<form method="POST">
ID: <input type="text" name="Id" value="<?php echo $idc ?>">
Naam: <input type="text" name="Name" value="<?php echo $naam ?>">
Brand: <input type="text" name="Brand" value="<?php echo $merk ?>">
Type: <input type="text" name="Type" value="<?php echo $typ ?>">
Color: <input type="text" name="Color" value="<?php echo $kl ?>">
<input name="Id" type="hidden" value="<?php echo $idc; ?>"> </input>
<input type="submit" value="Save"> </input>
</form>
</body>
Related
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);
...
I was trying to retrieve data from PostgreSQL database, In PHP.
Retrieving the data is fine but it does not work when it is linked with HTML.
When I click on find button in HTML interface, it did not really retrieve data from PostgrSQL.
Can anybody help?
PHP
$host = "host=sv4gis";
$dbname = "dbname=survey";
$credentials = "user=sde password=dfd54f";
$objectid = "";
$jobno = "";
$unit = "";
$coordinate = "";
$name = "";
$northing = "";
$easting = "";
$elev = "";
$db = pg_connect( "$host $dbname $credentials" );
if(!$db){
echo "Error : Unable to open database\n";
} else {
echo "Opened database successfully\n";
}
function getPosts() {
$posts = array();
$posts[0] = $_POST['objectid'];
$posts[1] = $_POST['jobno'];
$posts[2] = $_POST['unit'];
$posts[3] = $_POST['coordinate'];
$posts[4] = $_POST['name'];
$posts[5] = $_POST['northing'];
$posts[6] = $_POST['easting'];
$posts[7] = $_POST['elev'];
return $posts;
}
// Selection Operation
if (isset($_POST['search'])) {
$data = getPosts();
$sql = "SELECT * FROM monu_from_Lst WHERE OBJECTID = $data[0]";
$ret = pg_query($db, $sql);
if($ret) {
if(pg_num_rows($ret)) {
while($row = pg_fetch_array($ret)) {
echo $objectid = $row['objectid'];
echo $jobno = $row['jobno'];
echo $unit = $row['unit'];
echo $coordinate = $row['coordinate'];
echo $name = $row['name'];
echo $northing = $row['northing'];
echo $easting = $row['easting'];
echo $elev = $row['elev'];
}
echo "Operation done successfully\n";
// pg_close($db);
}else{
echo 'No Data For This Id';
}
} else {
echo 'Result Error';
}
}
HTML
<form action="php_insert_update_delete_search.php" method="post">
<input type="number" name="objectid" placeholder="OBJECTID" value="<?php echo $objectid;?>">
<input type="text" name="jobno" placeholder="JOB#" value="<?php echo $jobno;?>">
<input type="text" name="unit" placeholder="UNIT" value="<?php echo $unit;?>">
<input type="text" name="coordinate" placeholder="COORDINATE" value="<?php echo $coordinate;?>">
<input type="text" name="name" placeholder="NAME" value="<?php echo $name;?>">
<input type="number" name="northing" placeholder="NORTHING" value="<?php echo $northing;?>">
<input type="number" name="northing" placeholder="NORTHING" value="<?php echo $northing;?>">
<input type="number" name="easting" placeholder="EASTING" value="<?php echo $easting;?>">
<input type="number" name="elev" placeholder="ElEVATION" value="<?php echo $elev;?>">
<div>
<input type="submit" name="search" value="Find">
</div>
</form>
Your code seems to be fine. The problem might be with
<form action="php_insert_update_delete_search.php" method="post">
If you are posting the file to itself try using
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
Make sure your query runs successfully. if your query does not run successfully
try following
$sql = "SELECT * FROM \"monu_from_Lst\" WHERE objectid= $data[0]";
I have working code as following
<?php
$host = "host=localhost"; // use your hostname
$dbname = "dbname=blogsitedb"; // use your dbname
$credentials = "user=postgres password=admin"; // use your credentials
$objectid = "";
$jobno = "";
$unit = "";
$coordinate = "";
$name = "";
$northing = "";
$easting = "";
$elev = "";
$db = pg_connect("$host $dbname $credentials");
if(!$db)
{
echo "Error : Unable to open database\n";
}
else
{
echo "Opened database successfully\n";
}
function getPosts()
{
$posts = array();
$posts[0] = $_POST['objectid'];
$posts[1] = $_POST['jobno'];
$posts[2] = $_POST['unit'];
/*
$posts[3] = $_POST['coordinate'];
$posts[4] = $_POST['name'];
$posts[5] = $_POST['northing'];
$posts[6] = $_POST['easting'];
$posts[7] = $_POST['elev'];
*/
return $posts;
}
// Selection Operation
if(isset($_POST['search']))
{
$data = getPosts();
$sql = "SELECT * FROM \"monu_from_Lst\" WHERE objectid= $data[0]";
$ret = pg_query($db, $sql);
if($ret)
{
if(pg_num_rows($ret))
{
while($row = pg_fetch_array($ret))
{
echo $objectid = $row['objectid'];
echo $jobno = $row['jobno'];
echo $unit = $row['unit'];
/*echo $coordinate = $row['coordinate'];
echo $name = $row['name'];
echo $northing = $row['northing'];
echo $easting = $row['easting'];
echo $elev = $row['elev'];*/
}
echo "Operation done successfully\n";
// pg_close($db);
}
else
{
echo 'No Data For This Id';
}
}
else
{
echo 'Result Error';
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<input type="number" name="objectid" placeholder="OBJECTID" value="<?php echo $objectid;?>"><br><br>
<input type="text" name="jobno" placeholder="JOB#" value="<?php echo $jobno;?>"><br><br>
<input type="text" name="unit" placeholder="UNIT" value="<?php echo $unit;?>"><br><br>
<input type="text" name="coordinate" placeholder="COORDINATE" value="<?php echo $coordinate;?>"><br><br>
<input type="text" name="name" placeholder="NAME" value="<?php echo $name;?>"><br><br>
<input type="number" name="northing" placeholder="NORTHING" value="<?php echo $northing;?>"><br><br>
<input type="number" name="northing" placeholder="NORTHING" value="<?php echo $northing;?>"><br><br>
<input type="number" name="easting" placeholder="EASTING" value="<?php echo $easting;?>"><br><br>
<input type="number" name="elev" placeholder="ElEVATION" value="<?php echo $elev;?>"><br><br>
<div>
<!-- Input For Find Values With The given objectid -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
I have two pages. The first one I am sending data over to the second page. The second page I am using to edit the data sent over and other data within my database. I call for the data I sent over like this:
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
The issue is I have other data on the page that and whenever I edit any of this information, I want to be able to do an UPDATE query to save the new information. However, my query isn't working and I believe it is because my new input field's (data I didn't send over from the first page) data is not being recognized.
Whenever I var_dump the values, I get the data (and in the same format) as how I sent it over to this page.
Here is my code for the second page:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
$newId = filter_var($id, FILTER_SANITIZE_STRING);
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
}catch(PDOException $e) {
echo $e->getMessage();
}
$stmt = $dbc->query("SELECT * FROM users WHERE id='$newId' ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//print_r($stmt);
while($row = $stmt->fetch()) {
$productAmount = $row['amount'];
$productAvailable = $row['available'];
?>
<form name="update" method="POST">
<input type="text" name="id" value="<?php echo $newId; ?>">
<input type="text" name="first" value="<?php echo $first; ?>">
<input type="text" name="last" value="<?php echo $last; ?>">
<input type="text" name="product" value="<?php echo $product; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<button type="submit">Update Product Information</button>
</form>
<?php
}
var_dump($_POST);
if(isset($_POST['update'])) {
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $productAmount);
$stmt->bindParam(5, $productAvailable);
$stmt->bindParam(6, $newId);
$stmt->execute();
}
?>
When I do var_dump($_POST); I get the following values, clearly not including the amount and available data.
array(5) { ["id"]=> string(1) "4" ["first"]=> string(3) "Tom" ["last"]=> string(5) "Brady" ["product"]=> string(3) "Tea" ["edit"]=> string(4) "Edit" }
Why isn't all my data being recognized?
Nowhere in your script do you have:
$productAmount = $_POST['amount'];
$productAvailable = $_POST['available'];
Add those 2 lines just below: $product = $_POST['product'];
UPDATED
Is the form supposed to be populated by the database? Or the form itself? If by the database (initially), then you'll need to change all the $variables in the form to their corresponding field names from the table, ie. $row['id'], $row['first'], etc.
See below for update...
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
$productAmount = $_POST['amount'];
$productAvailable = $_POST['available'];
$newId = filter_var($id, FILTER_SANITIZE_STRING);
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
} catch(PDOException $e) {
echo $e->getMessage();
}
if (isset($_POST['update'])) {
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $_POST['amount']);
$stmt->bindParam(5, $_POST['available']);
$stmt->bindParam(6, $newId);
$stmt->execute();
}
if ( !empty($newId) ) {
$stmt = $dbc->query("SELECT * FROM users WHERE id='$newId' ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while( $row = $stmt->fetch() ) {
?>
<form action="" method="post">
<input type="text" name="id" value="<?php echo $row['id']; ?>">
<input type="text" name="first" value="<?php echo $row['first']; ?>">
<input type="text" name="last" value="<?php echo $row['last']; ?>">
<input type="text" name="product" value="<?php echo $row['product']; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<input type="submit" name="update" value="Update Product Information">
</form>
<?php
}
}
var_dump($_POST);
For the Undefined index just use a ternary in your form like so:
... value="<?php echo !empty($row['amount']) ? $row['amount'] : ''; ?>">
... value="<?php echo !empty($row['amount']) ? $row['available'] : ''; ?>">
Change these lines:
$stmt->bindParam(4, $productAmount);
$stmt->bindParam(5, $productAvailable);
to:
$stmt->bindParam(4, $_POST['amount']);
$stmt->bindParam(5, $_POST['available']);
So the result of cleaning up second part of your code would be this:
No need for a form name.
name="update" goes in the button's markup.
$_POST array now contains the new variables.
We check to make sure update is set before running the query.
<form method="POST">
<input type="text" name="id" value="<?php echo $newId; ?>">
<input type="text" name="first" value="<?php echo $first; ?>">
<input type="text" name="last" value="<?php echo $last; ?>">
<input type="text" name="product" value="<?php echo $product; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<button type="submit" name="update">Update Product Information</button>
</form>
<?php
}
if(isset($_POST['update'])) { // checking the button
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $_POST['amount']); // now it is in the POST array
$stmt->bindParam(5, $_POST['available']); // same here
$stmt->bindParam(6, $newId);
$stmt->execute();
}
I have built a database named "artStore" and a table within that database named "inventory". I've been able to figure out how to create a new entry to the database, but I'm trying to create a page that can edit those entries.
Here is "inventory" the table I created:
$sql = "CREATE TABLE inventory (
id INT(6) AUTO_INCREMENT PRIMARY KEY,
product VARCHAR(30),
category VARCHAR(30),
seller VARCHAR(30)
)";
Here is what I'm currently trying:
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
}
} else {
echo "No Results";
}
?>
<form action="update.php" method="POST">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input id="id" type="text" name="id" value="<?php echo $resultId; ?>" style="display:none;">
<input type="submit" value="Update My Record">
</form>
What I'm trying in update.php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$sql = "INSERT INTO inventory (product, category, seller) VALUES ('$product', '$category', '$seller')";
if ($connection->query($sql) === true) {
echo "Inserted Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
$connection->close();
Try the below code I added hidden field on form and changes on your sql query
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
$resultId = $row["id"];
}
} else {
echo "No Results";
}
?>
<form action="update.php" method="POST">
<input type="text" name="update_id" value="<?php echo $resultId; ?>">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input id="id" type="text" name="id" value="<?php echo $resultId; ?>" style="display:none;">
<input type="submit" value="Update My Record">
</form>
In update.php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$updateId = $_POST['update_id'];
$sql = "UPDATE inventory set product = '$product',category='$category',seller='$seller' WHERE id = '$updateId'";
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
$resultId = "product_id";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
$resultid = $row["id"];
}
} else {
echo "No Results";
}
?>
You were using $resultId in the form but you have not declared and assigned a value to it in the loop.
<form action="update.php" method="POST">
<input id="id" type="hidden" name="id" value="<?php echo $resultId; ?>">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input type="submit" value="Update My Record">
</form>
<!-- Instead of passing the ID in textbox with display: none you can pass it directly in hidden -->
<?php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$product_id = $_POST['id'];
if($product_id!='')//MEANS WE HAVE TO UPDATE THE RECORD
{
// UPDATE QUERY WILL UPDATE THE SAME RECORD ONLY MATCHING THE UNIQUE PRODUCT ID
$sql = "UPDATE inventory SET product = '$product', category = '$category', seller = '$seller' WHERE id = '$product_id' LIMIT 1";
if ($connection->query($sql) === true) {
echo "Updated Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
}
else// If id is blank it means you have a new record
{
$sql = "INSERT INTO inventory (product, category, seller) VALUES ('$product', '$category', '$seller')";
if ($connection->query($sql) === true) {
echo "Inserted Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
}
$connection->close();
?>
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.