Codeigniter get value from table row for edit or delete - php

I am retrieving data from MySQL table and displaying in a HTML Table by <?php foreach ?> loop like below.
Now I want to edit/delete the data of a particular row of the above HTML table by pressing the edit or delete button of the table. My MySQL table primary key is branch_code.
I know how to update/delete data in MySQL table in Codeigniter but I do not know how to retrieve the data from the table row. I could not try because I do not know how to start it.
I found similar questions like
Get values from html table using codeigniter
PHP-CodeIgniter: How to get the corresponding html table row values to be deleted by Javascript
In No#1 it was written Collect all this data in an array and "send" it to your PHP via an Ajax POST request. ----- ok great, but how could I do that ?
Can you please help me ?
May be my question is duplicate, but I didn't get any answer from those originals or I would say, I am unable to proceed the process.
Thank you in advance.
Update:
from the No#2 I got the below...
$(document).on('click', '#deleteRow', function() {
var obj = $(this).parent().parent();
var companyId = obj.attr('branch_code');
obj.remove();
});
I understood that I should add unique attribute to <tr>.
Now how can I pass the value in a variable to a model so that I can update my MySQL table ($this->db->where('branch_code', $branch_code);) ?

The way I usually do this is when you make render the html table you would create a unique id for each <tr> , so you'd do something like this:
<?php foreach ( $table->result() as $row): ?>
<tr id="branch_<?= $row->branch_code ?>">
<td>Whatever you want here</td>
<td></td>
</tr>
<?php endforeach; ?>
Then you can do an AJAX call to delete and grab that id with it.
<script>
function deleteBranch(id) {
$.post('controller_url', {"branch_code" : id }, function(data){
//Your controller method would echo a 1 for success
if (data == 1) {
$("#branch_" + id).fadeOut();
//show some kind of message
}
});
}
</script>
So from the controller you could now have a $this->input->post("branch_code") that you could reference to get the branch to delete.

Related

Delete Current Row in Php

How can i delete the current row from Mysql using php ?
I want to search from my Mysql database, every individual row has a Delete button on right side.
When i click on Delete button, that current row should be deleted from database.
I've tried to create a function in php that contains the Query to delete from database. But its not working when i call it in my Search block.
I've created two functions, one in PHP (named as "hello") that contains the Delete Query and one in JavaScript (named as "DeleteRecord") that is calling php function "hello".
Now i called JS function in my Search block.
JS function is working fine, but when JS call a php function, it also works if i just use echo, but within php function if i un comment the Delete Query, it doesn't work !
Anyone to help me out
Thanks !
function viewRecord($Para)
{
echo "<table border=1>
<thead>
<th>Book_Number</th>
<th>Name</th>
<th>Auther</th>
<th>Quantity</th>
<th>Shelf</th>
</thead>";
while($row=mysql_fetch_array($Para))
{
echo "<tr>";
echo "<td>".$row['Book_Number']."</td>";
global $DeleteRecordNumber;
$DeleteRecordNumber = $row['Book_Number'];
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Auther']."</td>";
echo "<td>".$row['Quantity']."</td>";
echo "<td>".$row['Shelf']."</td>";
echo "<td>"."<input type=button value=Delete onclick=DeleteRecord()>"."</td>";
echo "</tr>";
}
echo "</table>";
}
function hello()
{
global $DeleteRecordNumber;
$asd = $DeleteRecordNumber;
echo $asd;
// $Del = "DELETE FROM books WHERE Book_Number='$asd'";
// mysql_query($Del);
}
mysql_close($Connection);
?>
<script type=text/javascript>
function DeleteRecord()
{
document.write (<?php hello(); ?>);
}
</script>
Wait a minute, i think you are mixing apples with oranges! You cannot execute a PHP function on the client side using a button unless you submit the form. The more i look at your post the more errors i Find.
However, assuming you ARE submitting the command (you are not showing what DeleteRecord() does, so i will assume you have a form submision there), You should have a unique field in your table, for example 'id" which would be of type NOT NULL, AUTO_INCREMENT, PRIMARY.
When dislpaying your rows, have each row to hold this unique id. Then when the button is pressed simply do:
$result = MySQL_Query("DELETE QUICK FROM books WHERE id='idtodelete'");
Update the query with your table name and a unique id, That should do it.
converting it to function should go like:
function delete_record($id)
{
return MySQL_Query("DELETE QUICK FROM books WHERE id=$id");
}
If you dont want to use a unique field, use anything that is unique, like an email or something that is not present in another record in the same table, like your field 'Book_Number', but it is more standard the field 'id'.
Column names are case-sensitive, so, if your query is not working as it should, check the character case of everything.
Are you trying to delete a record without refreshing the page?
If so you can remove the element via javascript/jquery and on the delete function you would make an ajax post call to the server with the book id and the operation to perform.
In jQuery it would look like (assuming you put an id in your book_number<td> as book_number):
<script>
var data = {
book_id: $("#book_number"),
operation:"delete"
}
var jqxhr = $.post( "example.php", data, function() {
alert( "Record deleted" );
//delete the row from the table
})
.done(function() {
alert( "Alternative to the above" );
})
.fail(function() {
alert( "error deleting record" );
})
.always(function() {
alert( "Operation completed" );
});
</script>
On the php side, in example.php you would need to adapt your code to include some processing if the $_SERVER['REQUEST_METHOD'] is equal to "POST" and if so, in your query string you would place:
"DELETE FROM books WHERE Book_Number='{$_POST['book_id']}'";
Keep in mind that although this might work, it is not safe from SQL injection, you would need to use some form of escaping to safeguard your queries from SQL Injection.
Another way to do it would be to have the delete button serve as a submit button for a form with the book_number being passed around and do the same above but this time around without the Javascript part. This would force a page reload.

rebinding the select options via jquery

Below is how i made my select option list
<select id="roomtype" name="roomtype" class="form-control select-block">
<?php
// Populate dropdown list of room types
$room = new Rooms;
$room_types = $room->Bind_Room_Types();
foreach ($room_types as $key => $value)
{
echo '<option id="roomtypeoption" value="'.$key.'">'.$value.'</option>';
}
unset($room);
?>
</select>
Now on an update request i made an ajax call which in return gives me a json data like below
[{"id":"1","roomno":"102","floor":"2nd","beds":"2 beds","roomtypeid":"1"}]
After getting the response i populated all the values on my form fields like below
success: function(response) {
// Taking ajax response into javascript objects to fill the form fields
console.log(response);
var object = {};
object = $.parseJSON(response);
$("#roomid").attr('value', object[0].id);
$("#roomnumber").attr('value', object[0].roomno);
$("#roomfloor").attr('value', object[0].floor);
$("#roombeds").attr('value', object[0].beds);
$("#roomtypeoption").remove(); // not working
$("#roomtypeoption").attr('value', object[0].roomtypeid); //not work.
$("#submit").attr('id', 'update').off('click');
}
now in case of text fields its working fine , but when i came to select tag it is not getting updated.
2nd problem is that as you can see in my json i have pasted above. there is 'roomtypeid:1'. This is actually a foreign key. What i want is when my select list get updated on success of ajax then 'roomtypeid' should be placed in How to display the value against foreign key (roomtypeid)
I'm lost in this :(
Please help thanks
I changed my approach. Closing the question.

Update MySQL with jQuery pulldown in foreach loop

I have been having as issue for a while, and can not seem to wrap my head around it. I have a dropdown menu that is pulled from a database for the status of an item.
$myQuery2 = "SELECT InventoryItemStatus.InventoryItemStatusID, InventoryItemStatus.InventoryItemStatusDescription FROM InventoryItemStatus";
$result2 = mysql_query($myQuery2) or die (mysql_error());
if(mysql_num_rows($result2)){
$select2= '<select style="width:90px" name="StatusList">';
while($rs=mysql_fetch_array($result2)){
$select2.='<option value="'.$rs['InventoryItemStatusID'].'">'.$rs['InventoryItemStatusDescription'].'</option>';
}
}
$select2.='</select>';
Easy. Now my goal is to update the database with jQuery/AJAX without reloading the page. I figured out how to do that by using the following code.
$(document).ready(function(){
$('[name="StatusList"]').each(function() {
$(this).change(function() {
var mydata = $('[name="StatusList"]').val();//$(this).val();
var inputdata = $('[name="StarmontInventoryItemID"]').val();
$.ajax({
type: 'POST',
url: 'update_status/update_starmont.php',
data: {StatusList:mydata ,StarmontInventoryItemID:inputdata}
});
});
});
});
No problem. This code listens for a change on the pulldown, when activated calls a script and updates the database accordingly. The issue I am having that is driving me insane is I need this dropdown to appear for every inventory item I have. For example I do a query at the beginning of my code, which pulls 10 inventory items. Then what I do is a foreach in php to allow me to pull each item separately. What I am trying to do is have this dropdown appear for each of those 10 items, and when changed it will update the database for the appropriate inventory item. What is happening right now is that the dropdown that appears at the top of the list works, it will update as I want it too. But for the following 9, it just doesnt work and I can not figure out why.
Here is my foreach loop.
<?php
if (sizeof($rows14) > 0) {
foreach($rows14 as $row14):
$myQuery2 = "SELECT InventoryItemStatus.InventoryItemStatusID, InventoryItemStatus.InventoryItemStatusDescription FROM InventoryItemStatus";
$result2 = mysql_query($myQuery2) or die (mysql_error());
if(mysql_num_rows($result2)){
$select2= '<select style="width:90px" name="StatusList">';
while($rs=mysql_fetch_array($result2)){
$select2.='<option value="'.$rs['InventoryItemStatusID'].'">'.$rs['InventoryItemStatusDescription'].'</option>';
}
}
$select2.='</select>';
echo"
<tr class='tableRowClass2'>
<td height='20'>{$row14['OnHand']}</td>
<td height='20'>{$row14['ItemName']} - {$row17['StarmontSystemID']} - {$row17['StarmontSerial']}</td>
<td height='20'>
<form method='post'>
{$select2}
<input type='hidden' value='{$row14['InventoryItemID']}' name='StarmontInventoryItemID'/>
</form>
</td>
</tr>";
endforeach;
}
?>
As you can see, when the dropdown changes, I want to update the InventoryItemID with the appropriate status. What I dont understand is why the first one works, but the rest following after do not? Could it be something like I have to set a flag?
I have tried multiple different things such as moving the query for the dropdown inside the foreach loop, outside it, a combination but I just cant seem to get it to work! Please any help or advise would be greatly appreciated.
Thanks for you time!
Your problem is that the select elements' name is not unique. As is, jQuery only binds your change event to the first select element. You need to use each()
$('[name="StatusList"]').each(function() {
$(this).change(function() {
//YOUR CODE
});
});
You will have the same problem with StarmontInventoryItemID and will have to use functions like next()/prev()/parent()/child() to get its value.
Furthermore I recommend using Firebug or others in-browser debug tool, it is a big help to debug javascript and especially ajax calls.

How to retrieve data from mysql php and show in table from dropdown

Hey guys i am a newbie to php.What problem i am facing is i have created a dropdown which is populated from the data from database using this code.This is working fine for me and it is populating dropdown too
include('connect.php');
$query="select * from faculty";
$result=mysql_query($query);
while($row = mysql_fetch_assoc($result))
{$dropdown.="\r\n<option value='{$row['Designation']}'>{$row['Designation']} </option>";}
echo "<select>".$dropdown."</select>";
Solution i want is,when a user selects a value from dropdown,result should be retrieved from database and should be displayed in table.Please help me guys
You have to basically :
1) Perform a form sending to some server side script(PHP in your case) when there is a change in the dropdown selection (use onchange event for the dropdown) and fetch the values from the db ,
2) Tell the server side script to spit out an html string which contains the table containing the desired information.3) 3) Output the string on your page.
This will do a page refresh.
If you donot want to have a page refresh, resort to using Ajax.
P.S. I recommend using some framework such as jQuery in case you need to use Ajax
What you have to do is something like this:
In your Html:
<select onchange="fetchContent()">
<option id="1_Designation">abcd</option>
<option id="2_Designation">1234</option>
<option id="3_Designation">lkjh</option>
</select>
In your javascript:
fetchContent()
{
id = $(this).id;
$.ajax({
type: "POST",
url: "/path/content.php?id="+id,
success: function(response) {
$("#tableRow").html(response);
}
});
}
In content.php you will have to get the value of id and then do the necessary data retrieval and then return the data.
$id = $_POST['id'];
//retrieve the data to $data
echo $data;

How to pass php values to javascript then to ajax?

I am echoing data into a table with values from my database. It looks like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point
echo "<tr><td>".$somedata."</td></tr>";
?>
So the value of this table row will be displayed based on how much data is in the database. I want to asynchronously update the page, for example the user wants to delete this from the DB. How can I pass this value to javascript with an onClick function? Or is there another way? If I have a link to delete in the table like:
<td><a onClick="delete(ThisValueOfThisTableRow)">Delete</a></td>
And in javascript or jQuery I want to find this value and set it to a variable, then pass it as:
var some_value = //get this value
.ajax{
url: "somephpfile.php"
data:{some_value:value}
}
I think this would be helpful to anyone if they a responsive member page. Please help out!
maybe something like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array) {
?>
<tr>
<td><?=$somedata;?></td>
<td><a href='#' class='delete-btn' id='row-<?=$someID;?>'>Delete</a></td>
</tr>
<?
}//end while
?>
and then for the js event
$('.delete-btn').click(function() {
var id = $(this).attr("id");
id = id.split("-");
data = { "id" : id[1] }
//your ajax here, pass in your data obj
});
best of luck-
PHP
while ( $row = mysql_fetch_array( $result ) ) {
echo '<tr><td><a onclick="delete_row(' . $row['id'] . ')">delete row</a></td></tr>';
}
Javascript
function delete_row( id ) {
alert( id ); //To show you are getting the id remove this for production
//ajax goes here
}

Categories