how to insert multiple bids value in a coloumn [duplicate] - php

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!';
}
}
?>

Related

User inputs, clean and sanitize before sending to db

I've searched a lot of the questions here and I found that they either very old or suggesting using prepared statements PDO which I am not using. So I need your help please.
I have a small discussion/chat box where a user submit a message using a <textarea>
What I need is sanitize and filter the user input so it only accepts plain texts (e.g. no tags, no html tags, no scripts no links, etc). Also, it is important to allow line breaks.
Based on my reading I am doing the following in the following order:
trim()
htmlentities($comment, ENT_NOQUOTES)
mysqli_real_escape_string()
nl2br()
Is what I am doing is right? or I am missing something?
Also is there anything I have to do when echoing the data from the db?
really, appreciate your help and kindness
First, keep the text logical and clean:
trim() -- OK
htmlentities($comment, ENT_NOQUOTES) -- No; do later
mysqli_real_escape_string() -- Yes; required by API
nl2br() -- No; see below
The logic behind those recommendations: The data in the database should be just plain data. Not htmlentities, not br-tags. But, you must do the escape_string in order to pass data from PHP to MySQL; the escapes will not be stored.
But... That is only the middle step. Where did the data come from? Older versions of PHP try to "protect" you be adding escapes and other junk that works OK for HTML, but screws up MySQL. Turn off such magic escaping, and get the raw data.
Where does the data go to? Probably HTML? After SELECTing the data back out of the table, then first do htmlentities() and (optionally) nl2br();
Note, if you are expecting to preserve things like <I> (for italic), you are asking for trouble -- big trouble. All a hacker needs to do is <script> ... to inject all sorts of nastiness into your web page and possibly your entire system.
You also have another option. You can use prepared statements with mysqli
They aren't very difficult to learn and work a bit better than mysqli_real_escape_string() in that you don't need to worry about escaping every single variable that will be in your query. They are by nature "prepared" before they go into the database. There are other advantages to this as well, in that:
you do not need to addslashes() to be able to handle characters with
apostrophes etc.
for large databases, they will considerably speed
up your queries (much like PDO).
Here's how to do it:
You connect to the database by creating a new mysqli object like this:
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $dbc->connect_error);
}
Next you want to convert your variables from your form.
Say you have a form field like this:
<input type="text" name="var1">
you can use htmlentities and trim together like so, and create your $var1 variable:
$var1 = htmlentities(trim($_POST['var1']));
Then you can create your transaction like this:
$stmt= $conn->prepare("insert into tablename (key1, key2) values (?,?)");
$stmt->bind_param("is",$var1, $var2);
$stmt->execute();
$stmt->close();
That's basically it. You do a query just like you normally would, but instead use the ? placeholders, assigning the datatype (above is i for integer, and s for string) and then bind them to your placeholders in the query.
That's basically it.
if you want to do it with a select with a variable, you use the normal select syntax and the same way with a ? with the variable, and then bind it. You can then bind your results into variables easily like so (assuming var3 is an integer):
$stmt= $conn->prepare("select var1, var2 from tablename where var3 = ?");
$stmt = bind_param("i", $var3);
$stmt->bind_result($var1, $var2);
$stmt->execute();
$stmt->close()
and then you can fetch your variables using this
$stmt->fetch();
or if your query brings back multiple rows
while ($stmt->fetch() {
echo $var1 . $var2;
}
nl2br() is used for output, you don't need to worry about input; it can be stored in the database as \n, and when you need it spits it out as breaks. If one of these variables needs the new lines turned into <br/> tags, you can, as you suggest use nl2br() on the variables (note this adds no security, but as you said you needed it), like so
echo nl2br($var1, false);
you can also use trim() and htmlentities() on this if it is being echoed into, say, a form input field and you don't want your form to break if there are html characters in the output.
Your question can lead me to build a full project with many features ;) lol
Before we start with out steps, we need a dummy (test) database for this scenario. We call out database chatbox with table called chat. You can simply create it by executing the following sql statement in your MySQL test environment:
CREATE TABLE `chat` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`msg` VARCHAR(200) NOT NULL DEFAULT '0',
`user_id` INT(11) NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
;
Now you can go a head and follow the steps here:
Step 1: Create project folder in your web server.
Build database connection based on PDO and call it dbConnect.inc.php:
<?php
// check if PDO driver not available
if (!defined('PDO::ATTR_DRIVER_NAME'))
echo 'PDO driver unavailable <br />';
// database configuration
$dbHost = "localhost";
$dbPort = "3306";
$dbName = "chatbox";
$dbUser = "root";
$dbPass = "";
$strDSN = "mysql:host=$dbHost:$dbPort;dbname=$dbName";
// database connection
try
{
$dbConn = new PDO($strDSN, $dbUser, $dbPass);
//Activate following line to view all error messages
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e)
{
die("Could not connect to the database $dbName, error info: <br />"
. $e->getMessage());
exit();
}
I will test this works before go to next step. Btw the prepared method does not require mysqli_real_escape_string().
I have used PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION in stead of if statements, this method will give you useful error details while development the project. You will find out which method is more practical for getting error message while your development process of the project.
Step2: Create a file call filter.inc.php:
<?php
// filter for input
function filterInput($content)
{
$content = trim($content);
$content = stripslashes($content);
return $content;
}
//filter for viewing data
function filterOutput($content)
{
$content = htmlentities($content, ENT_NOQUOTES);
$content = nl2br($content, false);
return $content;
}
This file contain a function to filterInput to sanitize or filter your input content for comments or other inputs. And filterOutput that effect your data view.
All depending on your strategy and what you need, like if you need to allow people post url's or email address, should url and email become active link or only viewed as text etc. that way you can define which filter should be use for your content input and which filter should be used for you content output.
You can add or delete extra features to functions. There are many features for text input and output, you can test those individually and evaluate it, and even extend the filter function or create your own function.
Final step 3: Now we put the puzzles together in our index.php file:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Chat box</title>
</head>
<body>
<?php include './dbConnect.inc.php'; ?>
<?php include './filter.inc.php'; ?>
<h1>Chat box</h1>
<p>
<?php
// this is dummy user id, but use the id over user id when login or the way you want
// this is only example
$user_id = 1;
if (isset($_POST["msg"]))
{
$msg = filterInput($_POST["msg"]);
$sql = "INSERT INTO chat "
. "(msg, user_id) "
. "VALUES "
. "(:msg, :user_id)";
$stmt = $dbConn->prepare($sql);
$fieldsArr = [':msg' => $msg, ':user_id' => $user_id];
$stmt->execute($fieldsArr)
// refresh page after insert
header("Location: " . $_SERVER['REQUEST_URI']);
}
?>
<form action="index.php" method="post">
<textarea name="msg" id="msg" required></textarea>
<input name="submit" type="submit">
</form>
</p>
<p>Comments</p>
<p>
<?php
$sql = "SELECT * FROM chat WHERE user_id = (:user_id);";
$stmt = $dbConn->prepare($sql);
$fieldsArr = [':user_id' => $user_id];
$stmt->execute($fieldsArr)
while ($result = $stmt->fetch())
echo "<h3>" . filterOutput($result['msg']) . "</h3>";
$dbConn = null;
?>
</p>
</body>
</html>
This is to demonstrate how things works. You have insert, select statement as example and filter functions. You can make tests, extend it the way you like or further develop your own project.
Here is screen shot of the chatbox example I made:
filter_input could be another one you are looking for. It can save you hours from writing sanitizing and validation code. Of course, it does not cover every single case, but there is enough so that you can focus more on specific filtering/validating code.
Though it is strongly recommended to use prepared statements with
PDO/mysqli. But sometimes it is not so easy to convert the whole
project in the tail end of the project. You should learn PDO/mysqli for
your next project.
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
There are different Types of filters for you. You can select depending on your needs. You can also use filter_has_var to check for variable set.
Your code looks fine, if you don't want to prepare statements then escaping is the next best thing. And when you echo it should be straightforward, it's only plain text.

Can't Get Simple SQL Insert to Work

<?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.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 1

$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('{$mname}', {$pos}, {$vis}) ";
if(mysql_query($q)) {
header("Location: content.php");
}
else {
echo mysql_error();
}
Here, $mname is a string. $pos and $vis are integers.
Where is the mistake?
try to use only single quote to query variable rather pseudo(i think pseudo variable needs to be also quoted for query) like
$q= "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis')";
If you're going to use braces to try and prevent the greedy nature of variable expansion, you should use them properly.
The string "{$pos}", when $pos is 42, will give you "{42}", which is clearly not a valid integer in terms of your SQL statement. What you're looking for is instead:
${pos}
In this case, of course, you don't actually need the braces since the characters following the variable name cannot be part of a variable name - they are, respectively, ', , and ).
You only need to use braces when the following character could be part of a variable name. For example, consider:
$var = "pax";
$vara = "diablo";
In that case, $vara will give you diablo while ${var}a will give you paxa.
And I give you the same advice I seem to give weekly here :-) If you have a query that's not working, print it out! You'll find that the problem will usually become immediately obvious once you see the query in the final form you're passing to the DBMS.
And, as per best practices, I'll advise against using this method of creating queries. Anyone that's investigated SQL injection attacks (google for sql injection or, my favourite, little bobby tables) soon learns that they should use parameterised queries to prevent such attacks.
you are missing ' sign as the error says.
$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis') ";
The value will be stored to table. Just make datatype to int in mysql table if you want it to be integer and make validation not to enter string while inserting.
You cannot name a column name whenever you run something through MySQL. One way to check is to run the query within HeidiSQL. MySQL functions will be highlighted blue, so you know if the column name becomes blue to not use it. Also; Here's a quick run of PDO to make things a little bit better; I'd suggest looking further into it as well.
public function MakeMenu() {
$q = <<<SQL
INSERT INTO subjects (menu_name,_position,visible)
VALUES(":menu_name","_position","visible")
SQL;
$resource = $this->db->prepare( $query );
$resource->execute( array (
'menu_name' => $_POST['menu_name'],
'_position' => $_POST['position'],
'visible' => $_POST['visible'],
));
}
To make things easy enough you can just make a call.php page as well. Make the calls.php page require your class page and add a hidden input to your form. IE
<input type=hidden" id="process" value="make_menu">
Then within the calls.php page add
if ( isset($_POST['process']) )
{
switch ($_POST['process'])
{
case 'make_menu':
$class->MakeMenu();
break;
I know this isn't just a quick answer, but I'm hoping you'll look further into what's happening here and move away from mysql functions. I have seen posts from people running IIS servers and not having any luck with any of the deprecated functions. Not sure how long it will be until Apache follows suite, but don't waste your time with something that's being deprecated as we speak.

add multiple items to a database in one form

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

Created an insert forum using HTML/PHP but I get error when adding a certain amount of content

I've very new to this, and it's part of a University project which I decided to go the extra mile in.
I've created a HTML form to insert rows into a table on a MYSQL database. The form works fine when limited number of characters are entered but when I try over a certain amount I get an error. I'm using VARCHAR's for all columns and their limits are far higher than the text I am trying to insert.
Here is my code
<html>
<body>
<h1>Add new entries to Home and News page here</h1>
<form action="insert.php" method="post">
<br>Date: <input type="date" name="date"></br>
<br>Title: <input type="text" name="title"></br>
<br>Body:<input type="text" name="body" </br>
<br>Media: <input type="text" name="media"></br>
<br>ID: <input type="text" name="id"</br>
<input type="submit">
</form>
</body>
</html>
and the PHP
<?php
$con=mysqli_connect("***","****","****","*****");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO news (date, title, body, media, id)
VALUES
('$_POST[date]','$_POST[title]','$_POST[body]','$_POST[media]','$_POST[id]')";
if (!mysqli_query($con,$sql)) {
die('Error ' . mysqli_error());
}
echo "1 record added";
mysqli_close($con);
?>
A point in the right direction would be appreciated.
What's the error you're receiving? Please note your error trapping may be incorrect, try:
die ('Error: '.mysqli_error ($con));
I notice you're not escaping (making safe) the data being sent by the user. So if for example I set my "title" to:
This is my title, '; SQL INJECTION; '
I'd break your code:
INSERT INTO news (date, title, body, media, id)
VALUES
('date','This is my title, '; SQL INJECTION; '','body','media','id')";
You can resolve this by using any method of "escaping" (making safe) the values you're putting into your query. There's literally a hundred ways you could do this, if you've been asked to the mysqi_*() functions, you could do it thusly:
$date = mysqli_real_escape_string ($con, $_POST['date']);
$title = mysqli_real_escape_string ($con, $_POST['title']);
$body = mysqli_real_escape_string ($con, $_POST['body']);
$media = mysqli_real_escape_string ($con, $_POST['media']);
$id = mysqli_real_escape_string ($con, $_POST['id']);
$sql = "INSERT INTO news (date, title, body, media, id)
VALUES
('$date','$title','$body','$media','$id')";
So an explanation of what's happening:
(XKCD has a nice joke about the subject.)
Without the mysqli_real_escape_string, you're building the SQL query ($sql) with anything the user is posting through the form. That's all fine and dandy, providing they don't end up altering your SQL statement.
So if they insert a single quote: ', the SQL will end up invalid, because the "VALUES ('$title')" for example could become "VALUES ('An adventure's dream')", notice how MySQL is going to see 'An adventure' as the value, and "s dream'" as some broken stuff on the end?
With the inclusion of "mysqli_real_escape_string()", any bad symbols (like a single quote) are escaped, which for MySQL means having a "\" added in front of it. That tells MySQL to ignore the symbol - and treat it as data, rather than an SQL command.
For easy debugging - I'd suggest putting:
print "<pre>$sql</pre>";
just after you create $sql. That way you can see exactly what's being sent to MySQL.
(Personally I prefer using PHP's PDO library - which if you're interested in the subject, is worth a read. It has some cool features for escaping stuff :))
Really hope you enjoy studying your degree!
FYI:
The VARCHAR(255) should silently chop your data to 255 characters long, without raising an error.
That is because in mysql you fill in for example your body contains varchar(255) which means the body of the news can only contain 255 charachters this also include spaces.
If you want to be able to fill in more characters just make the number varchar(5000) for example bigger

Categories