"Issue with updating a record using a button” - php

When I click on the update button, the SQL query updates the last record not the wanted one
when displaying several courses, I would like to give the user the right to confirm one of the courses, when I click on the update button, it updates the last record
<?php
$cc = mysqli_query($mysqli, "SELECT * from course WHERE c_email ='$emailu' AND course_situation='pending'");
while($ccc = mysqli_fetch_array($cc)) {
$idcourse = $ccc['idcourse'];
$city = $ccc['idville'];
$pickup = $ccc['course_depart'];
?>
<tr>
<td><?= $idcourse ?></td>
<td><?= $pickup ?></td>
<td><?php echo $ccc['course_date'] ?>, <?php echo
$ccc['course_heure'] ?></td>
<td>
<?php
if($ccc['course_situation'] == "pending") { ?>
<span class="badge badge-danger">Pending</span>
<?php } else { ?>
<span class="badge badge-success">Confirmed</span>
<?php } ?>
</td>
<td><?php echo $ccc['c_phone'] ?></td>
<td><?php echo $ccc['c_phone'] ?></td>
<td><?php echo $ccc['idclient'] ?></td>
<td>
<button type="submit" name="cancelcourse" class="btn btn-danger btn-xs"><i class="icon md-check" aria-hidden="true"></i> Update</button>
</tr>
<?php }
if(isset($_POST["cancelcourse"])) {
$query = "UPDATE course SET id='$idu' AND course_situation='confirmed' WHERE idcourse='$idcourse' ";
if(mysqli_query($mysqli, $query)) {
echo "<div class=' alert alert-success' style='padding-left:150px'>
<strong>Success!</strong> Event page updated.</a>.
</div>";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
} else {
echo "<div class='alert alert-danger'>
<strong>ERROR!</strong> We invite you to try Again Later.
</div> " . mysqli_error($mysqli);
}
}

You generate button for each course, but all your buttons are equal, they don't contains any information about which course you want to update. You use variable $idcourse, but it is assigned inside while-loop that generates table - for each row that is shown this variable is changed, so after showing whole table it will contains id for last row.
Please remember, that each time your page is reloaded (like after clicking button) whole script is executed from beginning and no variables are stored, unless you pass it yourself.
Simplest solution:
1.Add id to button
<button type="submit" name="cancelcourse" class="btn btn-danger btn-xs" value="<?=htmlspecialchars($idcourse)?>">
2.Change query
$idcourseToRemove = mysqli_real_escape_string($mysqli, $_POST["cancelcourse"]);
$query = "UPDATE course SET id='$idu' AND course_situation='confirmed' WHERE idcourse='$idcourseToRemove' ";
And last advice: learn about SQL Injection and how to avoid it (like for example by mysqli_real_escape_string function)

UPDATE course SET id='$idu',course_situation='confirmed' WHERE
idcourse='$idcourse'

Related

update table row and save in database in php codeigniter

I am making a table from a database and want to add an Edit/delete button to each row update or delete a specific row from the database. I have successfully added working "delete" button but I have no idea how could I update data in table <td> in view and send it to controller.
Here is my code:
view file
<table class="table table-striped">
<tr>
<td>name</td>
<td>age</td>
<td>gender</td>
<td>class</td>
<td>roll no.</td>
</tr>
<?php foreach($record as $r): ?>
<tr>
<td><?php echo $r->name; ?></td>
<td><?php echo $r->age; ?></td>
<td><?php echo $r->gender; ?></td>
<td><?php echo $r->class; ?></td>
<td><?php echo $r->roll no; ?></td>
<td><a href="" >Edit</a>
<a href="<?php echo base_url()."student/deleteRow" ?id="$r->name">"
onclick="return confirm
('Are you sure to Delete?')"><i class="icon-trash"></a></td>
</tr>
<?php endforeach; ?>
</table>
Controller Function
public function deleteRow(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$this->student_model->rowDelete($id);
redirect($_SERVER['HTTP_REFERER']);
}
}
I don't know how can I now insert an input field to update table row without effecting previous view. Any suggestion would be helpful.
To Edit the Studen data you need to pass an id or uniue column name to the data base to get that student data.
First Set the student id in <a href=""> tag.
<td><a href="<?= base_url('student/edit_student') ?>/$r->id" >Edit</a>
Then When you click on the edit it will take you to the controller. You can get the third url parameter direct in as show in the controler code:
You can also use get as shon
Your Controller should be:
public function edit_student($id){
$student_data = $this->student_model->get_student_data($id);
$this->load->view('your_view',['student_data'=>$student_data)]);
}
Here is you model which get the id form controllr and find the student data and passit to back to the controller:
Your Model should be:
public function get_student_data($id){
$this->db->select('*');
$this->db->from('your_table_name');
$this->db->where('id',$id);
$query = $this->db->get();
$student_data = $query->$row_array();
if(isset($student_data) && !empty($student_data)){
return student_data;
} else {
return FALSE;
}
}
Form controller you pass the data to the view.
On View Side:
<?php
// Just to ensure the data. Comment it after testing
echo "<pre>";
print_r($student_data);
echo "</pre>";
?>
<form action="<?= base_url('student/update_student') ?>/<?= $student_data['id'] ?>">
<input name="your_column_name" value="<?= $student_data['your_column_name'] ?>">
// Try to do the same for all you column.
<input type="submit" value="updata">
</form>
Here is the controller for update the data
public function update_student($id){
$student_data = $this->input->post();
$status = $this->student_model->update_student($id,$student_data);
if($status == TRUE){
$this->load->view('your_view');
// Your Success view
} else {
// Your view if fail to update
$this->load->view('your_view');
}
}
Here is the model for update the data
public function get_student_data($id,$student_data){
$this->db->where('id',$id);
$this->db->update('your_table_name',$student_data);
if($this->db->affected_rows() == 1){
return TRUE;
} else {
return FALSE;
}
}
Very similar to what you have done for delete. Something like this:
<td>
<a href="" >Edit/Delete</a>
<!-- This should be another method in Student controller -->
<i class="icon-trash"><!-- I changed order of edit and delete -->
</td>
I need to warn you for CSRF. If you don't implement better security here, anyone pointing to that link would be able to edit or delete data.
Check Security class in documentation and how to set hidden value so that way you would ensure that only one who has already requested that page was able to edit/delete rows.
<td><a href="<?php echo base_url();?>controller_name/function_name/<?php echo $edit_id;?>" >Edit</a></td>
another way
<td><a href="<?php echo base_url();?>controller_name/function_name?id=<?php echo $edit_id;?>" >Edit</a></td>
You can use any one according to your requirement.

how to delete a row in database using codeigniter

hye, i'm trying to do 'delete function' for my modul. i've tried so many different ways for this. but it come out no result, some come with error.
this is my controller (named expert.php) :
public function remove() {
$siri = $this->uri->segment(3);
$this->Kepakaran_m->delete($siri);
$this->view();
}
siri is the a field name (column name) in my table. it it primary key.
this is my model (named Kepakaran_m.php):
function delete($siri) {
$this->dbsmk->where('siri', $siri);
$this->dbsmk->delete('kexpt003pakar');
if ($this->dbsmk->affected_rows() == 1) {
return TRUE;
}
return FALSE;
}
kexpt003pakar is the table name.
so my view is this (named kepakaran.php):
<tbody>
<?php if(empty($kepakaran)) { ?>
<tr>
<td colspan="8">Pengguna tidak mempunyai rekod kepakaran!</td>
</tr>
<?php } else {
$num = 0;
foreach ($kepakaran as $list_kepakaran) {
$num++;
?>
<tr>
<td><?php echo $num; ?></td>
<td><?php echo $list_kepakaran->kategori; ?></td>
<td><?php echo $list_kepakaran->bidang; ?></td>
<td><?php echo $list_kepakaran->spesifik; ?></td>
<!-- untuk keluarkan tahap -->
<td><?php
if($list_kepakaran->tahap=='1'){
echo "Sederhana";
}elseif ($list_kepakaran->tahap=='2') {
echo "Tinggi";
}elseif ($list_kepakaran->tahap=='3') {
echo "Sangat Tinggi";
}
?>
</td>
<!-- done untuk keluarkan tahap -->
<td><?php echo $list_kepakaran->biltahun; ?></td>
<td>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#tambahkepakaran"><i class="glyphicon glyphicon-pencil"></i></button>
<i class="glyphicon glyphicon-trash"></i>
</td>
</tr>
<?php }} ?>
</tbody>
so the delete button is in this area >>siri; ?>" type="button".....
i hope your answer will help me to discover this up. thank you :)
What's the error? I think you just need to modify your codes becomes:
<i class="glyphicon glyphicon-trash"></i>
Then it should be ok.
In order to use uri segment..do not forget to call url helper in autoload.php
english is not my native language.
For solve your problem, you can check a lot of things.
Did you forget to load model in your controller ?
Try to dump value of $siri in your remove function and show response on your network tab in chrome devTools for example.
If you don't call your controller, look at side of your href or open Application/config/routes.php for use routing and add this $route['expert/remove/(:num)']['GET'] = "expert/remove/$1";
If $siri is empty look at the side of $this->uri->segment(3);
Verify if you load correctly the helper.
For that, go to Application/config/autoload.php and see if url is in helper $autoload['helper'] = array('url','security','language', 'form', 'text');

Change Enum With OOP PHP

I'm new to learning web development with PHP and I have a problem I'm trying to solve. I have an ENUM type in my database which is of 2 values: "Y" or "N". It is called userStatus inside my user table (tbl_users). I'm trying to use PHP to change that ENUM value for that particular user when a button is clicked. However when I click the button nothing happens and I'm unsure if its the button or my PHP or a combination of both being wrong which is causing this not to work?
PHP to change ENUM:
if(isset($_POST['btn-activate'])){
if(isset($_GET['id']))
{
$id = $_GET['id'];
extract($user_home->getID($userId));
$statusY = "Y";
$statusN = "N";
$stmt = $user->runQuery("SELECT userID,userStatus FROM tbl_users WHERE userID=:uID");
$stmt->execute(array(":userID"=>$userId));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if($row['userStatus']==$statusN)
{
$stmt = $user->runQuery("UPDATE tbl_users SET userStatus=:status WHERE userId=:userID");
$stmt->bindparam(":status",$statusY);
$stmt->bindparam(":userID",$userId);
$stmt->execute();
$msg = "
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>WoW !</strong> Your Account is Now Activated : <a href='manage_users.php'></a>
</div>
";
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> Your Account is allready Activated : <a href='manage_users.php'></a>
</div>
";
}
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> No Account Found : <a href='manage_users.php'></a>
</div>
";
}
}
}
Get user id function:
public function getID($userId)
{
$stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE userId=:id");
$stmt->execute(array(":id"=>$userId));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
Table Which displays users:
$database = new Database();
$db = $database->dbConnection();
$conn = $db;
$query = "SELECT * FROM tbl_users";
$stmt = $conn->prepare($query);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $row['userID']?></td>
<td><?php echo $row['userName']?></td>
<td><?php echo $row['userFirstName']." ".$row['userSurname']; ?></td>
<td><?php echo $row['userEmail']?></td>
<td><?php echo $row['userRole']?></td>
<td><?php echo $row['userStatus']?></td>
<td>
And My button at the end of the table which should, when clicked, run the PHP at the to:
<?php if($row['userStatus'] == ('N')){
echo ' <button type="submit" class="btn btn-info"><i class="glyphicon glyphicon-ok" name="btn-activate" ></i> Activate</button>';
}else{
echo ' <button class="btn btn-default"><i class="glyphicon glyphicon-eye-close"></i> Archive</button>';
} ?>
<button data-toggle="modal" data-target="#view-modal" data-id="<?php echo $row['userID']; ?>" id="getUser" class="btn btn-warning"><i class="glyphicon glyphicon-pencil"></i> Edit</button>
</td>
</tr>
Thanks in advance.
There is no code (nothing happens) if either of the first two if conditions don't evaluate to TRUE.
Consider adding some debugging output. At least add an else for each of those ifs and echo some debug output.
Very strange that the code is checking both $_POST and $_GET. I suspect that id is being passed in on the form submit, just like btn-activate, and not as a parameter in the uri. (i.e. Did you mean $_POST['id'] ? Just guessing here.
We see a reference to $userid in this line:
extract($user_home->getID($userId));
But we don't see what value is assigned to $userId. The preceding line attempts to set a variable named $id. But we don't see $id being used anywhere else.
Personally, I'd avoid using the extract function where it isn't specifically needed. (I don't want my code susceptible to malfunctioning, in this example, when someone adds a column to tbl_users.)
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
Put the name attribute to your button, not in the <i> element.
<?php
if($row['userStatus'] == ('N')){
echo ' <button type="submit" class="btn btn-info" name="btn-activate"><i class="glyphicon glyphicon-ok"></i> Activate</button>';
} else {
echo ' <button class="btn btn-default"><i class="glyphicon glyphicon-eye-close"></i> Archive</button>';
}
?>

Sort array with two infos | PHP

I made code which loads online players from game server(through MySQL table). Now, I'm newbie in PHP and I don't Know how to sort them(users) in table by ID. I googled and I found answer which will sort arrays by value(1, 2, 3, 4 etc..). Only problem is because users, with ID, have a name. How to connect user's name with ID, so they stay together after sort?
Here's a code
while($_hsync_podatci = $_hsync_rezultat->fetch_assoc())
{
?>
<tr class="_hsync_online_stil_<?php echo $_hsync_dio; ?>" id="_hsync_na_mrezi_<?php echo $_hsync_podatci['ServerID']; ?>">
<td><?php echo $_hsync_podatci['ServerID']; ?></td>
<td><?php echo $_hsync_podatci['Ime']; ?></td>
<td>
<button type="button" id="_hsync_izbaci_<?php echo $_hsync_podatci['ServerID']; ?>" class="btn btn-danger" onclick="_hsync_izbaci(<?php echo $_hsync_podatci['ServerID']; ?>)" style="float: right;">
<span class="glyphicon glyphicon-log-out"></span>Izbaci
</button>
</td>
</tr>
<?php
$_hsync_dio = !$_hsync_dio;
}
Above while is table's header. Var $_hsync_dio is for background color. One row is white, second is grey, and so on.
When doing a MySQL query you can sort the array automatically when fetching the data for example:
$players = mysqli_query($conn, "SELECT * FROM playerTable ORDER BY id ASC");
while($row = mysqli_fetch_assoc($message_sender_info)){
$message[] = $row;
}
Use DESC instead of ASC for e reverse sorting.

PHP foreach loop outside loop

I'm trying to wrap my head around PHP and variable scope. Take a look at the following:
<?php foreach ($data as $tip) { ?>
<tr>
<td><?php echo $tip['id']; ?></td>
<td><?php echo $tip['title']; ?></td>
<td class="delete"><i class="icon-cross"></i></td>
</tr>
<?php } ?>
This just runs a foreach loop that pulls some information out of the database and displays it in a table. The last table cell has an icon in it for deleting that article. What I'm trying to do is have a modal popup that asks for conformation to delete that specific article but I cannot tie the tip id with the delete button because the modal window sits outside the loop. How can I go about accessing the individual id?
Do this :
<?php foreach ($data as $tip) { ?>
<tr>
<td><?php echo $tip['id']; ?></td>
<td><?php echo $tip['title']; ?></td>
<td class="delete" onclick="deleteArticle(<?php echo $tip['id'] ?>)">
<a href="#deleteModal" class="modal">
<i class="icon-cross"></i>
</a>
</td>
</tr>
<?php } ?>
<script>
function deleteArticle(id){
// now you can do what ever you want to do with this id
}
</script>
There is a built it javascript function called "confirm".
If you're using JQuery (And I assume you are) try this:
$('.delete').click(function(){
var check = confirm("Are you sure you want to delete this article?");
if(check)
{
// you code here
}
else return false;
});

Categories