Deleting a database record using $_POST with Codeigniter - php

I've been doing it all wrong, I used to take the value from the URI segment and didn't realize it wasn't the ideal way. So I changed my approach and now have everything via a $_POST. I'm not sure if I'm doing this correctly, could someone shed some light? My view contains tabular data listing items pulled from the DB. Each item has two links, "View" and "Delete." The code seems to work but was wondering if it could be coded better. I forgot that the form name wasn't unique, so when I went to go delete a record, it would always delete the newest record (the last hidden field was set).
myview.php (snippet)
<?php foreach($records as $record): ?>
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
View Delete
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
</form>
<?php endforeach ?>

Viewing/Deleting via uri id is perfectly fine, I wouldn't venture to say that using $_POST is wrong, but creating a new unique form for every delete element is terribly messy, and weighed against what you are gaining (no exposed id i guess?), I believe it is more 'correct' to use the uri for delete functions.
If you only want certain people to be able to delete certain records, handle that programmatically in the delete function itself, don't depend on the fact that the request is only sent via $_POST. This is not dependable, anyone can generate a post request.

For anyone who comes across this later, here's how I solved my issue.
In my controller I have a method called delete that checks to see if the form field was submitted via a $_POST. If there's no variable, redirect them somewhere with an error message. If the field was passed, then go through the normal checks to make sure the record can be deleted.
if(!isset($_POST['item_id']))
{
$this->session->set_flashdata('message', 'item cannot be removed!');
redirect("/item");
}
if($this->input->post('item_id')) {
... code ....
... code ....
}

Your syntax error is with this line:
<?php foreach($records as $record): ?>
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
View <a href="#" onclick="document.myform<?php echo
$location->id;?>.submit();">Delete</a>
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
</form>
<?php endforeach ?>
You can not do looping for a form. Instead, use the following code:
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
<?php foreach($records as $record): ?>
a href="/location/view/<?php echo $location->id;?>">View</a> Delete
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
<?php endforeach ?>
</form>

Related

Send form data to the same page not functionning

I'm a newbie in PHP, and I would like to send datas from a form and display it into the same page, here is my code for better understanding:
<form method="post" action="same_page.php">
<input type="text" name="owner" />
<input type="submit" value="Validate" />
</form>
<?php
if(isset($_GET['owner']))
{
echo "data sent !";
}
?>
So normally, after having entered some random text in the form and click "validate", the message "data sent!" Should be displayed on the page. I guess I missed something, but I can't figure out what.
You forgot to add submit name in your form.You are using POST as method so code should be
<form method="post" action="">
<input type="text" name="owner" />
<input type="submit" name="submit_value" value="Validate" />
</form>
<?php
if(isset($_POST['submit_value']))
{
echo '<pre>';
print_r($_POST);
}
?>
Will display your post values
You are using a POST method in your form.
<form method="post" action="same_page.php">
So, change your code to:
if (count($_POST) && isset($_POST['owner']))
Technically, the above code does the following:
First checks if there are content in POST.
Then, it checks if the owner is set.
If both the conditions are satisfied, it displays the message.
You can actually get rid of action="same_page.php" as if you omit it, you will post to the same page.
Note: This is a worst method of programming, which you need to change.
You should Replace $_GET['owner'] with $_POST['owner'] as in your form you have specified method='post'
Replace:
$_GET['owner']
With:
$_POST['owner']
Since you are using the post method in your form, you have to check against the $_POST array in your PHP code.

Displaying Database Query Results

Suppose I have a form. After I submit my form, the data is submitted to dataprocess.php file.
The dataprocess.php file processes the variable sent via form and echoes desirable output.
It seems impossible to echo to a specified div in specified page only using PHP (without using AJAX/JavaScript as well). I do not want to use these because some browsers might have these disabled.
My concern is that I want to maintain the same formatting of the page that contained the form element. I want the form element to be there as well. I want the query result to be displayed below the form.
I could echo exact html code with some modification but that's memory expensive and I want it systematic.
Is it possible to process the form within the same page? Instead of asking another .php file to process it? How does one implement it?
The above is just for knowledge. It will be long and messy to include the PHP script within the same HTML file. Also, that method might not be efficient if I have same process.php file being used by several forms.
I am actually looking for efficient methods. How do web developers display query result in same page? Do the echo all the html formatting? also, does disabling JavaScript disable jQuery/AJAX?
Yes it is possible to process the form on the same page.
<?php
if (isset($POST))
{
//write your insert query
}
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<!-- Your form elements and submit button -->
</form>
<table>
<?php
//your select query in a while loop
?>
</table>
</body>
</html>
But if you choose this technique instead of ajax, you have to refresh all the page for each insert action.
An example
<div id="dialog-form">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<table>
<tr>
<td>Job</td>
<td>
<input type="text" name="job" />
</td>
</tr
</table>
<input type="submit" value="Insert" />
</fieldset>
<input type="hidden" name="doProcess" value="Yes" />
</form>
</div>
<?php
$myQuery= $db->prepare("INSERT INTO Jobs (job) VALUES (:p1)");
if (isset($_POST['doProcess']) && $_POST['doProcess'] == 'Yes')
{
$myQuery->bindValue(":p1", $_POST['job'], PDO::PARAM_STR);
$myQuery->execute();
}
?>
if you really dont want to use ajax (which i think you should). You can do something like this.
<form action="" method="POST">
<input type="text" value="something" name="something_name"/>
<?php
if(isset($_POST['something_name'])){
echo '<div id="display_something_name_if_exists">';
echo $_POST['something_name'];
echo '</div>';
}
?>
</form>
Basically what it does is submits to itself and then if there is a submission (tested with isset), it will echo a div with the correct information.

$_POST, image forms and mysql.How to get them working together?

I'm trying to get a website working. What I have are basically two images displayed (random, taken out of a mySQL database). What I need to do is (when the user clicks one of the images) the following:
Update the page, passing the info about the selected image (submit form);
Add one piece of data to the database (upvote the image)
I need to use $_POST to pass an array of values to the next page. So I thought:
<form name="input" action="the_page.php" method="POST">
<input type="image"
name="img"
src="image.png"
value ="dat1[\"data1\",\"data2\",\"data3\"]">
<!-- If value must be a single string, I'll use hidden inputs-->
</form>
<form name="input" action="the_page.php" method="POST">
<input type="image"
name="img"
src="image2.png"
value ="dat2[\"data1\",\"data2\",\"data3\"]">
</form>
Then I can upvote the selected image on the mySQL database with a little php upvote() function that updates the record. The upvoting process is done when the new page is loaded. From this, I have a couple questions:
I'm guessing the images will act as buttons, right? (They are supposed to submit the form, hence refreshing the page). If not, how can I achieve this? I'm unable to do it with a link (since I can't add the values to it). Maybe a javascript function? But I don't know how to submit the form that way either...
Once the page is reloaded, does it mean that only the data from one form has been submited, so I can retrieve the data by simply calling the PHP variable $_POST['img'] and get an array back?
EDIT: I now managed to get everything working, slightly similar to what I proposed initially. Thanks for the AJAX suggestion though, since it was what helped me solve it (looked up AJAX tutorials, found solution).
Here's my solution:
<?php
echo "<form name=\"input\" action=\"F2F.php\" method=\"POST\">";
echo "<input type=\"hidden\" name =\"table\" value=\"".$table1."\">";
echo "<input type=\"image\" name=\"nom\" src=\"".$IMG_Route1."\" value =\"".$Nom_base1."\" border=\"0\">";
echo "</form>";
?>
(where the image goes)
and then, on the header:
<?php
if ($_POST['nom']||$_POST['nom_x']){
if (!$_POST['nom']){
echo 'Could not retrieve name. $_POST[\'nom_x\'] = '.$_POST['nom_x']. mysql_error();
exit;
}
if (!$_POST['table']){
echo 'Could not retrieve table. $_POST[\'table\'] = '.$_POST['table']. mysql_error();
exit;
}
upvote($_POST['table'],$_POST['nom']);
}
?>
You can use one form and a set of radio buttons to simplify things a bit. Clicking on the label will toggle the radio button. You can use commas to separate multiple values for each checkbox, which you can then abstract later on (see below)
<form name="input" action="the_page.php" method="POST">
<ul>
<li>
<label>
<img src="whatever.jpg" />
<input type="radio" name="selectedImage" id="img1" value="12,16,19" />
</label>
</li>
<li>
<label>
<img src="whatever2.jpg" />
<input type="radio" name="selectedImage" id="img2" value="12,16,19" />
</label>
</li>
</ul>
</form>
You can detect when the radio button is selected by adding a listener for the change event, then submit the form.
$('input[name="selectedImage"]').change(function() {
$('form[name="input"]').submit();
});
To abstract the multiple values, you can then explode the form result with PHP, which will return an array of the values.
$selectedImageValues = array();
$selectedImageValues = explode(",", $_POST['selectedImage']);
From there you can pull the different values out and save the data to the database.

isset for link - PHP

I'm attempting to create a link for users to click that will remove them from a list. I'm trying to figure out how to do this without using a submit button and without using $_GET(if possible).
Anyway, I'm afraid to do it with $_GET (the way I have it now), because the user can type this in the URL (even though 99% wouldn't know how or think to do this) and they would be removed from the list.
How can I name the link so I can use $_POST?
$attendingUsers = mysql_query("Select acceptedInvites from events where eventID = ".mysql_real_escape_string($_GET['eventID'])." ");
$users= mysql_fetch_array($attendingUsers);
$user = $users['acceptedInvites'];
if(preg_match("/$userid/", $user)){
echo "You are attending this event</br>";
echo 'Click here to remove yourself from the list';
if($_GET['delete']=1){
$sql=...
}
}
Is it possible to do this without using $_GET? Thanks!
Never delete via a link. Read The Spider of Doom
Best way is to link to a "delete" page with an "are you sure" form. Submitting the form (via POST) performs the delete and redirects back to a suitable results page.
For example
Click here
to remove yourself from the list
Then, in remove.php
<?php
// get Event details via $_GET['eventID']
if (isset($_POST['confirm'])) {
// delete via SQL
// redirect
header('Location: http://example.com/events.php');
exit;
}
// display event details
?>
<form method="post" action="remove.php?eventID=<?php echo $eventId ?>">
<p>Are you sure?</p>
<input type="submit" name="confirm" value="Remove me from this event">
</form>
You should probably also look into CSRF protection but that's really outside the scope of this question.
Your are required to use either $_GET or $_POST
<form action="delete.php" method="post">
<input type="hidden" name="eventId" value="yourEventId" />
<a href="#" onclick="this.form.submit();" > Delete</a>
</form>
If I have my JavaScript right, this should do the trick:
Delete
<form id="delete" action="delete.php" method="post">
...
</form>
The link will then submit the form.
You could use some kind of encoding to make the get var unreadable, like an md5 or even an encrypted string.

I can't get checkboxes values

I got this and I have no idea what I'm missing here:
<?php
//Some validation for the SUBMIT form
if(isset($_POST['submit'])&&$_POST['submit']=='add'){
$_POST = array_map("mysql_real_escape_string", $_POST); //This little fella is responsible for the mess ¬¬
$campus_string = $_POST['campus']; //To get a checkboxes Array
....
print_r($campus_string); //to see if I am getting the checkboxes when submitting
}
?>
....
//Now inside <body> of the HTML
<form action="" method="post" name="filosofal">
//A little loop to create the checkboxes from a DB
foreach($campi as $keyCampi => $valueCampi){
echo '<tr>
<td>
<input type="checkbox" id="campus[]" name="campus[]" value="'.$value['Id'].','.$valueCampi['Id'].'" />'.$valueCampi['Nombre'].'<br />
</td>
</tr>';
}
</form>
But print_r doesn't show anything, the array is not being stored when submitting via POST. Hope you can help me to pinpoint where I'm screwing it.
EDIT: Solved
Well, I finally figured it out, it's kind of embarrasing.
In my code, I use:
$_POST = array_map("mysql_real_escape_string", $_POST);
to avoid some encoding conflicts (like names with 's on them), security and such.
I commented the line and it works now (didn't add that part since I wasn't aware its relevance on the issue), no changes needed to be done.
Don't know why it took me five days to find that little thing over there, but now is done. Anyways, thanks everyone.
Try adding
<input type="hidden" name="submit" value="add" />
Into your form, at the moment your if statement will be returning false...
Try dumping the post data:
echo "<pre>";
print_r($_POST);
//if you check the radio then it will be listed in your $_POST dump
//add action to your form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
foreach($campi as $keyCampi => $valueCampi){
?>
<tr>
<td>
<input type="checkbox" id="campus[]" name="campus[]" value="<?php echo $valueCampi['Id'].','.$valueCampi['Id']; ?>" /><?php echo $valueCampi['Nombre'].'<br />
</td>
</tr>';
<? php } ?>
</form>
Generally speaking, the way I see it is that checkbox is either ON or OFF. Therefore, in my mind, the name of the checkbox is the value. For instance:
<input type="checkbox" name="single"> Single?
If that checkbox is checked (value="on"), then the answer is yes. If it is not checked (value="off" or no value), then the answer is no. Therefore, my PHP code looks something like:
if ($_POST['single'] == 'on')
$single = true;
else
$single = false;
Basically, as far as I'm concerned, the "value" of a checkbox should never be set. That's my particular preference though, and it's worked well for me. It may not suit your needs, though.
Good luck.

Categories