Simple HTML form not adding value into MySQL table - php

The form below is not adding points to the fourth field in the MySQL table "contest."
I can't find anything wrong with the code. Am I missing something obvious?
echo '<form action="http://www.website.com/folder/file.php" method="post">
<input type="hidden" value="'.$u.'" name="u">
<input type="hidden" value="'.$profile.'" name="profile">
<input type="hidden" value="'.$profileid.'" name="profileid">
<div class="friend2title"><label for="url">Add points:</label></div>
<div class="friend2field"><input name="state" type="text" id="state" maxlength="150"></div>
<div class="addresssubmit"><input name="submit" type="submit" value="Add"></div>
</form>
';
Then, on http://www.website.com/folder/file.php:
$u = $_POST['u'];
$profile = $_POST['profile'];
$profileid = $_POST['profileid'];
$state = $_POST['state'];
$state = mysql_real_escape_string($state);
mysql_query("INSERT INTO contest VALUES (NULL, 'critic', '$profileid', '$state', NULL')");

You have to declare the value attribute with the default value in your state input
<input name="state" type="text" id="state" value="' . $state . '" maxlength="150">
Additionaly, your code is vulnerable to SQL Injection, never trust in fields that came from users, it is very dangerous for your database.

Related

Problem: Part of the PHP exercise does not run correctly

I created a section for editing. When I edit the information and click the save button, the information is not saved and the header section does not display completely.
<?php
if (isset($_POST['submit_btn']))
{
$id = $_POST['id'];
$fn = trim($_POST['name']);
$ln = trim($_POST['lastname']);
$age = trim($_POST['age']);
$q = "UPDATE `users` SET `fn` = '$fn',
`ln` = '$ln',
`age` = '$age'
WHERE id = '$id'";
mysqli_query($dbconnect,$q);
if (mysqli_affected_rows($dbconnect) > 0)
redirect("?msg=ok&id=**$id**");
else
redirect("?msg=error&id=**$id**");
}
else
echo ("Not In If(isset)");
?>
<form action="" method="post">
<label for="name">FirstName:</label>
<input type="text" name="name" id="name" value="<?php echo $row['fn']?>">
<br>
<label for="lastname">LastName:</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $row['ln']?>">
<br>
<label for="age">Age:</label>
<input type="text" name="age" id="age" value="<?php echo $row['age']?>">
<br>
<input type="submit" name="submit_btn" value="Save">
<a href="index2.php">
Back
</a>
</form>
</body>
Bold sections do not work here.
Below is a picture of the result:
In the link that I specified, after clicking on save the ID will not be displayed and all the information filled in the forms will be lost.
Sorry if the result is styleless and boring and I just created this page to practice php😁
Thank you for being responsive🙏🙏🙏
You are mistaking a POST request with a GET request.
Part, which appears in the URL is sent to the webserver in GET request.
Your form is submitting POST request to the webserver, logic in the code does the same, but you are trying to display information from url (GET).
Please check the examples in php.net:
POST variables: https://www.php.net/manual/en/reserved.variables.post.php
GET variables: https://www.php.net/manual/en/reserved.variables.get.php
You can take an example with GET request variable below, however, be careful with trusting the "end client" and always prepare your statements, which you send to your database to execute queries.
if (isset($_GET['submit']))
{
$number = $_GET['number'];
echo $number
? "Number which was submitted: $number <br>"
: 'Number is not set';
} else {
echo 'Form has not been yet submitted';
}
?>
<form action="" method="get">
<input type="number" name="number" placeholder="Number">
<input type="submit" name="submit" value="Save">
</form>

How to read post values easier in PHP

I am posting a values from a HTML form to a php file. In my current code I am submitting several post values and have to do a check for each post variable if they are set.
I'd like to know if there is a more effective way of doing this. One requirement is that the values will be inserted in order.
HTML form:
<form>
<input type=text name=exercise1> <input type=text name=sets1>
<input type=text name=exercise2> <input type=text name=sets2>
<input type=text name=exercise3> <input type=text name=sets3>
<input type=text name=exercise4> <input type=text name=sets4>
...
</form>
SQL table:
id autoincrement
exercise varchar(200)
sets varchar(10)
I tried the next code:
$exercise1 = $_POST['exercise1'];
$sets1 = $_POST['sets1'];
$exercise2 = $_POST['exercise2'];
if(isset($exercise1)){
$sql = "insert into exercises (exercise, sets) values ($exercise1, $sets1)";
execute_sql($sql);
}
if(isset($exercise2)){
$sql = "insert into exercises (exercise, sets) values ($exercise2, $sets2)";
execute_sql($sql);
}
Default form method is GET, so you are probably not getting anything while trying to read $_POST. To fix it, you need to change this:
<form>
to this:
<form method="post">
To make it easier, you should redefine your form, so it would be an array:
<input type="text" name="exercise[]"> <input type="text" name="sets[]">
<input type="text" name="exercise[]"> <input type="text" name="sets[]">
<input type="text" name="exercise[]"> <input type="text" name="sets[]">
<input type="text" name="exercise[]"> <input type="text" name="sets[]">
That will keep an order as in code. Some browsers are not sending empty values, so it would be better to manually order them (so you would know, if there was no answer or whatever):
<input type="text" name="exercise[1]"> <input type="text" name="sets[1]">
<input type="text" name="exercise[2]"> <input type="text" name="sets[2]">
<input type="text" name="exercise[3]"> <input type="text" name="sets[3]">
<input type="text" name="exercise[4]"> <input type="text" name="sets[4]">
Now you can iterate through it in PHP like this:
<?php
foreach($_POST["exercise"] as $id => $exercise){
echo "EXERCISE $id: " . $exercise . ", SETS $id: " . $_POST["sets"][$id] . "<br />";
}
?>
Please note, that your SQL query is probably vulnerable to injection attacks!
Instead of raw query, you should use something like mysqli_real_escape_string() (or similar; depends what lib are you using to connect to database):
<?php
$sql = "insert into exercises (exercise, sets) values (" . mysqli_real_escape_string($exercise) . "," . mysqli_real_escape_string($_POST["sets"][$id]) .")";
?>

I am stuck while writing MySQL query to submit the content of a form which has text & checkbox

I have a form that had text and dropdowns. Now the client wants to use checkbox instead of dropdown. How to I change the query . Here is my code:
Form is in join.php
<form name="pantryinfo" id="pantryForm" method = "post" action="email.php" data-toggle="validator" role="form">
<label>Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Pantry Name" required>
<label>Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter Street address" >
<p class="help-block"></p>
<input type="checkbox" id="snapeligible" name="snapeligible" value="Yes">SNAP Eligilble<br>
<label>Community Meal?
select class="form-control" id="communitymeal" name="communitymeal" required >
<option></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</label>
<input name="submit" type="submit" id="submit" value="Add Food Provider" class="btn btn-primary center-block">
</form>
The field SNAP Eligilble was a dropdown just like Community Meal but now is a check box.
My earlier query was as follows in email.php
require 'config/connectDB.php';
//set variables from the form
$pname = $_POST['name'];
$paddress = $_POST['address'];
$psnapeligible = $_POST['snapeligible'];
$pcommunitymeal = $_POST['communitymeal'];
$sql = "INSERT INTO temp(pan_id, pname, paddress, psanpeligible, pcommunitymeal, )
VALUES(NULL,'$pname', '$paddress', '$psnapeligible', '$pcommunitymeal',)";
I am not sure how to append the query to include data from the check box only when the checkbox is selected as its not a required field.
An unchecked checkbox will not even be found in the $_POST array. This means to see from the PHP side whether the box was checked, all you have to do is look at whether the matching variable is set.
Change:
$psnapeligible = $_POST['snapeligible'];
To:
$psnapeligible = isset($_POST['snapeligible']) ? 'yes' : 'ho';
Make an IF-Statement, where you proof if the Value of the Checkbox is set.
Is it set use this Statement
Else use the another Statement without the psnapeligible
if (isset ($psnapeligible)) {
$sql = "...";
else {
$sql = "...";
}
you can chek in your php page (email.php) if your chek box is set or not ...
if (isset($_POST['snapeligible'])) {
$psnapeligible = $_POST['snapeligible'];
}
else {
$psnapeligible = "No" ;
}

$_post does not carry the data input from an html text field

Updated
This is the whole code.
Still i do not have a value in the text field "user" but i have in all others.
I print the values before adding them to the db ( deleted it from the original code already - i have all values instead the one in the user field )
This is a testing environment.
What I have issues with, is the following:
the field "user" is a field containing text and for some reason the $_post do not contain it.
all the others variables from the number fields are carried in $_post[field_name], but not the text field.
Do you have any idea how to fix this?
I tried with using html special char, but still no results.
Thanks in advance for the help !
this is the html
<html><head><title>MySQL Table Viewer</title></head><body>
<form action="submit.php" method="POST">
Day: <input type="number" name="day"/> Month: <input type="number" name="mont"/> Year: <input type="number" name="year"/>
<br> <br>
Start Hour:<br>
<input type="number" name="shour"/>
<br>
End Hour:<br>
<input type="number" name="ehour"/>
Agent: <input type="text" name="user" value=""/>
<input type="submit" class="button" name="submit" value="submit" />
</form>
</body></html>
this is the php
<html>
<body>
<?php
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$con = mysql_connect("localhost","root","samokow");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("reservations", $con);
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user)
VALUES ('$day', '$mont','$year', '$shour','$ehour','$user')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Booking done." ;
mysql_close($con);
?>
</body>
</html>
You're quoting your $_POST[] you should do it like this:
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user) VALUES (".mysql_real_escape_string($_POST['day']).", ".mysql_real_escape_string($_POST['mont']).",".mysql_real_escape_string($_POST['year']).", ".mysql_real_escape_string($_POST['shour']).",".mysql_real_escape_string($_POST['shour']).",".mysql_real_escape_string($_POST['user'])."))";
this should work.
You don't have to qoute variables such as post in your query but instead use mysql_real_escape_string
EDIT:
Your year tag is invalid you end it with an $, and in your query you're getting shour 2 times
`Year: <input type="number" name"year"$`
Should be: Year: <input type="number" name="year">
$_POST[day]', '$_POST[mont]','$_POST[year]', '$_POST[shour]','$_POST[shour]'
shouldn't the second shour be ehour?
I hope this code is for testing purposes only?
Paste all of this in the same page!
<form method="POST">
Day: <input type="number" name="day" />
Month: <input type="number" name="mont" />
Year: <input type="number" name="year" />
Start Hour: <input type="number" name="shour" />
End Hour: <input type="number" name="ehour" />
Agent: <input type="text" name="user" />
<input type="submit" class="button" name="submit" value="submit" />
</form>
Before including the $_POST values in your database, you should use mysql_real_escape_string() Just like the others said.
ALSO, you will have to use mysqli or PDO because mysql_query() is deprecated.
if(isset($_POST['submit'])){
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$sql="INSERT INTO reservations (`day`, `mont`, `year`, `shour`, `ehour`, `user`) VALUES ('$day', '$mont','$year', '$shour','$shour','$user')";
}
I would recommend to provide a valueparameter in the input tag as well:
.... Agent: <input type="text" name="user" value="">
some browsers are picky about that (MS IE ...?)
Try this :
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user) VALUES ('$day', '$mont','$year', '$shour','$shour','$user')";
you need to put the row in quotes like this:
$_POST['user']

How to write a javascript button which contains data?

How do you create a javascript button to take the information from the form to the php sql:
<form>
<input type="text" placeholder="Name" name="name" class="name" /></br>
<input type="text" placeholder="Phone Number" name="number" class="number"/></br>
<input type="text" placeholder="Location " name="location" class="location"/></br>
<input type="submit" value="Add Booking" />
</form>
?php
$name = $_GET['name'];
$number = $_GET['number'];
$location = $_GET['location'];
$con = mysql_connect(".....",".....",".....");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
("chanh", $con);
$sql ="INSERT INTO book (name, number, location,timestamp)
VALUES ('$name', '$number','$location',NOW())";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added"
mysql_close($con);
?>
Any help would be appreciated as I am just a rookie! Thanks
You just need to specify where you form will be submitted
<form action="submit.php" method="get">
<input type="text" placeholder="Name" name="name" class="name" /></br>
<input type="text" placeholder="Phone Number" name="number" class="number"/></br>
<input type="text" placeholder="Location " name="location" class="location"/></br>
<input type="submit" value="Add Booking" />
</form>
Javascript is only needed here if you want to perform some sort of validation
NOTE
Avoid adding variables directly to your query, you will be vulnerable to SQL injection.
Here is what you can do:
$con = mysql_connect(".....",".....",".....");
$name = mysql_real_escape_string($_GET['name']);
$number = mysql_real_escape_string($_GET['number']);
$location = mysql_real_escape_string($_GET['location']);
create an , then set that when the button is clicked, the form is submitted. ie
but = document.getElementById('clickButton');
formToSubmit = document.getElementById('myForm');
but.onclick = function(){
formToSubmit.submit();
};
You don't need JavaScript to submit a form. It looks like you're just missing the < from <?php for now.
You could explicitly specify the action and method on the form HTML element, but if you don't it's a GET request and it will submit to the current URL (Web address).
Really, if you're doing something other than fetching data (like a search), your form should be using a HTTP POST, not a GET. For more understanding of why this kind of thing matters, see What should every programmer know about web development. However, that is a very big topic!
You just need to postback the form, in other words, set an action on the form as in:
<form id="mainForm" action="process.php" method="post">..
And add an onclick handler on the button as follows:
<input type="submit" value="Add Booking" onclick="javascript:document.getElementById('mainForm').submit();" />
However, not that I set the method to post; this will require your PHP code to change to:
$name = $_POST['name'];
$number = $_POST['number'];
$location = $_POST['location'];
Using POST in this case may not be necessary but you need to be aware that using GET will encode the form parameters in the URL as in process.php?name=value&numner=value... and some of this information may be sensitive and therefore, desirable to be submitted to the server in the body of the HTTP request as opposed to transmitted encoded in the URL.

Categories