I am trying to make a site which users can upload phrases. Basically there is a text field and then it gets uploaded to the mysql database. Here is what I have tried so far.
HTML::
<form class="form-horizontal" action="drop.php" method="post">
<fieldset>
<!-- Form Name -->
<legend>Submit a Billboard</legend>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="textinput">What will your Billboard Say?</label>
<div class="controls">
<input name="text" type="text" placeholder="What you going to say?" class="input-xlarge">
</div>
</div>
<br>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button id="singlebutton" name="singlebutton" class="btn btn-primary">Drop Your Billboard</button>
</div>
</div>
</fieldset>
</form>
PHP::
<?php
//Connecting to sql db.
$connect = mysqli_connect("localhost","mod","","bill");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')
?>
Besides your SQL injection, your button doesn't do anything really, not without any JS which if you're using, you haven't shown it. Therefore, this answer is based on what you posted
It would require an type="submit" in order for your button to fire up anything.
I'm taking a blind stab at this, but I'm prrrrretty sure that's what's "not" going on here.
Plus and more importantly (and not a blind stab), you're missing a closing bracket, a quote and semi-colon in: (a major syntax error)
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')
^^^ missing bracket/quote/semi-colon
so do
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')");
^^^ missing/added
Escape your data:
if(!empty($_POST['text'])){
$text = mysqli_real_escape_string($connect, $_POST['text']);
mysqli_query($connect,"INSERT INTO submit (submission) VALUES ('".$text."')");
}
However, you really should use a prepared statement for that SQL injection:
https://en.wikipedia.org/wiki/Prepared_statement
Check for errors.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
If your entire code is inside the same page, you will receive undefined index notice.
Error reporting will tell you that.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
As well as or die(mysqli_error($connect)) to mysqli_query().
If so, then you will need to use !empty() for the POST array.
http://php.net/manual/en/function.empty.php
You could have also used:
$connect = mysqli_connect("localhost","mod","","bill")
or die(mysqli_error($connect)); // check if successful or not
if(!empty($_POST['text'])){
$text = mysqli_real_escape_string($connect, $_POST['text']);
$query = "INSERT INTO submit (submission) VALUES ('".$text."')";
$result = mysqli_query($connect, $query);
if (!$result)
{
throw new Exception(mysqli_error($connect));
}
else{ echo "Success."; }
}
You can try isset() function to insert the input into your database.
if(isset($_POST['singlebutton']))
{
$text= $_POST['text'];
$query= $connect->prepare ( "INSERT INTO submit(submission) VALUES (?)");
$query -> bind_param("s",$text );
if ($query->execute())
{
echo"<center><strong>Text added! </strong></center>";
} // display when text is added
else{
echo"Error in adding text!"; // display when there is error
}
}
Related
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'm trying to validate the user input and query to delete the record which have the same name. I'm using phpStorm for coding
I have tried to go over the typo, format of the code and check the query in phpAdmin and it's working fine
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 3/24/2019
* Time: 4:38 PM
*/
// Include config file
require_once "config.php";
$product_name= '';
$product_name_err = '';
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty(trim($_POST["product_name"]))){
$product_name_err = "Please enter the product name.";
} else{
$product_name = trim($_POST["product_name"]);
}
//Delete the data in the product table
$sql = "DELETE FROM `products` WHERE `name` = '$product_name'";
if ($product_name_err =''){
mysqli_query($link,$sql);
}
}
?>
<?php include "header_admin.php"?>
<div class="wrapper">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group" <?php echo (!empty($product_name_err)) ? 'has-error' : ''; ?>>
<label>Product name</label>
<input type="text" name="product_name" class="form-control" >
<span class="help-block"><?php echo $product_name_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Delete Item">
</div>
</form>
</div>
<?php include "footer.php"?>
I expect the preceding code to check if the field is blank and the query delete that matched record on the database but either of them seem to work properly. The $product_name seem not received any value at all.
The below code should work correctly. There was a typo in your confition: if ($product_name_err =''){ should be if ($product_name_err ==''){
Also, your code was vunerable to injection attacks, which is fixed below by using the mysqli_escape_string function.
if($_SERVER["REQUEST_METHOD"] == "POST") {
$product_name = mysqli_escape_string($link, trim($_POST["product_name"]));
if(empty($input)){
$product_name_err = "Please enter the product name.";
}
//Delete the data in the product table
$sql = "DELETE FROM `products` WHERE `name` = '$product_name'";
if($product_name_err == ''){
mysqli_query($link,$sql);
}
}
Your if condition is incorrect, use '==' instead of '='.
if ($product_name_err ==''){
mysqli_query($link,$sql);
}
also you should really consider using prepared statements to prevent sql injection attacks and it does other nice things for you like you not having to escape ' or " characters from your strings.
More info on prepared statements
Php code check will help to check your PHP code. May be it will help you.
#PHP Code Checker
An advanced, custom PHP code checker that searches your code for common, hard to find typos and mistakes; includes a syntax check.
This has consumed my Saturday. Please help.
I have a large form that I need to update a record in a MySQL database table hosted on a GoDaddy shared account. There are 18 records I'm trying to update when the form is submitted, but so far I've only gotten 17 to do so. The 2nd to last field, "blackTowellCount", causes problems when I include it in the UPDATE statement.
If I exclude the field in question from the SQL statement, ALL 18 fields successfully POST the data to the PHP file and the 17 listed in the SQL statement upload just fine. When I include the blackTowellCount field, the UPDATE stops working and the form no longer POSTS the data to the PHP form. WTF?!
You'll also notice that there's a nearly identical field, "whiteTowellCount" that updates just fine.
portion of the form:
<div class="well">
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-2">
<label for="blackTowellCount" class="pull-right">Black Towells</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" id="blackTowellCount" name="blackTowellCount" placeholder="black towell #"/>
</div>
<div class="col-md-2">
<label for="whiteTowellCount" class="pull-right">White Towells</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" id="whiteTowellCount" name="whiteTowellCount" placeholder="white towell #"/>
</div>
<div class="col-md-1">
</div>
</div>
</div>
Functional SQL:
$addIntakeSQL = mysqli_query($link,"UPDATE Act SET w9FilePath='".$w9Upload_destination."', riderFilePath='".$riderUpload_destination."', hospRiderFilePath='".$hospRiderUpload_destination."', inputFilePath='".$inputListUpload_destination."', stageFilePath='".$stagePlotUpload_destination."', backlineFilePath='".$backlineUpload_destination."', bathTowellCount='".$bathTowellCount."', breakfastCount='".$breakfastCount."', lunchCount='".$lunchCount."', dinnerCount='".$dinnerCount."', breakfastRestriction='".$breakfastRestriction."', lunchRestriction='".$lunchRestriction."', dinnerRestriction='".$dinnerRestriction."', arrivalDate='".$arrivalDate."', arrivalTime='".$arrivalTime."', needTransport='".$needTransport."', whiteTowellCount='".$whiteTowellCount."' WHERE actID='".$actID."'") or die (mysqli_error());
Broken SQL:
$addIntakeSQL = mysqli_query($link,"UPDATE Act SET w9FilePath='".$w9Upload_destination."', riderFilePath='".$riderUpload_destination."', hospRiderFilePath='".$hospRiderUpload_destination."', inputFilePath='".$inputListUpload_destination."', stageFilePath='".$stagePlotUpload_destination."', backlineFilePath='".$backlineUpload_destination."', bathTowellCount='".$bathTowellCount."', breakfastCount='".$breakfastCount."', lunchCount='".$lunchCount."', dinnerCount='".$dinnerCount."', breakfastRestriction='".$breakfastRestriction."', lunchRestriction='".$lunchRestriction."', dinnerRestriction='".$dinnerRestriction."', arrivalDate='".$arrivalDate."', arrivalTime='".$arrivalTime."', needTransport='".$needTransport."', blackTowellCount='".$blackTowellCount."', whiteTowellCount='".$whiteTowellCount."' WHERE actID='".$actID."'") or die (mysqli_error());
portion of .PHP file:
$bathTowellCount = $_POST['bathTowellCount'];
$breakfastCount = $_POST['breakfastCount'];
$lunchCount = $_POST['lunchCount'];
$dinnerCount = $_POST['dinnerCount'];
$breakfastRestriction = $_POST['breakfastRestriction'];
$lunchRestriction = $_POST['lunchRestriction'];
$dinnerRestriction = $_POST['dinnerRestriction'];
$arrivalDate = $_POST['arrivalDate'];
$arrivalTime = $_POST['arrivalTime'];
$needTransport = $_POST['needTransport'];
$blackTowellCount = $_POST['blackTowellCount'];
$whiteTowellCount = $_POST['whiteTowellCount'];
$addIntakeSQL = mysqli_query($link,"UPDATE Act SET w9FilePath='".$w9Upload_destination."', riderFilePath='".$riderUpload_destination."', hospRiderFilePath='".$hospRiderUpload_destination."', inputFilePath='".$inputListUpload_destination."', stageFilePath='".$stagePlotUpload_destination."', backlineFilePath='".$backlineUpload_destination."', bathTowellCount='".$bathTowellCount."', breakfastCount='".$breakfastCount."', lunchCount='".$lunchCount."', dinnerCount='".$dinnerCount."', breakfastRestriction='".$breakfastRestriction."', lunchRestriction='".$lunchRestriction."', dinnerRestriction='".$dinnerRestriction."', arrivalDate='".$arrivalDate."', arrivalTime='".$arrivalTime."', needTransport='".$needTransport."', whiteTowellCount='".$whiteTowellCount."' WHERE actID='".$actID."'") or die (mysqli_error());
}
Hi First of all as all suggested your code is open to SQL injections, Use PDO instead . Second php has its functions to display errors include them if you got nothig to do.
add these lines at top of your page
error_reporting(E_ALL);
ini_set('display_errors',1);
also you have not given mysqli_error() its parameter
Replace die(mysqli_error()); with die(mysqli_error($link));
There was a space in front of "blackTowellCount" in the database. I hate programming.
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
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.