I'm having trouble with this form. I want the user to be able to edit an item in the datebase. They chose which item they want to edit on one page and get sent with a GET to the editing page. The GET has the id of the item they need to edit.
The editing page loads with the details of the item inserted into the user form (apart from the name of the file) this field is left blank. I am trying to do some logic that checks if the user has chosen a file.
If they haven't then this field should be ignored as I will presume the user is happy with the file that is already uploaded.
If they chose a file then this means they want this to be the new picture. Only then do I want to run the logic to upload the picture and insert its name into the database.
I'm getting my POST details by saying:
$clean_pic = $_POST['pic'];
I am then saying if it's blank do nothing otherwise run the upload:
if($clean_pic = ''){}
else{
It's not working. Any ideas how I should find out if its blank? Cut down code:
if (isset($_POST['add']))
{
// validate 'pic': must consist of alphanumeric characters only.
$_POST['pic'] = isset($_POST['pic']) ? $_POST['pic'] : '';
//if(preg_match('/\.(jpg|gif|jpeg)$/i',$_POST['pic']))
//{
$clean_pic = $_POST['pic'];
//}
//else
//{$error++; $errmsg .= 'Invalid pic. ';}
}
if (isset($_POST['add']) && ($error==0))
{
if (!isset($_POST['pic'])) { echo"test1";}
else {echo"test222";}
/*tied this too but it didnt work (it will always display result 1):
if (!isset($_POST['pic'])) { echo"test1";}
if (isset($_POST['pic'])) {echo"test222";}*/
}
else //output error messages
{
/////////render form
?>
<form enctype="multipart/form-data" action="" method="post" id="save"><fieldset>
<table id="site-form">
<tr>
<td class="one_of_three"><label>Item Name: </label></td>
<td class="two_of_three"><input type="text" name="fileName" id="fileName" value="<?php echo"$db_name";?>"/></td>
<td><label class="errors" id="fileNameError"> </label></td>
</tr>
<tr>
<td class="one_of_three"><label>Picture: </label></td>
<td class="two_of_three"><input type="file" name="userfile[]" id="pic"/></td>
<td><label class="errors" id="picError"> </label></td>
</tr>
<tr>
<td class="one_of_three"> </td>
<td class="two_of_three"><input name="add" id="save_button" type="submit" value="Update"/> Cancel.</td>
<td> </td>
</tr>
</table>
</fieldset></form>
<?php }?>
What about if (!isset($_POST['pic']))?
You cant access the file using 'id' attribute ('pic'). You have to use the value of 'name' attribute ('userfile'). You can check whether the file is uploaded or not using $_FILES array in php.
if(isset($_FILES) && isset($_FILES['userfile']) && (trim($_FILES['userfile']['name']) != '') ) {
//Your upload code here
}
else
{
//No file uploaded
}
You need to check to things :
one is $_POST['pic'] is an array
second one is in the form you have to use enctype="multipart/form-data" attribute.
Related
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'];?>">
I'm having some difficulty with php forms.
I have created a page called 'post_details.php' (this simply displays a photo of a product & description). Each product has a unique id
Within posts_details.php, I have used to include command to include a form. This form allows users to send me feedback regarding the product.
For some reason the form is not workin. Everytime the submit button is clicked, the alert box warns me that I need to complete the form (even if the form is complete)
The last part of line one doesn't seem to work. It's not picking up the post_id
Can anyone please help ??
post a comment
<form method="post" action="post_details.php?post= <?php echo $post_id; ?>">
<table width "600">
<tr>
<td>Your email:</td>
<td><input type="text" name="comment_email"/></td>
</tr>
<tr>
<td>Your Comment:</td>
<td><textarea name="comment" cols="35" rows="16"/></textarea></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="postcom"/></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['comment'] )) {
$comment_email = $POST['comment_email'];
$comment = $POST['comment'];
if( $comment_email=='' OR $comment=='') {
echo "<script>alert('Please complete form')</script>";
echo "<script>window.open('post_details.php?post=post_id')</script>";
exit();
}
else {
echo "complete";
}
}
?>
You have error here
if(isset($_POST['comment'] )) {
$comment_email = $POST['comment_email'];
^
$comment = $POST['comment'];
^
....
Instead of $POST it must be $_POST['comment_email'] and $_POST['comment']
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; ?>
Well, I have the following problem: my little test website is near completion and all that’s left is PHP validation on submit. But there exactly lies my problem. I can’t seem to let it validate when the user clicks submit.
I searched plenty of websites but on all of those they submit the page to the same page, and I submit the page to a new page. I don’t know how different this is from the first method but I can’t seem to get it to work.
I have 5 fields in my form which need to be required:
<table>
<tr>
<td align="right">Naam:</td>
<td align="left"><input type="text" name="naam" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Woonplaats:</td>
<td align="left"><input type="text" name="woonplaats" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Straatnaam:</td>
<td align="left"><input type="text" name="straatnaam" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Huisnummer:</td>
<td align="left"><input type="text" class="formnumbers" name="huisnummer"/></td>
</tr>
<tr>
<td align="right">Telefoonnummer:</td>
<td align="left"><input type="text" name="telefoonnummer" onkeydown="return phonenumber(event)"/></td>
</tr>
</table>
That’s all. My form action is as follows:
<form action="?page=pizza_bestelling" method="post" name="orderform">
I know PHP validation should be really easy (at least that’s what I’ve heard) but I can’t seem to work it out myself, so that’s why I decided to ask it here.
Now all it needs to do is check if one of those 5 fields is empty, if so don’t submit. Otherwise submit.
(Keep in mind that I have 16 fields in my form, it counts only for these 5 specific, the other 11 can be empty)
I appreciate any help in this matter, since it’s all that’s left before completing my website!
Thanks in advance!
Upon submiting you will lose "?page=pizza_bestelling" of the link, you can set it in a hidden input with that value if you need it passed.
set the method to method="post" in the form
and on the same page you will need something like
function validate_form($data)
{
//rules that will end with return false; if they are not valid
// example
if (!isset($data["naam"]) || $data["naam"] == '') return false; // if the name is not set or it's empty
// return true if all validation checks are passed
return true;
}
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$form_data['naam'] = $_POST['naam'];
$form_data['woonplaats'] = $_POST['woonplaats'];
// and so forth for each variable
// run the validate_form function for the data you got through POST
validate_form($form_data);
}else
{
//form displayed here
}
You want to set up an errors array which will store any errors, and allow you to print them out if necessary.
Then you check each variable in the following manner:
$errors = array(); //initialise error array
if (empty($_POST['naam'])) {
$errors[] = 'You forgot to add a name';
} else {
$name = trim($_POST['naam']);
}
This checks if the naam input and writes a message to the errors array if it's empty, or assigns the value to the $name variable if not.
Once you've gone through all your inputs, you can then perform a check on the errors array:
if (empty($errors)) { // If everything's OK.
//do what you need to do
} else {
echo '<p>The following errors occurred:<br/>';
foreach ($errors as $msg) {
echo "$msg<br/>\n";
}
echo '<p>Please try again</p>';
}
This only checks for empty fields of course - you should implement more validation for valid emails etc. For useability purposes you should really look at a one-page solution with sticky fields though.
Do a for each as follows:
$allowed = array("naam","woonplaats","stratnaam","formnumbers","telefoonnummer");
foreach ($allowed as $key => $val){
if($_POST[$key] == "")
$errors = true;
}
if($errors){
// don't submit
}
else {
// submit
}
My issue is I have a PHP $_POST that returns a null or empty value, and I personally do not see any error with my code (but I know its there) and I can't really step away from it for a few hours since I am on a time schedule. So, I was hoping someone could help me out ;)
Here is what I have, basically:
<table border="0" align="center">
<tr>
<td>
<div id="lvl3">Project Name:</div>
</td>
<td>
<input type="text" name="prjname" maxlength="250">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" name="prjsubmitname">
<input type="button" value="Cancel" onclick="$('#popupoverlay').hide(); $('#prjpopupbox').hide(); $('#prjname').hide(); $('#prjdescription').hide(); $('#prjversion').hide(); $('#prjrelease').hide();">
</td>
</tr>
This is my table for editing a project name- what is important here is the textbox input, I think.
Next I have my PHP:
//Did the user change the Project Name
if (isset($_POST['prjsubmitname']))
{
//Is the input empty
if (!trim($_POST['prjname']))
{
//Input is empty
echo('<script>senderror("Please enter a valid Project Name empty");</script>');
} else {
//Input isnt empty, assign variables
$url = geturlext();
$prjname = mysql_real_escape_string(trim($_POST['prjname']));
//Is input invalid
if (strcasecmp($prjname, "main") == 0 | $prjname == "404")
{
//Input is invalid
echo('<script>senderror("Please enter a valid Project Name invalid");</script>');
} else {
//Input is valid, connect to database
dbconnect();
$checkquery = mysql_query("SELECT * FROM projects WHERE name = '$prjname'") or die(mysql_error());
$check = mysql_num_rows($checkquery);
//Does Project Name already exist
if ($check == 0)
{
//No it does not
$updatequery = mysql_query("UPDATE projects SET name = '$prjname' WHERE name = '$url'") or die(mysql_error());
echo("<script>location.href='index.php?page=" . $prjname . "'</script>");
} else {
//Yes it does
echo('<script>senderror("That Project Name already exists");</script>');
}
}
}
}
This is where I get my issue; No matter what I enter in the textbox, I always get the error message for 'Input is empty'. I have printed the output of $_POST['prjname'] and it is indeed empty.
Now the weird part is, I have this exact same (at least I think) setup for changing the project description, and it works flawlessly. For the sake of comparison- i've included the same parts of the project description editor below.
The table:
<table border="0" align="center">
<tr>
<td>
<div id="lvl3">Project Description:</div>
</td>
<td>
<textarea type="text" name="prjdescription" maxlength="750" style="width:300px; height:100px; resize:none;"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" name="prjsubmitdescription">
<input type="button" value="Cancel" onclick="$('#popupoverlay').hide(); $('#prjpopupbox').hide(); $('#prjname').hide(); $('#prjdescription').hide(); $('#prjversion').hide(); $('#prjrelease').hide();">
</td>
</tr>
And the PHP:
//Did the user change the Project Description
if (isset($_POST['prjsubmitdescription']))
{
//Is the input empty
if (!trim($_POST['prjdescription']))
{
//Input is empty
echo('<script>senderror("Please enter a valid Project Description");</script>');
} else {
//Input isnt empty, do stuff
$url = geturlext();
$prjdescription = mysql_real_escape_string(trim($_POST['prjdescription']));
//Connect and change description
dbconnect();
$updatequery = mysql_query("UPDATE projects SET description = '$prjdescription' WHERE name = '$url'") or die(mysql_error());
echo("<script>location.href='index.php?page=" . $url . "'</script>");
}
}
For clarification, both tables are in the same form tag, and the PHP is right next to eachother.
No errors on Firebug, matter of fact Firebug doesn't give me anything. Other than that, I'm sure it's some really small typo that I am overlooking.
I have found a solution to this issue:
Renaming the variable '$prjname' in the Project Name editing PHP fixes the issue.
It would seem that having a variable ($prjname) with the same name as a $_POST (['prjname']) returns an empty or null string. No idea why.
Thanks to those who tried to help
EDIT: Actually, I get the error again if I only change the variable name ($prjname)- It only fixes when I change the $_POST name... Odd.
Looking at the description of above issue, we can conclude that form elements must be encapsulated within form tag ,then only form data will be posted to server.
So as a solution to your problem, you need to define input elements within form tag.