I am writing a PHP script to take the contents of a variable and insert it into my MYSQL database, it works well when I define the values, but using variables just gives a error, can any one tell me the correct way to save form input to a variable. (the form is in the same file as the sql script excluding the logins, so using $_POST doesn't work)
mysqli_query($connect,"INSERT INTO news (news)
VALUES ('$email')");
if(mysqli_affected_rows($connect) > 0){
echo $good;
else
echo $bad
}
form:
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s6">
<input placeholder="Placeholder" id="email" type="text"
<label for="news">news</label>
</div>
You're asking for a lot of issues with that script. Lets walk through all of them:
1) Setting form attributes
It is important to tell the browser how to send the form data to your server. Otherwise you'll end up having to rely on the superglobal $_REQUEST. As quoted from the official PHP website:
The variables in $_REQUEST are provided to the script via the GET,
POST, and COOKIE input mechanisms and therefore could be modified by
the remote user and cannot be trusted.
So instead you should add the method attribute to your form. You might want to add character encoding as well, just to be sure your script won't get confused when someone uses non utf-8 characters:
<form method="POST" action="" accept-charset="utf-8">
2) A way to access your POST data
To be able to actually do something with POST data, you need a way to access it. This is where the name attribute comes into play:
<input placeholder="Placeholder" id="email" type="text" name="email" />
The superglobal $_POST will now be able to access the value of that input field using the name attributes value as a key: $_POST['email']. This will only work after the form is sent though.
3) Submit your form
You cannot magicly expect your server to have all the form data filled in by your website visitor. You need to submit it first:
<input type="submit" value="Register email" />
This will become a button with the text you've setup in the value attribute. When the visitor clicks on it, your form data will be submit to your server.
So your entire form should look like this:
<form method="POST" action="" accept-charset="utf-8">
<input placeholder="Placeholder" id="email" type="text" name="email" />
<input type="submit" value="Register email" />
</form>
4) Setting up PHP
Before we start working with the POST data, we need to be sure the user is giving us data:
if(isset($_POST['email']) && !empty($_POST['email'])){
//...
}
This will verify that $_POST['email'] exists and also makes sure it isn't empty.
5) Securely handling user data: Prepared Statements
One of the first things you learn as a developer is to never ever trust user data. Inputting data into a database submitted by a user without verifying it, is asking for a lot of trouble. Especially SQL Injection.
Using MySQLi Prepared Statements, you can protect yourself against this:
//$link will be the connection to your database
//For example: $link = mysqli_connect("localhost", "db_user", "db_pass", "db_name");
if ($stmt = mysqli_prepare($link, "INSERT INTO news (news) VALUES (?)")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $_POST['email']);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
/* print success message */
echo "Email successfull registered!";
} else {
/* print errors */
printf("MySQL Error: %s\n", mysqli_error($link));
}
Wrapping it all together:
<?php
if(isset($_POST['email']) && !empty($_POST['email'])){
//$link will be the connection to your database
//For example: $link = mysqli_connect("localhost", "db_user", "db_pass", "db_name");
if ($stmt = mysqli_prepare($link, "INSERT INTO news (news) VALUES (?)")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $_POST['email']);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
/* print success message */
echo "Email successfull registered!";
} else {
/* print errors */
printf("MySQL Error: %s\n", mysqli_error($link));
}
}
?>
<!-- Your HTML here -->
<div class="row">
<form class="col s12" method="POST" action="" accept-charset="utf-8">
<div class="row">
<div class="input-field col s6">
<input placeholder="Placeholder" id="email" type="text" name="email" />
<input type="submit" value="Register email" />
</div>
</div>
</form>
</div>
<!-- Your HTML here -->
Give your input a name
<input placeholder="Placeholder" id="email" name="email" type="text">
and get the value in php with
$email = $_REQUEST['email']; //to get both GET and POST methods.
then use the $email in your query
Related
i'm brazilian i does a website simple to sent a simple users data, but to do a test i want sent manually newer data in a link without need complete manual form if it run then i can use directly by my app to save all users data.
see my idea:
mywebsite.com/savedata?method=post&usernamesave=Nome&Misael&userxp=34&userid=35&userlevel=31&usermail=crod%40gmail.com&userprog1=1&userprog2=2&userprog3=23&userprog4=25&userprog5=25&userprog6=25&userprog7=100&userprog8=100&proceed=
if i can change this data from my app and using hrefs i can do this and save a simple data without a complex data connection, it's possible ?
<a href="mywebsite.com/simplepost?method=post&joao&6y"> << type of exeple.
But when i use this and press enterkey the data isn't saved into a textfile, why ?
i using this in php :
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/*Php 5.6.2 Code By : Michael S. author*/
//globais
$username = $_POST['usernamesave'];
$userxp = $_POST['userxp'];
$userid = $_POST['userid'];
}
If i got you right you want to save data using a post method. If this is what you want to accomplish, then you don't have to pass the variables in URL. This is the main difference between POST and GET method.
Now for data saving, i will assume that you all ready created a database and a table to save your information on it, so let's jump to the form and how to handle them.
<?php
/*
* First form one will be the POST method.
*/
if(isset($_POST)){
echo "post method where used from a form to send this variables";
var_dump($_POST);
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username: </label>
<input type="text" name= "username">
<label for="age">Age: </label>
<input type="number" name="age"/>
<input type="submit" value="Submit">
</form>
When you click on submit the information will be sent and can be handled after.
In get method it's different you will see the variables inside the URL after hitting submit, and the same way you can send data to other pages.
<?php
/*
* Second form one will be the GET method
* Check the url.
*/
if(isset($_GET)){
echo "get method where made from a form with this variables";
var_dump($_GET);
}
?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username: </label>
<input type="text" name= "username">
<label for="age">Age: </label>
<input type="number" name="age"/>
<input type="submit" value="Submit">
</form>
Now in the url you should see something like
example.com/index.php?username=WaredNsour&age=24
I believe you are using the GET method to send information but in your PHP code, you are using the POST method to fetch them.
Try this :
if ($_SERVER["REQUEST_METHOD"] == "GET") {
/*Php 5.6.2 Code By : Michael S. author*/
//globais
$username = $_GET['usernamesave'];
$userxp = $_GET['userxp'];
$userid = $_GET['userid'];
}
In the code of your page that is processing the variables being sent, try the following (temporarily) as a test to see if variables are being sent/seen. If they are, they will be printed out.
<p>Post vars:
<?php var_dump($_POST) ?>
</p>
If nothing displays, try:
<p>Request vars:
<?php var_dump($_REQUEST) ?>
</p>
Note: in the url you posted you have: &Misael& if Misael is part of the username you should not use the & in front of it. http sees &s as separators for the variables. It will see Misael as a variable name, like: ...&Misael=something&.... If it is a space, use %20.
I am trying to redirect a to a new php page after the user has clicked on the submit button. I have got it to successfully send the form information to the MySQL database but then I cannot get a successful redirect.
I then changed some code and got it to successfully redirect but not send the form information to the database. My other php file is named nextForm.php and I have tried replacing the action="$_SERVER[PHP_SELF]" with the path to the nextForm.php file and I have tried using a require nextForm.php; line in the code where I want to redirect.
Here is the code I have currently:
<?php
//establish a connection to the MySQL db or terminate if ther is an error
$conn = mysqli_connect("localhost","root","mysql","covid_tech",3306) or die(mysqli_connect_error());
//HTML form to prompt user input
print <<<_HTML_
<FORM style="text-align:center" method="POST" action="$_SERVER[PHP_SELF]">
<div class="Customer_Name">
Enter Customer Name: <input type="text" name="Customer_Name" class="textbox">
</div>
<br/>
<div class="Contact_Name">
Enter Contact Name: <input type="text" name="Contact_Name" class="textbox">
</div>
<br/>
<div class="Contact_Phone">
Enter Contact Phone Number: <input type="text" name="Contact_Number" class="textbox">
<br/>
</div>
<button class="btn btn-1" style="text-align:center" onclick='disappear(this)' name="name_submit" method="POST" type="submit" value="find_cusName"><span>Enter Customer Name</span></button>
</FORM>
_HTML_;
//check to make sure the POST request was sent and check to make sure that there is a vlaue in the System POST variable
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['Customer_Name'])){
//SQL string to find the name that was input on the page
$find_name_sql = "SELECT cusName,cusID from customer where cusName = '$_POST[Customer_Name]'";
//run the query on the db
$result_find_name = mysqli_query($conn, $find_name_sql);
//Check to see if the query returned any rows
if(mysqli_num_rows($result_find_name) > 0){
//If it did, it should only be 1 row and we fetch it
$row = mysqli_fetch_row($result_find_name);
//set our current_id variable to the value in $row[1] which is the cusID attribute from the db
$current_id = $row[1];
}
else{
//sql statment to insert a new customer into the customer table of the db
$insert_first_customer = "INSERT INTO customer (cusName,contactName,contactNo) values('$_POST[Customer_Name]','$_POST[Contact_Name]','$_POST[Contact_Number]')";
//run the insert query
$add = mysqli_query($conn,$insert_first_customer);
}
//redirect to next form page here
}
mysqli_close($conn);
?>
The action attribute simply works as a way to direct your GET/POST requests. If you would like to redirect after running your PHP code, you should use the header() function or use a meta tag.
Example:
header('Location:'.$_SERVER['SERVER_NAME'].'/nextForm.php');
or
echo '<meta http-equiv="refresh" content="0;url=nextForm.php">';
and finish your code with the exit() function so an attacker could not bypass your redirect.
I want to send user entered form data to mysql via php using get.
<form action="formtosql.php" method="get">
<div class="row">
<div class="form-group col-md-4">
<label for="001">Student name:</label>
<input type="text" class="form-control" id="001" name="sname">
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="002">Status:</label>
<input type="text" class="form-control" id="002" name="sstatus">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
php code looks like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$name = $_GET['sname'];
$stat = $_GET['sstatus'];
// Connecting to the Database
$servername = "localhost";
$username = "root";
$password = "";
$database = "exam";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Die if connection was not successful
if (!$conn){
die("Sorry we failed to connect: ". mysqli_connect_error());
}
else{
$sql = "INSERT INTO `estatus` (`name`, `status`, `date`) VALUES ('$name', '$stat', current_timestamp())";
$result = mysqli_query($conn, $sql);
?>
In php im getting an error while using get:
Notice: Undefined index: sname in C:\xampp\htdocs\helloworld\formtosql.php
Notice: Undefined index: sstatus in C:\xampp\htdocs\helloworld\formtosql.php
This error does not occur if I am using Post.
I am assuming that you have both the generation of the form, and the processing of the submitted value, in the same script here?
This error does not occur if I am using Post.
You checked the REQUEST_METHOD to determine if you are dealing with the case, that the form was submitted.
When you use method="post" on your form, you can do that - the initial request that loaded the page containing the form was used making the GET method, submitting it will use POST - so these two cases can be distinguished between using that method.
But if you use method="get", then both requests - the one used to initialy load the page, and the one used to submit the form data - are of the same method, and therefor you can not use that any more, to differentiate between the two cases.
If you give your submit button a name, then you could check (using isset/empty), whether the corresponding parameter exists - and use that to determine, which of the two cases you are dealing with.
But as already mentioned in comments - for requests that create data on the server side, you should generally use POST, not GET. Under When do you use POST and when do you use GET? you can find a more in-depth explanation of that.
I know its a duplicate one but i'm getting this error while trying to fetch data passed from a link..I dont know how to resolve it.
here is my code:
add_package.php
echo "<td><a href='delete.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Delete</a></td>";
echo "<td><a href='edit_package.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Update</a></td>";
here the delete link works perfectly but when i click update it takes to the edit_package page where i'm getting an undefined error..
code for edit_package.php:
<?php
include('db.php');
$id4 = $_GET['id3'];//update the page
$name4 = $_GET['name3'];//helps to update the package
echo $id4;
echo $name4;//getting values here correctly..
if(isset($_POST['submit']) )
{
$package=$_POST['package'];
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
$retvali=mysql_query($sql13,$conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
$retval = mysql_query( $sql, $conn );
?><script>alert("Updated Successsfully");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
else
{
?><script>alert("Already Exists");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
}
else
{
?><script>alert("enter only letters and numbers")</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<form id="form-validation" action="edit_package.php" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
<div class="col-md-6">
<div class="block" style="height:500px;">
<div class="block-title">
<h2><strong>State the Package For Tour</strong></h2>
</div>
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="val_username">Update Package <span class="text-danger">*</span></label>
<div class="col-md-6">
<div class="input-group">
<input type="text" id="package" name="package" class="form-control" required >
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
</div>
<div class="form-group form-actions">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</div>
</div>
</fieldset>
</form>
When i press update button i'm getting an undefined error i dont know why?..Thanks in advance
I'm attaching an image to it..
Try to change the <form>'s action URL to include your GET varaibles:
<form id="form-validation" action="edit_package.php?id3=<?php echo $_GET['id3']; ?>&name3=<?php echo $_GET['name3']; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
PLEASE NOTE: This is extremely unsafe! You need to sanitize ALL user input before using it. My example above, dis-regards security, and simply is to demonstrate my point. GET and POST data, are user variables. A malicious user could put bad code in the URL (ie ?name3=<badcode>) and it would be printed on the page, well in the source code, which they could easily pop out of. Also, in SQL queries, you need to escape the data or use prepared statements.
You should not be using mysql functions, switch to MySQLi or PDO. MySQL has been killed for a while now..
These are just asking for you to get hacked:
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
and..
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
You are vulnerable to SQL injections, would could easily allow a malicious attacker to add/edit/view/delete data in your database.
The problem is, you have $package (which is raw data from POST) and $id4 and $name4 (which is raw data from GET) in your SQL query.
You would use mysql_real_escape_string() on them, but you should be using mysqli or PDO anyways...
Example:
$name4 = mysql_real_escape_string($_GET['name3']);
It's confusing, I don't know what the GET variable is called name3 but you assign it the variable $name4.. Whoever (even you) comes along later on will be lost in your code.
Updated:
Try this code. I swapped your GET for POST in your php code, and passed the GET variables from your URL as hidden fields in your form.
<?php
include('db.php');
if(isset($_POST['submit']) )
{
$package = mysql_real_escape_string($_POST['package']);
$id4 = mysql_real_escape_string($_POST['id3']); // why is variable named id4 but its id3??
$name4 = mysql_real_escape_string($_POST['name3']); // why is variable $name4 but its name3??
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13 = "SELECT package_type,id FROM tbl_package WHERE package_type='$package' LIMIT 1";
$retvali = mysql_query($sql13, $conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='$package' WHERE package_type = '$name4' AND p_id='$id4'";
$retval = mysql_query( $sql, $conn );
echo '<script>alert("Updated Successsfully");window.location = "http://localhost/demo/add_package.php";</script>';
} else {
echo '<script>alert("Already Exists"); window.location = "http://localhost/demo/add_package.php";</script>';
}
} else {
echo '<script>alert("enter only letters and numbers");</script>';
}
}
?>
<form action="edit_package.php" method="post" enctype="multipart/form-data" novalidate="novalidate">
<input type="hidden" name="id3" value="<?php echo htmlspecialchars($_GET['id3'], ENT_QUOTES | ENT_HTML5); ?>" />
<input type="hidden" name="name3" value="<?php echo htmlspecialchars($_GET['name3'], ENT_QUOTES | ENT_HTML5); ?>" />
Update Package: <input type="text" id="package" name="package" class="form-control" required >
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</form>
I removed your HTML formatting from the form. You had div tags that didn't match up.. I can't see your whole code, but it looks like you have a bunch of div's that are messed up (ie: not closed where they should be). I also added mysql_real_escape_string() to the passed variables, and htmlspecialchars() to the GET variables echo'd in the hidden fields of your form. It's a start.
You might be able to make better sense of your code and troubleshoot errors, if you wrote your code a bit cleaner. Not trying to bash you :) Proper indentation, spacing, and formatting go a long way. It makes it easier on your eyes, and on yourself, in times like these..
I left your <script> tags because I assumed there was a reason your wanted to popup a message box.. I would just use header('Location: /path/to/where.php'); and pass your error message through a session variable or something, like an array of errors, which you get, clear, and show on the page the errors.
I want to submit this form through PHP. with validation for required field and validation for phone number and email field also
<form action="" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_LastName">
Last Name</label>
<input id="txt_LastName" type="text" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_Phone">
Phone</label>
<input id="txt_Phone" type="text" title="First Name. This is a required field" />
</div>
<div class="row requiredRow">
<label for="txt_Email">
Email</label>
<input id="txt_Email" type="text" class="required" title="Email. This is a required field" />
</div>
<div class="row">
<input type="submit" value="" class="button" />
</div>
</form>
In your method attribute inside your form, you need to declare either post or get.
Since your action attribute is "" it will submit to the page itself rather than redirecting to another page, so you can have your code that checks for validation in the same PHP file. First validation that is often checked is if the variable has a value by using isset:
if(isset($_POST['txt_Phone'])) { ... }
This just checks that the Phone number field does not contain empty data. I strongly suggest you perform other validation checks on the POST array so you do not have any users posting malicious code.
You can use functions like htmlspecialchars to prevent user-supplied text depending on what you plan to do with the values
Here are some references to help you along the way in the order they should be viewed.
Form Validation using PHP - PHP and MySQL Tutorial
PHP Advance Form Validation Tutorial
PHP Tutorial Part 2: Form Validation
Your form tag needs a target in the action field and a method in the method field (either GET or POST). So make the action your PHP script.
<form name="input" action="form_submit.php" method="get">
As for field validation, you will either have to parse that inside of the PHP and return a response or use Javascript in the browser to check on the fly.
Here is the shcema of such a script:
if ($_SERVER['REQUEST_METHOD']=='POST') {
//data validation:
$err="";
if (valid_phone($_POST['phone'])) $err="Wrong phone no";
if (!$err) {
//record data:
$sql="...";
query($sql);
Header("Location: ".$_SERVER['REQUEST_URI']); //redirect and exit
exit;
}
}
?>
<html>
<head></head>
<body>
<? if ($err) ?> <font color=red><b><?=$err?></b></font>
<form method="POST" id="get-protected">
here goes your form
Okay, firstly, I like to set the form action to <?=$_SERVER['REQUEST_URI']?> to submit it back to the current page, but leaving it as you have it will work fine too.
Secondly, you need to give all your <input>s a name attribute. This is the variable name that PHP will see.
When your users get an error (something doesn't validate correctly) you don't want all the data they entered to disappear. That means you have to set the value attributes of each input to what they had previously entered. Thus, your form starts to look like this:
<form action="<?=$_SERVER['REQUEST_URI']?>" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" name="first_name" value="<?=htmlspecialchars($_POST['first_name'])?>" />
</div>
...
<div class="row">
<input type="submit" name="submit" value="" class="button" />
</div>
</form>
If you didn't know <?= is a basically a shortcut for <?php echo but it will only work if your server has short tags enabled. Some people prefer to type it out the long way (in case they want to switch servers later, or for future-compatibility, or because they're nutbars), but I say screw them, I'm lazy.
This page that has the form on it, has to saved with a .php extension (well, technically it doesn't have to, but that's another story). Then you need to handle you form validation. You have to code that up yourself. It might look something like this (put it above your form somewhere)
<?php
if($_POST['submit']) {
$errors = array()
if(empty($_POST['first_name'])) $errors[] = 'please enter your first name';
if(empty($errors)) {
// save the data to database or do whatever you want with it
header('redirect:succcess.php');
} else {
foreach($errors as $e) {
echo $e;
}
}
}
?>
It's been a while since I've coded in PHP so forgive me if there are syntax errors. That's the jist of it anyway, I'm sure you can find validation libraries out there if you Google. Might take some of the grunt work out of trying to validate email addresses and such.
Using Javascript you can do the validation for this form.For each condition you can use return true and return false,based on the condition.Then you can submit the value.
Using action attribute in form tag the values will be submitted to that file.