Grabbing data from two HTML forms from the same page - php

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!">

Related

Pressing 'update' button in my Php edit page while a field is empty removes the id from the URL

So I have a PHP CRUD system which adds, edits and deletes entries from/to a database. The CMS in question is a drugs table. I can add drugs to this table using the add button and filling in a form, I can also delete the drugs by simply deleting them. But the one of issue is the edit/update part of the system.
The edit feature itself works fine, I'm able to edit an entry and it will post to the database and show up in the table because the user gets redirected back to the table page which shows all the drugs, however, when I remove the text from a field, leaving it empty, and press update, I get an error message which says a text field is empty, however, I also notice the id at the top of the page is no longer there which gives me an Undefined index:error.
I've narrowed the problem down to it being simply because the input type "submit" removes it for some reason.
URL before pressing update with a text field empty:
php_files/DrugEdit.php?Drug_ID=23
URL after pressing update with a text field empty:
eMAR/php_files/DrugEdit.php
How the program works (with code):
Php variable created by getting the Drug_ID from the URL (in this case 23)
$Drug_ID = $_GET['Drug_ID'];
Then gets the field data from the database and assigns them to variables
$result = mysqli_query($conn, "SELECT * FROM drugs WHERE Drug_ID=$Drug_ID");
while($res = mysqli_fetch_array($result))
{
$Drug_Name = $res['Drug_Name'];
$Allergies = $res['Allergies'];
$Side_effects = $res['Side_effects'];
$Type_of_Medication = $res['Type_of_Medication'];
$Dosage = $res['Dosage'];
}
?>
The data is then shown in a form where I can edit the data
<form name="form1" method="post" action="DrugEdit.php">
<table border="0">
<tr>
<td>Drug_Name <?php echo $drug_name_error ?></td>
<td><input type="text" Name="Drug_Name" value="<?php echo $Drug_Name;?>"></td>
</tr>
<tr>
<td>Allergies</td>
<td><input type="text" Name="Allergies" value="<?php echo $Allergies;?>"></td>
</tr>
<tr>
<td>Side_effects</td>
<td><input type="text" Name="Side_effects" value="<?php echo $Side_effects;?>"></td>
</tr>
<tr>
<td>Type_of_Medication</td>
<td><input type="text" Name="Type_of_Medication" value="<?php echo $Type_of_Medication;?>"></td>
</tr>
<tr>
<td>Dosage</td>
<td><input type="text" Name="Dosage" value="<?php echo $Dosage;?>"></td>
</tr>
<tr>
<td><input type="hidden" Name="Drug_ID" value=<?php echo $_GET['Drug_ID'];?>></td>
<td><input type="submit" Name="update" value="Update"> </td>
</tr>
</table>
</form>
If the update button gets pressed, it runs the block of code below:
$drug_name_error = " ";
if(isset($_POST['update']))
{
$Drug_ID = $_POST['Drug_ID'];
$Drug_Name=$_POST['Drug_Name'];
$Allergies=$_POST['Allergies'];
$Side_effects=$_POST['Side_effects'];
$Type_of_Medication=$_POST['Type_of_Medication'];
$Dosage=$_POST['Dosage'];
// checking empty fields
if(empty($Drug_Name) || empty($Allergies) || empty($Side_effects) || empty($Type_of_Medication) || empty($Dosage)) {
if(empty($Drug_Name)) {
$drug_name_error = "<font color='red'>Drug_Name field is empty.</font><br/>";
}
if(empty($Allergies)) {
echo "<font color='red'>Allergies field is empty.</font><br/>";
}
if(empty($Side_effects)) {
echo "<font color='red'>Side_effects field is empty.</font><br/>";
}
if(empty($Type_of_Medication)) {
echo "<font color='red'>Type_of_Medication field is empty.</font><br/>";
}
if(empty($Dosage)) {
echo "<font color='red'>Dosage field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($conn, "UPDATE drugs SET Drug_Name='$Drug_Name' ,Allergies='$Allergies' ,Side_effects='$Side_effects' ,Type_of_Medication='$Type_of_Medication',Dosage='$Dosage' WHERE Drug_ID=$Drug_ID");
//redirecting to the display page. In our case, it is index.php
header("Location: ../drug_manager.php");
}
}
Thank you for taking the time to read my problem. Hopefully I've provided enough information for you.
input type "submit" removes it for some reason
Because you're submitting the form, and the URL for the form submit action is defined in the <form> element:
<form name="form1" method="post" action="DrugEdit.php">
Note that there's no Drug_ID value on that URL. However, in the form processing code you're not looking for it in the URL, you're looking for it in the form post:
$Drug_ID = $_POST['Drug_ID'];
So I'm not really sure where you're getting that error. But if somewhere in your form logic you're also looking for $_GET['Drug_ID'], or simply want it to be on the URL for some downstream need, then you can just add it to that URL:
<form name="form1" method="post" action="DrugEdit.php?Drug_ID=<?php echo $_GET['Drug_ID'];?>">

Retrieve Data from data base to html form on button CLICK

I am actually starting my newest codes with HTML/PHP .
I am searching for retrieving data (list of persons) from mysql Data Base, displaying it into html table, then when I will clik on button "edit" it will show me in another page the details of the selected person like this :
It works fine for all the rows expects the firt row of the table.
Any help please !!!
there is my code :
<table border = 1>
<caption> Liste des personnes </caption>
<tr>
<th>id </th>
<th>nom</th>
<th>prenom</th>
<th>date Naissance</th>
<th>sexe</th>
<th>ville</th>
<th>comptence</th>
<th>photo</th>
</tr>
<?php while ($obj = mysqli_fetch_object($result)){ ?>
<tr>
<td> <?= $obj->id ?> </td>
<td><?= $obj->nom?></td>
<td><?= $obj->prenom?></td>
<td><?= $obj->dateNaissance?></td>
<td><?= $obj->sexe?></td>
<td><?= $obj->ville?></td>
<td><?= $obj->competence?></td>
<?php if (isset($obj->photo)) {?>
<td><img src="uploads/<?= $obj->photo?>" width =20 height = 20 >
<?php } ?>
<td>
<form name="editPerson" action="edit.php" method="POST">
<input type="hidden" name="id" value="<?= $obj->id ?>">
<input type="submit" name="editer" value="Edit">
</form>
</td>
</tr>
<?php } ?>
</table>
Explainations
You can't have an action='edit.php' as you will edit a specific user, not all of them. You need to specify in your action what user you want to edit. And it is mostly done with the ID of the user. So you action will look like this action='edit.php?id=1. And so, your method would be GET.
In your edit.php, you will have a $_GET['id'] variable that will contain the ID of the user to be edited. So you will have to first create a new query to search for this specific user.
You can then proceed on preparing the query.
$query = $connexion->prepare('SELECT * FROM users WHERE id = :id');
And then, executing the query with the id from the URI.
$query->execute(['id' => $_GET['id']]);
And cast the result to a variable to get the user.
Then, all you have to do in your page is a little bit of refactoring from your previous page. Meaning that there will be now a big <form> tag surrounding your <table> tag and the <td> tag will now contain <input value='<?php $user->id; ?>'> tag for example for the ID. And your edit buttons will now be a save button.
The method of the <form> in your edit?id=1 would be a POST method ot itself. So in the same page, you will be able to update the user. You can also cast the form to another page, like saveUser.php. Just be consistent from one solution to another in all your project.
<form method='POST' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
Use this Code
<input type="submit" name="editer" value="Edit">
Instead of
<form name="editPerson" action="edit.php" method="POST">
<input type="hidden" name="id" value="<?= $obj->id ?>">
<input type="submit" name="editer" value="Edit">
</form>
And get the id value on edit.php file by using $_GET['id'].
Example for edit.php file:
$id = $_GET['id']

How to memorize a radio selection (twice)

this is probaly an easy one, but I just cant seem to figure it out. I've tried googling for this aswell, but without any luck to my particular problem...
What I want, is that the radio selection gets remembered two times (kinda), it remembers after the first time I click submit. But when I click submit again on my next page, it wont remember the value.
Well, I want all the information stored in my database pretty much..
Thanks!
EDIT 1: Oh yeah, the thing that does not go into my database is "valgt_skap" or in other words "radios", everthing else works fine.
Bokssvar.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
<title>Registrering</title>
</head>
<body>
<?php
if(isset($_SESSION['boxfeil'])) echo $_SESSION['boxfeil'];
unset($_SESSION['boxfeil']);
?>
<form action="bestilt.php" method="post" name="inputform_Field">
<table id="valgt_skap_tabell" class="bokssvartabell">
<tr>
<td>Valgt skap</td>
</tr>
<tr>
<td>
<input class="bokssvarskjema" type="text" name="valgt_skap" disabled value= <?php
if(isset(($_POST['radios']))){
echo ($_POST['radios']);
} else {
header('location: index.php');
} ?>>
</td>
</tr>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
<td>Telefon:</td>
<td>E-post:</td>
<td>Elev Nummer:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn_nm" id="fornavn_check"></td>
<td><input type="text" name="Etternavn_nm" id="etternavn_check"></td>
<td><input type="text" name="Telefon_nm" id="telefon_check" maxlength=8></td>
<td><input type="text" name="E-post_nm" id="epost_check"></td>
<td><input type="text" name="Elevnummer_nm" id="elevnr_check"></td>
</tr>
</table>
<div style="text-align:center;">
<button id="bestill_skap" type="submit" name="bestill_Skap">Bestill skap</button>
</div>
</form>
</body>
bestilt.php
<?php
require 'connectdb.php';
$inputFornavn_check = $_POST['Fornavn_nm'];
$inputEtternavn_check = $_POST['Etternavn_nm'];
$inputTelefon_check = $_POST['Telefon_nm'];
$inputEpost_check = $_POST['E-post_nm'];
$inputElevnr_check = $_POST['Elevnummer_nm'];
$inputSkap_check = $_POST['valgt_skap'];
$insertInfo_query = "INSERT INTO elever (Fornavn, Etternavn, Telefon, Epost, ElevNr, Skap)
VALUES ('$inputFornavn_check' , '$inputEtternavn_check' , '$inputTelefon_check' , '$inputEpost_check' , '$inputElevnr_check' , '$inputSkap_check')";
$connect_DB->query($insertInfo_query);
?>
Try using sessions to store the value. First use session_start(), then store in $_session['fieldname']=value. Then you can use it in the preceding pages.
On the second page, receive the value and put it on a hidden form element.
<form>
...
<input type="hidden" name="valgt_skap" value="$radioValue">
...
</form>
This element is not shown on the page, although it's present and submited with the form.

Store PHP/SQL foreach form items in variables

Sorry I'm a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP/SQL problem.
I have a PDO statement that gets all users from a database.
With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row of the user I select, then click submit and store the users name and also the number. I will use this information to populate another database later.
My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error.
I also specified to 'POST in the form but it doesnt seem to be doing that.
Does anyone have any ideas?
Thanks
//function.php
function getName($tableName, $conn)
{
try {
$result = $conn->query("SELECT * FROM $tableName");
return ( $result->rowCount() > 0)
? $result
: false;
} catch(Exception $e) {
return false;
}
}
//form.php
<form action "index.php" method "POST" name='form1'>
<table border="1" style="width:600px">
<tr>
<th>Name</th>
<th>Number Entered</th>
<tr/>
<tr>
<?php foreach($users as $user) : ?>
<td width="30%" name="FullName">
<?php echo $user['FullName']; ?>
</td>
<td width="30%">
<input type="int" name="NumberedEntered">
</td>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" value="submit"></td>
</form>
//index.php
$users = getName('users', $conn);
if ( $_REQUEST['NumberedEntered']) {
echo $_REQUEST['NumberedEntered'];
echo $_REQUEST['FullName'];
}
The variable FullName isn't transmitted by your form to index.php. Only values of form elemnts are sent. You can add a hidden form field, that contains FullName like this:
<input type="hidden" name="FullName" value="<?php echo $user['FullName']">
But your second problem is, that your foreach loop will create several input fields with the exact same name. You won't be able to recieve any of the entered numbers, except the last one. have a look at this question for possible solutions.
Update
Putting each row in individual form tags should solve your problem:
<?php foreach($users as $user) : ?>
<form action="index.php" method="POST">
<tr>
<td align="center" width="40%" >
<?php echo $user['FullName']; ?>
<input type="hidden" name="FullName" value="<?php echo $user['FullName']; ?>" />
</td>
<td width="30%">
<input name="NumberedEntered"/>
</td>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</form>
<?php endforeach; ?>

PHP MySQL setting session on submit from table generated by MySQL

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!

Categories