I want to insert the value of a selected 'select form' into my mysql database.
How can i get the right value of this?
<form action='' method='post'>
<select name="myselectbox">
<option name="myoption1" value="myoption1">myoption1</option>
<option name="myoption2" value="myoption2">myoption2</option>
<option name="myoption3" value="myoption3">myoption3</option>
<option name="myoption4" value="myoption4">myoption4</option>
</select>
<input type='submit' value='submit'/>
</form>
something like that? (this one didn't work obviously..)
$sql = "INSERT INTO Entries (myoption1) VALUES ('$_POST[myselectbox]')";
you have to wrap your select tag into a form tag .
<form action='' method='post'>
<select name="myselectbox">
<option name="myoption1" value="myoption1">myoption1</option>
<option name="myoption2" value="myoption2">myoption2</option>
<option name="myoption3" value="myoption3">myoption3</option>
<option name="myoption4" value="myoption4">myoption4</option>
</select>
<input type='submit' value='submit'/>
</form>
once you submit the form, you will get the post variable as $_POST['myselectbox'] that could be appended into a mysql query as you have already did. but for a better way dont just append it like that but check the form is submitted and post variables are available or not before appending.
eg:
if(!empty($_POST['myselectbox'])){
/*.. do your query section... */
}
you have error in your SQL command, $_POST needs html names to be wrapped in quotes like => $_POST['some_name'] :
$sql = "INSERT INTO Entries (myoption1) VALUES ('$_POST[myselectbox]')";
/* ^^ missing quotes here*/
try it this way :
$sql = "INSERT INTO Entries (myoption1) VALUES (".$_POST['myselectbox'].")";
Assuming that your form is correct and it is posting the values that you want to your script.
(You have sprinkled your code with echo to ensure this is the case?)
The simplest reliable way of sending the data into a SQL statement and therefore into mysql is to use prepared statements.
Take a look here: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
Basically you write the SQL statement without your variables in it (replaced with ?) and then tell mysql to execute the statements with your variables later. It avoids the need to escape strings and worry about how to build things up.
As an example, you might have:
// Connect to mysql
$mysqli = new mysqli('where your server is', 'my_user', 'my_password', 'world');
// Build the initial statement - easier to read as you don't have your string concatenation here
$stmt = $mysqli->prepare( "INSERT INTO Entries (myoption1) VALUES (?)" );
// Tell mysql that the '?' should be replaced with the value in your post array
$stmt->bind_param( "s", $POST['myselectbox'] );
// Execute the statement
$stmt->execute()
Obviously you should add error handling too, but the documentation covers the basics of this.
SQL Injection
The main reason why the use of prepared statements is a good idea is that it avoids SQL injection attacks.
There are other ways round, but in my mind this is the simplest solution.
SQL Injection attacks are situations where someone attempts to change the SQL statement that is being run by "injecting" other SQL into your statement.
Using your code as an example, you may execute this statement:
$sql = "INSERT INTO Entries (myoption1) VALUES ('". $_POST['myselectbox'] ."')";
Which would normally receive (let's suggest) something like myoption1.
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES ('myoption1');
If someone decided to, they could send '='' OR '1'='1
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES (''='' OR '1'='1');
Which is (obviously) very different.
Or, even worse send '=')'; DROP TABLE Entries WHERE (''='
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES (''=''); DROP TABLE Entries WHERE (''='');
Use Prepared Statements
Simply put, but using prepared statements, you are telling mysql that what you are sending is a literal string to be used as a parameter. It can never be regarded as part of the statement itself and therefore the above is simply not possible.
Much much safer.
I hope that makes it clearer. If you want more info I suggest you research it independently...
$value = mysql_real_escape_string($_POST['myselectbox']);
$sql = "INSERT INTO Entries (myoption1) VALUES ($value)";
Related
<?php include_once("database.php");
?>
<?php include_once("header.php");
?>
<?php
if ($_POST['submit'] )
{
$food_name = $_POST['food_name'];
$food_calories = $_POST['food_calories'];
echo $food_name . $food_calories;
if (!empty($food_name) && !empty($food_calories) )
{
$query = 'INSERT INTO foods VALUES(0, $food_name, $food_calories)';
mysqli_query($con, $query) or die(mysqli_error($con));
echo 'added';
} else {echo'fail';}
} else {echo'fa2oo';}
?>
<h1> Please Fill out Form Below to Enter a New Food </h1>
<form action="addfood.php" method="post">
<p>Name:</p>
<input type="text" name="food_name"/>
<p>Calories:</p>
<input type="text" name="food_calories"/> </br>
<input type="submit" value="submit" />
</form>
<?php include_once("footer.php")?>
Really don't understand why this simple insert is not working. The form is self-referencing. The form does not echo anything and simply resets when i hit the submit button. database connects with no errors.
Since you're inserting strings, you need to enclose them by single quotes ('):
$query = "INSERT INTO foods VALUES(0, '$food_name', $food_calories)";
Note, however, that building an SQL statement by using string manipulation will leave your code vulnerable to SQL inject attacks. You'd probably be better off using a prepared statement.
You have a few errors in your code:
1. Missing name attribute
You are missing the name attribute for your submit button. So add it like this:
<input type="submit" name="submit" value="submit" />
//^^^^^^^^^^^^^
2. Wong variables in empty()
You have to check if the $_POST variables are empty! Otherwise you would try to assign an undefined variable to another variable. So change your second if statement to this:
if (!empty($_POST['food_name']) && !empty($_POST['food_calories']) )
//^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
And also put the assignments inside the second if statement.
$food_name = $_POST['food_name'];
$food_calories = $_POST['food_calories'];
3. Wrong quotes + missing quotes
You have to use double quotes that your variable in the query gets parsed as variables. Also you have to put single quotes around them since they are strings, so change your query to this:
$query = "INSERT INTO foods VALUES(0, '$food_name', '$food_calories')";
//^ ^ ^ ^ ^
Side notes:
Add error reporting at the top of your file(s) to get useful error messages:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
You may also want to change to mysqli with prepared statements since they are, much safer.
Here's the safe way of doing this using mysqli. Prepared statements will make sure you don't have (as high of) a risk of SQL injection
editing to include the connection:
$conn = new mysqli($host, $username, $password, $dbname);
If you want to see errors, you need to tell php to give the the errors. this should suffice:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
This part is how to do the query.
Note the bind_param part; this is where you identify how your variables are going to into the database, and what datatype they need, so you don't need to remember which items to put in quotes in the actual query.
$query = $conn->prepare("INSERT INTO foods VALUES(0, ?, ?)");
$query->bind_param("si",$food_name, $food_calories);
$query->execute();
$query->close();
As mentioned before, $food_name is a string, so you specify it as such with the s in the bind_param and assuming that calories are an integer, they go in as i.
Another nice feature of using this approach is you no-longer need to worry about escaping variables; items in inputs go in exactly as they are entered
If you want more information in detail there's always this reliable source:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
If you find this a bit too much, here's a great site to learn step by step how to use prepared statements from scratch (it also includes PDO but you may find it easier to use the mysqli at first and it still pretty good). http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Have fun!
There are a few things wrong here.
Firstly, anything inside this conditional statement will not happen because of your submit button not bearing the "submit" name attribute.
if ($_POST['submit'] ){...}
However, it's best using an isset() for this.
if (isset($_POST['submit'] )) {...}
Modify your submit to read as:
<input type="submit" name="submit" value="submit" />
^^^^^^^^^^^^^
Then, we're dealing with strings, so wrap the variables in your values with quotes.
Wrap your query in double quotes and the values in single quotes:
$query = "INSERT INTO foods VALUES (0, '$food_name', '$food_calories')";
Sidenote #1: If you experience difficulties, use the actual column names in which they are to go inside of.
I.e.: INSERT INTO table (col1, col2, col3) VALUES ('$val1', '$val2', '$val3')
Sidenote #2: Make sure that 0 for your column is indeed an int, however I don't know why you're using that.
If that column is an auto_increment, then replace the 0 with '' or NULL, should your schema accept it.
Now, should there be any character that MySQL may complain about, being quotes, etc., then you will need to escape/sanitize your data.
Say someone entered Tim's donuts in an input:
MySQL would translate that in your values as 'Tim's donuts', in turn throwing a syntax error.
Using mysqli_real_escape_string() for instance, would escape the apostrophe and render it as 'Tim\'s donuts' being a valid statement since it has been escaped.
Better yet, using prepared statements, as outlined below.
In its present state, your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
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: Error reporting should only be done in staging, and never production.
Footnotes:
Given that we don't know which MySQL API you are connecting with, please note that different APIs do not intermix with each other.
For example:
You can't connect using PDO and querying with mysqli_
You can't connect using mysql_ and querying with mysqli_
etc. etc.
You must be consistent from A to Z, meaning from connection to querying.
Consult Choosing an API on PHP.net
https://php.net/mysqlinfo.api.choosing
Final closing note(s):
As stated by Rizier123, you are best using:
if (
!empty($_POST['food_name'])
&&
!empty($_POST['food_calories'])
)
It is a better solution.
Your issue (at least one of them) might be the SQL statement itself. Depending on the columns that you have in this foods table, you'll be required to specify the columns that you're inserting into. Try this:
INSERT INTO foods (col1, col2, col3) VALUES (val1, val2, val3)
Also, if val1 is supposed to be the ID column, you can't specify a value for that if it's auto-incrementing... the db will take care of that for you.
So I have finished creating a database and I use php to insert data into it, I have been trying to do SQL injection attacks and other things to see if I am secure, but since I am no expert I was hoping to check that what I have done is secure and the correct way to go about.
I have this(names/variables have been modified) form and when the submit button is pressed, the function insert() runs
<form action="" method="POST">
var1: <input type="text" name="var1"><br>
var2: <input type="text" name="var2"><br>
<input type="submit" value="Submit">
</form>
<php?
function insert() {
$connect = mysqli_connect("localhost","user","user","table");
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
mysqli_query($connect, "INSERT INTO column_name (var1, var2) VALUES ( '$var1','$var2'); ");
}
?>
and I can't seem to inject my form which has var1 and var2 with this
$var2 = '): DROP TABLE test --and several variants of this
From looking around I have found that mysqli_query will only accept one query so that is why it is not working. Correct me if I am wrong.
my other idea was affecting the PHP script that is running,
by injecting the form with this
$var2 = "'); "); mysqli_query($connect,"DROP TABLE test");//
Question: can this type of thing happen? where you can affect the PHP function through the $post method while it runs? I have looked around and can't find anything. Is that because it can't?
any research papers, articles, etc. that I can have a look at to help if what I am asking is obvious would be appreciated :)
EDIT: I will be adding prepared Statements to make this secure
SQL injections use commands like union to run multiple queries at once at vulnerable place. Your form IS vulnerable, because you are either not using any sort of escaping, nor prepared statements. What if your $var2 would contain for example hi')? That would escape the brackets and open a vulnerability. Also if you just $_POST['value'] and insert it directly in database, it opens XSS vulnerability.
If you want to make sure your site is safe i suggest you:
Fisrt, Use prepare statement:
$mysqli->prepare("SELECT Distinct FROM City WHERE Name=?");
$stmt->bind_param("s", $city);
$stmt->execute();
Second, Use filter_input method, for example:
filter_input(INPUT_POST,'email',FILTER_EMAIL);
You are not supposed to certify your site against SQL Injection by trying to figure out how to exploit the hundreds of potential security breaches you leave all around the place.
If you want to make sure your site is safe, just take the applicable security measures, like using prepared statements.
This question already has answers here:
Multiple inputs with same name through POST in php
(5 answers)
Closed 8 years ago.
I'm trying to insert multiple bids like from -to in a column 'bidamount'. I have did some coding in for database and some code I have did for multiple bids but what I'm getting here whenever I'm inserting the value like 3.1 to 8.1. It is inserting a value 8.1 and 0. This one is not inserting all the value from 3.1 to 8.1 in column bidamount in table of a database.
I'm new here in php so I'm not getting exact things what is wrong with these code. Please help me in this.
My code :
<?php
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gunjanbid", $con) or DIE('Database name is not available!');
if(isset($_POST['submit'])) {
$m=$_POST['bidamount'];
$n=$_POST['bidamount'];
for($bidd=$m;$bidd<=$n;$bidd++)
$bidds=array($bidd);
$username=$_SESSION['userName'];
$productid=$_GET['id'];
$sql1="INSERT INTO bid(productid,description,closing_date,bidamount,userName) values('$productid','$r',Now(),'$bidds','$username')";
$result1=mysql_query($sql1);
if($result1!=1) {
echo "failure!";
}
}
?>
<form action="" name="auction1" method="post" >
<input type="hidden" name="description" value="">
<input type="hidden" name="closing_date" value="">
<input type="text" name="bidamount" value="" size="5"> to
<input type="text" name="bidamount" value="" size="5" >
<input type="submit" name="submit" class="button" value="Bid Now">
</form>
Please help me. I'm new in php.
I suggest you to use this code
$bid = explode("to",$_POST['bidamount']);
$m = $bid[0];
$n = $bid[1];
instead of
$m = $_POST['bidamount'];
$n = $_POST['bidamount'];
Firstly: If you want to submit multiple values with the same name, you can put brackets after the name, like name="bidamount[]", and PHP will assemble them into an array for you.
Secondly, though, MySQL doesn't understand arrays. It doesn't like storing more than one value in a column. And quite frankly, you don't want to do it anyway. Seriously. It causes more trouble than it's worth.
Discrete values are harder to get. Since there's no "array" type in MySQL, you end up having to parse a string and other such junk to get your individual values back. Getting two values from two columns, on the other hand, is much simpler.
MySQL can't help you keep the data valid. All it sees is a big bunch of characters/bytes. It can't do but so much with the individual pieces. It can't enforce uniqueness, for example.
It makes indexes useless. Once you have to parse each string in order to find stuff in it, you've pretty much killed any chance of MySQL being able to use indexes to speed up the query.P
If your two values represent a "low" and "high", then call them that, and store them as separate fields.
If they're just two arbitrary amounts, on the other hand -- and particularly if you anticipate having more than two -- then they should each be part of their very own row in another table.
As for the code: though it's not part of the question, there are a couple of other issues.
mysql_query is deprecated. (Read: not even the authors of PHP think you should use it.) Stop farting around with it. There are much better ways of talking to a database.
You're trusting the user way too much.
Open up the page, then go into your browser's dev tools. find the hidden fields, and change the description to "Joe's item". Submit the form, and it should break. The reason is that SQL uses ' for quotes. One being in your string throws off the quoting and corrupts the SQL.
It's bad enough that this can be done accidentally -- but some people will do it on purpose, and can supply just the right data to trick your server into running SQL it shouldn't. That's called "SQL injection", and it can be a pretty serious security issue.
You could work around this issue by simply stripping ' out of your input. But frankly, that's almost as half-assed as just saying "Don't use apostrophes!!11!11". And there is at least one other special character in strings as well.
If you use a more modern database extension, like PDO, you can fix the first two issues at once.
Watch:
<?php
if ($_POST['submit']) {
// By the way, you don't need to create the DB connection if you don't need to
// mess with the DB. :)
$con = new PDO('mysql:host=localhost;dbname=gunjanbid', 'root', '');
$low = $_POST['low'];
$high = $_POST['high'];
$id = $_GET['id'];
$description = $_POST['description'];
$user = $_SESSION['username'];
// PDO has a `query` method that works much like `mysql_query`. But that does
// absolutely nothing to fix the SQL injection issue.
//
// Instead, use a prepared statement. You can insert placeholders (?) for data,
// and when you run the statement later with the real data, PDO and MySQL know which
// stuff is data and which is SQL. Since they're kept separate, the data won't have
// a chance to be interpreted as part of the SQL.
$stmt = $con->prepare('
INSERT INTO bid (productid, description, closing_date, userName, low, high)
VALUES (?, ?, NOW(), ?, ?, ?)
');
if (!$stmt->execute([$id, $description, $user, $low, $high])) {
echo 'Failure!';
}
}
?>
I've got an internal site I'm developing for work. I'm by no means a web developer but know enough to get some basic functionality done. I've got a form working fine for inserting data. I'm trying to figure out this one last piece, though.
The page is designed to add jobs to our site. Each position has assigned responsibilities. The easiest way to make this work (in my brain) is to create a table for responsibilities that has a responsibilityID, PositionID, and then the responsibility. I want a way to kind of bulk add these responsibilities when completing the form for the new position. Something similar to how you add new fields when using the MySQL workbench - where you can just click on the next row and it'll add that field. That would work great.
I'm not sure what to even search for to accomplish this other than adding multiple items - which hasn't turned up what I'm looking for.
Thanks in advance!
Most times people here like to see what you've tried.
This question was asked here.
example MySQL statement:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
You can replace the values with PHP variables if needed. Just make sure if they are strings, they are in 'quotes'.
If you have a form that allows you to submit multiple responsibilities simultaneously then I would use PDO. Remember PDO is your friend, and always sanitize your inputs before inserting them. Here is them most basic version, You probably want to replace the inputs with dropdowns or texteareas.
table
responsibilityID|PositionID|responsibility
The responsibilityID should be PK and auto-increment
html
<form>
<div>
<h1>job</h1>
<label>PositionID</label><input name='jobs[][positionID]' />
<label>responsability</label><input name='jobs[][responsibility]' />
</div>
<div>
<h1>job</h1>
<label>PositionID</label><input name='jobs[][positionID]' />
<label>responsability</label><input name='jobs[][responsibility]' />
</div>
<div>
<h1>job</h1>
<label>PositionID</label><input name='jobs[][positionID]' />
<label>responsability</label><input name='jobs[][responsibility]' />
</div>
<div>
<h1>job</h1>
<label>PositionID</label><input name='jobs[][positionID]' />
<label>responsability</label><input name='jobs[][responsibility]' />
</div>
<input type='submit' />
</form>
Basic
Create an insert statement then loop through your jobs binding each value to the statement and executing them.
$insert_sql = "INSERT INTO responsibilities (`PositionID`, `responsibility`) VALUES (:PositionID, :responsibility);";
$stmt = PDO::Prepare($insert_sql)
foreach ($jobs as $job){
//add some input testing before you execute to make sure you are not inserting bad values
$stmt->bindValue(":positionID", $job['positionID'], PDO::PARAM_INT);
$stmt->bindValue(":responsibility", $job['responsibility'], PDO::PARAM_STR);
$stmt->execute();
}
The :fieldname in the query tells PDO what needs to be replaced with the bind functions, then the bindValue/bindParam functions tells what to insert where into the query and properly escapes the value so you can insert it. Older sql functions allowed for unescaped or improperly escaped values and you got the little bobby tables problem. PDO protects you from some of the worst injection attacks, but you should probably make sure that positionID points to a real position or that responsibility doesn't have weird java-script exploit code in it.
Fancy
Create an insert statement, bind params, then foreach loop through your responsibilities, checking/sanitizing the input (never trust form data) then executing the statement. Every time you loop the bound parameter will point at the new job.
$insert_sql = "INSERT INTO responsibilities (`PositionID`, `responsibility`) VALUES (:PositionID, :responsibility);";
$job = array('positionID'=>NULL, 'responsibility'->NULL);
$stmt = PDO::Prepare($insert_sql)
$stmt->bindParam(":positionID", $job['positionID'], PDO::PARAM_INT);
$stmt->bindParam(":responsibility", $job['responsibility'], PDO::PARAM_STR);
foreach ($jobs as $job){
//add some input testing before you execute to make sure you are not inserting bad values
$stmt->execute();
}
with the inputs you want to have multi values, use the name attribute like responsibilities[], and then insert serialized data to the database
When I execute this query it returns false, which means the query is wrong. Can you figure out why?
$string1 = 'wee';
$string2 = 'wee';
$string3 = 'wee';
$string4 = 'wee';
if (isset($_POST['submit'])) {
$query = "INSERT INTO data (book, title, content, author)
VALUES ($string1, $string2, $string3, $string4)";
mysql_query($query, $con);
}
However, when I put something that is like the following, it returns true and inserts correctly:
$query = "INSERT into data (book, title, content, author)
VALUES ('wee', 'wee', 'wee', 'wee')";
And another question: when I submit, it seems that the query is returning twice when executed which means two records with one query. Does anyone understand that?
If you need more information, just ask.
Thanks in advance.
Although this question seems answered, you should not be using user input directly in queries as this opens holes for vulnerabilities like SQL Injection (and that's bad mmmay)
If you look at the mysql page on php.net (mysql_query) the page says it is recommended you use an abstraction layer like PDO (pdo-mysql)
Using PDO will allow you to bind parameters to your sql queries to bypass the security implications of using user input in your queries.
If you don't bind parameters to your queries, you're gonna have a bad time.
Your field data type is string or varchar so you need to put '' or "" around them.
Change your query as below
$query = "INSERT into data (book, title, content, author)VALUES ('".$string1."', '".$string2."',
'".$string3."', '".$string4."')";
To resolve submit issue, please post your html code