I have a slight problem with my php script. I have a table that generates rows populated by a MySql statement.
At the last column I have a button for edit, and delete. My problem is when I hit delete, the query works successfully but it redirects me to a blank page!
The header location is correct but when I hit delete it stays on the current page, but it is just a plain white page.
<?php foreach($rows as $row): ?>
<tr>
<td>
<form action="" method="post"> <?php echo $row['id']; ?> </form>
</td>
<td>
<form action="" method="post"> <?php echo $row['roleid']; ?> </form>
</td>
<td>
<form action="" method="post">
<?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?>
</form>
</td>
<td>
<form action="" method="post">
<?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8'); ?>
</form>
</td>
<td>
<form action="" method="post">
<input name="Edit" type="submit" value="Edit" />
<input name="id" type="hidden" value="<?php echo $row['id']; ?>" />
</form>
</td>
</tr>
<?php endforeach; ?>
And I can successfully set a session using:
if (isset($_POST['Edit'])) {
$_SESSION['id'] = $_POST['id'];
header("Location: edit_account.php");
}
But it seems I have ran into another problem:( I also want to add a delete button on each row to delete that user account. Right now this is how it looks:
<td> <form action="" method="post">
<input name="Delete" type="submit" value="Delete" />
<input name="id" type="hidden" value="<?php echo $row['id']; ?>" />
</form> </td>
And the php code used is:
if (isset($_POST['Delete'])) {
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
DELETE
FROM user
WHERE
id = :id
";
// The parameter values
$query_params = array( ':id' => $_POST['id'] );
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetch();
// This redirects the user back to the members-only page after they register
header("Location: ../adminindex.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to adminindex.php.php");
}
My problem is the redirection! When I click on the Delete button it actually runs the query but afterwards it just redirects to memberlist.php but the page is blank!?
Why would this be happening? Is there something I am missing?I have tried changing the header location with no success.
Thanks for the help!
die("Redirecting to adminindex.php.php"); ??
Why don't you use a switch?
like this:
switch($action){
case 'delete':
//your code here
break;
case 'edit':
//your code here
break;
}
and to do the delete button:
echo $row['username'] ."<img src=some fancy img>";
Related
So I've searched through some posts, and I've seen that I can't use a HTML form within another HTML form.
Like:
<form method="post" action="x.php">
<input type="..."/>
<form method="post" action="x.php">
<input type="..."/>
</form>
</form>
Ok, but my problem is that I want to make a different page, which contains HTML code like this:
<?php
if(isset($_GET['vote']) && $_GET['vote']=='yes'){
echo 'vote successfully inserted';
}
# gets the email value from MAIN form
$email = isset($_POST['email'] : $_POST['email'] : NULL;
#grab the infos from bd for the user with that email,
$stmt = $db->prepare('SELECT name,email,vote FROM tbl WHERE email=:e');
$stmt->execute(array(':e'=>$email));
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
if($row->vote == 'no'){ # IF THE USER DIDN'T VOTED, THEN
if(isset($_POST['vote'])){ # IF THE <a> IS PRESSED, UPDATE DB
$sql = "UPDATE tbl SET vote='yes' WHERE email=:e";
$s = $db->prepare($sql);
$s->execute(array(':e'=>$email));
}
}
?>
<table>
<tr>
<td>Name</td>
<td>Email</td>
<td>Address</td>
<td>Vote</td>
</tr>
<tr>
<td><?php echo $row->name;?></td>
<td><?php echo $row->email;?></td>
<td><?php echo $row->address;?></td>
<td>
<form method="POST" action="" id="SECOND">
VOTE!
</form>
</td>
</tr>
</table>
<?php } // end while() ?>
Then, under this <table>, I have another form:
<form action="" method="POST" id="MAIN>
<input type="text" name="email" placeholder="email"><br/>
<input type="submit" value="Login" name="submit"/>
</form>
The project is about a electoral campaign, where a user can 'login' with this email address, and submit his vote.
So,
when the user requests the page, the MAIN form will pop-up, he will fill in his email, and will press submit.
he is redirected to the same page (I'm hiding the MAIN form), and the table will pop-up.
now, the user can select his favorite candidate, and press on the <a> link - his vote will be stored in db, updating the vote field from, initially 'no' to 'yes'.
Now, the prob is that when the <a> link is pressed, the update in the db doesn't take place.
The reason the link doesn't update the database is because the form is not being submitted. Change the to an
<input type="submit" value="VOTE!">
So here is goes. I have a website that has a login. Upon a successful login, a session variable called user is created which contains an array of the userid, username, email and so on. Then from there I have links to other pages. What is giving me trouble is that I have a page called membership.php. This page does a select query for the userid, username, email and generates a table with all of the users. There is also a submit button beside each user that is entitled "Edit". When this button is clicked it redirects to a page edit_account.php. My goal here is when i click on the edit button, a session variable is created containing the userid of that specific user. Then when it redirects to the edit_account.php page I can use that session as part of my select statement to gather data from the table and then edit that users details. Below is a snipit of my code so you can see what I am talking about.
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: ../../index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT
id,
roleid,
username,
email
FROM user
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if (isset($_POST['Edit'])) {
$_SESSION['id'] = $_POST['id'];
header("Location: edit_account.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Registration</title>
<link href="../../css/default.css" rel="stylesheet" type="text/css" />
</head>
<div id="container">
<div id="header">
<h1>
</h1>
</div>
<div id="navigation">
<ul>
<li>Home</li>
<li>About</li>
<li>Services</li>
<li>Contact us</li>
<li>Logout</li>
</ul>
</div>
<div id="content">
<h2>
Users
</h2>
<form action="" method="post">
<table border="0" align="left" cellpadding="25px">
<tr>
<th>ID</th>
<th>Role ID</th>
<th>Username</th>
<th>E-Mail Address</th>
</tr>
<?php foreach($rows as $row): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['roleid']; ?></td> <!-- htmlentities is not needed here because $row['id'] is always an integer -->
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><input name="Edit" type="submit" value="Edit" /></td>
<td><input name="id" type="hidden" value="<?php echo $row['id']; ?>" /></td>
</tr>
<?php
endforeach;
?>
</tr>
</table>
</form>
</div>
<div id="footer">
Copyright © 2013
</div>
</div>
<body>
</body>
</html>
I believe the problem resides in the block of code:
if (isset($_POST['Edit'])) {
$_SESSION['id'] = $row['id'];
header("Location: edit_account.php");
}
But I have tried many things and nothing seems to work. Also on edit_account.php page I have this code at the top:
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
which spits out everything in the session variable. When I select the submit button and it redirects, this is the output of the above code.
array(2) {
["user"]=>
array(4) {
["id"]=>
string(1) "1"
["username"]=>
string(5) "admin"
["roleid"]=>
string(1) "1"
["email"]=>
string(15) "admin#admin.com"
}
["id"]=>
NULL
}
Thank you in advance for the help. Anything is greatly appreciated.
The main problem is that you're basically building a form that looks (stripping out all the fluff html):
<form>
<input name="Edit" type="submit" value="Edit" />
<input name="id" type="hidden" value="foo" />
<input name="Edit" type="submit" value="Edit" />
<input name="id" type="hidden" value="bar" />
<input name="Edit" type="submit" value="Edit" />
<input name="id" type="hidden" value="baz" />
etc...
</form>
There's just ONE form, with multiple submit buttons, and multiple copies of the same hidden field with the same name. As such, PHP will use the LAST hidden id value to populate $_POST with. There is NO way for PHP to tell which of the many submit buttons was clicked, or that it should try to use the id value next to that one particular submit button - that's not how HTTP forms work.
You need something more like this:
<table>
<tr><td><form><input type="hidden" name="id" value="foo"><input type="submit"></form></td></tr>
<tr><td><form><input type="hidden" name="id" value="bar"><input type="submit"></form></td></tr>
<tr><td><form><input type="hidden" name="id" value="baz"><input type="submit"></form></td></tr>
etc..
</table>
Note now EACH row has its OWN form, with one submit button and one hidden field within. This way, only that ONE hidden field is submitted, and you'll get the proper id value showing up in your PHP code.
put form code in each table row not on the whole table a single form.
another problem is u login from admin account and u are making changes of the admin session variable so declare another session variable for it.
or u can also put the update code at the starting of the page that either the form is submited so update the user data than no need of making changes in the session variable.
This is great. Thank you Marc B. Exactly what I was looking for. This is the html code:
<?php foreach($rows as $row): ?>
<tr>
<td> <form action="" method="post"> <?php echo $row['id']; ?> </form> </td>
<td> <form action="" method="post"> <?php echo $row['roleid']; ?> </form> </td>
<td> <form action="" method="post"> <?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?> </form> </td>
<td> <form action="" method="post"> <?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8'); ?> </form> </td>
<td> <form action="" method="post"> <input name="Edit" type="submit" value="Edit" /> <input name="id" type="hidden" value="<?php echo $row['id']; ?>" /> </form> </td>
</tr>
<?php endforeach; ?>
And I can successfully set a session using:
if (isset($_POST['Edit'])) {
$_SESSION['id'] = $_POST['id'];
header("Location: edit_account.php");
}
But it seems I have ran into another problem:( I also want to add a delete button on each row to delete that user account. Right now this is how it looks:
<td> <form action="" method="post"> <input name="Delete" type="submit" value="Delete" /> <input name="id" type="hidden" value="<?php echo $row['id']; ?>" /> </form> </td>
And the php code used is:
if (isset($_POST['Delete'])) {
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
DELETE
FROM user
WHERE
id = :id
";
// The parameter values
$query_params = array(
':id' => $_POST['id']
);
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetch();
// This redirects the user back to the members-only page after they register
header("Location: ../adminindex.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to adminindex.php.php");
}
My problem is the redirection. When I click on the Delete button it actually runs the query but afterwards it just redirects to memberlist.php but the page is blank!? Why would this be happening? Is there something I am missing?I have tried changing the header location with no success. Thanks for the help!
Hi I'm trying to update a single field from a HTML form, for some reason one of the session variables I am passing to the update query is not being accepted. I have already echoed the variable in the page so am fairly certain it exists in memory.
NB, I know my code is horrifically insecure but I'm learning PHP and once I've got the basics working Ill go over it and bring it upto best practice standards.
E2A: If I do var_dump($filename); before trying to run the query it returns string(6) "356/18", after the query it returns NULL. I'm not unsetting the variable anywhere so where could it be going!
Here is my form:
<form method="post" action="">
<p>Your username is: <?php echo $_SESSION['userid'] ?> Your company ID is: <?php echo $companyid['id']?></p>
<h3>Please enter note for file: <?php echo $filename; ?></h3>
<table width="200" cellpadding="5">
<tr>
<th width="18%" align="right" nowrap>Add Note: </th>
<td width="82%" nowrap>
<input type="text" name="note" />
</td>
</tr>
<tr>
<td colspan="2" width="100%" nowrap>
<input type="submit" value="Submit" name="Submit" />
</td>
</tr>
</table>
</form>
Here is my UPDATE query:
$sql = "UPDATE fields SET Notes = ('".mysql_real_escape_string(stripslashes($_REQUEST['note']))."')
WHERE companyId='".$companyid['id']."' AND fileNumber ='".$filename."'";
if($result = mysql_query($sql)) {
echo "<h1>Thank you</h1>Your information has been entered into our database<br><br>";
echo $sql;
echo $filename;
} else {
echo "ERROR: ".mysql_error();
}
} else {
echoing $sql produces the following:
UPDATE fields SET Notes = ('asdasda') WHERE companyId='11' AND fileNumber =''
and here is the bit where I instantiate the POST vars.
include "header.php";
$checkFiles = "checkFiles.php";
// Catches form input from previous page and stores it into session variable called filename for future reference;
$_SESSION['filename']=$_POST['filename'];
$filename = $_SESSION['filename'];
//User id stuff from previous page too;
$userid = $_SESSION['userid'];
$id = mysql_query("SELECT id FROM users WHERE DXNumber='".$userid."'");
// Returns pointer so fetch it as an array and insert it into variable $companyid for later use;
$companyid = mysql_fetch_array($id);
You need to include session_start() on the top of each file.
Just do:
AND fileNumber ='".$_SESSION[filename]."'";
In your update query.
If that doesn't work, make sure that a value for $_SESSION[filename] is being set.
<h3>Please enter note for file: <?php echo $filename; ?></h3>
Create a input box
<input type="text" name="filename" value="<?php echo $filename; ?>"/>
Then filename value will be pass to $_POST array
So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...
My website is featuring online classified advertisements, programmed by PHP and MySQL. The following code let the administrator delete multiple records using the checkbox tool.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<td><? echo $rows['CountryName']; ?></td>
<td><input name="delete_items[]" type="checkbox" value="<?php echo $rows['id']; ?>" /></td>
</table>
<input type="submit" name="deleteSelected" value="Submit" >
</form>
<?php
if(isset($_POST['deleteSelected'])) {
$delete_items = join(', ', $_POST["delete_items"]);
$query = "DELETE FROM $table_name WHERE id IN ($deleted_items)";
$result = mysql_query($query);
header("Location: admin.php"); }
?>
When I press the submit button without checking boxes (all boxes are unchecked), I receive the following error message (p.s. the script is working well without any error message, if any Checkbox being checked):
Warning: join() [function.join]: Invalid arguments passed in C:\xampp\htdocs\admin_listing.php on line 87
I’ve tried the implode function instead of using join, but still I'm getting an error message.
Maybe I do not passing an array through the function correctly, but I cannot find a solution for the above.
Any advise would be appreciated.
It looks like you are displaying all the records from your database into a single input in the form.
The code will probably work well with the implode() as you tried, but you will need to use a loop in the displaying of the form to generate it properly with the options.
Something like this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<?php
while($row=$databaseResult) //however you are getting the data out of the database.
{
echo "<tr><td>".$rows['CountryName']."</td><td><input name='delete_items[]' type='checkbox' value=".$rows['id']."/></td></tr>";
}
?>
</table>
<input type="submit" name="deleteSelected" value="Submit" >
</form>
Thank you all for trying to help, I found a simple solution by adding one code line, as follows:
<?php
if(isset($_POST['deleteSelected'])) {
if(isset($_POST["delete_items"][0])) {
$delete_items = join(', ', $_POST["delete_items"]);
$query = "DELETE FROM $table_name WHERE id IN ($delete_items)";
$result = mysql_query($query);
header("Location: admin.php");
}
}
?>
Hope it can help someone else...