In the below script, I'm trying to submit many from php to mysql in one table,
<?php
include "koneksi.php";
$soal[] = $_POST['soal'];
$j1=$_POST['jwb_1'];
$j2=$_POST['jwb_2'];
$j3=$_POST['jwb_3'];
$j4=$_POST['jwb_4'];
$j5=$_POST['jwb_5'];
$kunci=$_POST['kunci'];
$beban=$_POST['beban'];
$id=$_POST['id_soal'];
$course=$_SESSION['course'];
$mgu=$_SESSION['m`enter code here`inggu'];
$jum=$_POST['jum'];
$i=$id;
for ($i=1;$i<=$jum;$i++){
$sq=mysql_query("insert into
t_soal(id_soal, course, soal, jawab_1,
jawab_2, jawab_3, jawab_4, jawab_5, beban,
kunci, minggu)
values('$i', '$course', '$soal', '$j1',
'$j2', '$j3', '$j4', '$j5', '$beban',
'$kunci', '$mgu')");
}
Be sure to never put your data this way. Please, be aware of SQL Injection, XSS attacks... You need to validate your inputs, parameterized and clean it. Then, put it in your mysql using SQL statement.
And try to use a good form for your SQL statement. Like this :
INSERT INTO `databaseName`.`tableName` (`id_soal`, `course`) VALUES ($i, $course);
Everything should work..(Be sure to connect correctly to your database too!)
Related
I have a page with two forms on it (and two submit buttons), and the forms link the page back to itself with action="" for the INSERT INTO statements. One of the INSERT INTO statements is:
<?php
$sql="INSERT INTO panelProduct (length_mm, width_mm, aperture)
VALUES ('$_POST[p_length_mm]','$_POST[p_width_mm]','$_POST[p_aperture]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
One of the reasons I have put the form and the INSERT statements on the same page is that the form allows users to add products to an order, and there may be several products (so I thought the user could keep submitting until they're done...). The other reason was that I need to use a $_POST value sent from the previous page to do something else with the products they enter, and I don't know how to send it to more than one page.
Anyway, the problem I have found is that a new row is inserted into the database every time the page is refreshed, containing NULL values. This makes sense to me as the PHP will execute the statement above every time it encounters it. My question therefore is how I can make some sort of condition that will only execute the INSERT statement if the user enters something in the form and 'Submits'?
you could use the empty() method of PHP to check for null values in each of the variables.
Something like:
if(!empty($_POST['p_length_mm']) && !empty($_POST['p_width_mm']) && !empty($_POST['p_aperture']))
{
//execute your query here
}
else
{
//if there's an alternative you would like to happen if values are null, or just leave out.
}
Hope that does the trick.
You have to check if data come from your form. I'd suggest this approach - name your submit button (i.e. <input type="submit" name="my_submit_button" value="Whatever" /> and this condition to your insert code:
if( isset( $_POST['my_submit_button']) ) {
.. process your post data
}
Also, always remember not to trust user provided data. Verify if all data expected are present in$_POST and format matches requirements (i.e. you ask for number and received letters etc). If all test passed, then you are ready to commit your data to DB.
You need a condition like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) {
// a form was posted
}
Of course, you still need to check whether your post actually contains the right stuff:
isset($_POST['p_length_mm'], $_POST['p_width_mm'], $_POST['p_aperture'])
Even better is to use filter_input_array() to sanitize your incoming data; your current code is open to SQL injection attacks. Using PDO or mysqli and prepared statements is the way to go.
For a while I am more and more confused because of possible XSS attack vulnerabilities on my new page. I've been reading a lot, here on SO and other googled sites. I'd like to secure my page as best as it is possible (yes, i know i cant be secure 100%:).
I also know how xss works, but would like to ask you for pointing out some vulnerable places in my code that might be there.
I use jquery, javascript, mysql, php and html all together. Please let me know how secure it is, when i use such coding. Here's idea.
html:
<input name="test" id="id1" value="abc">
<div id="button"></div>
<div id="dest"></div>
jQuery:
1. $('#id').click (function() {
2. var test='def'
3. var test2=$('#id1').val();
4. $.variable = 1;
5. $.ajax({
6. type: "POST",
7. url: "get_data.php",
8. data: { 'function': 'first', 'name': $('#id').val() },
9. success: function(html){
10. $('#dest').html(html);
11. $('#id1').val = test2;
12. }
13. })
14. })
I guess it's quite easy. I have two divs - one is button, second one is destination for text outputted by "get_data.php". So after clicking my button value of input with id 'id1' goes to get_data.php as POST data and depending on value of this value mysql returns some data. This data is sent as html to 'destination' div.
get_data.php should look like this:
[connecting to database]
switch($_POST['function']) {
case 'first':
3. $sql_query = "SELECT data from table_data WHERE name = '$_POST[name]'";
break;
default:
$sql_query = "SELECT data from table_data WHERE name = 'zzz'";
}
$sql_query = mysql_query($sql_query) or die(mysql_error());
$row = mysql_fetch_array($sql_query);
echo $row['data']
For now consider that data from mysql is free from any injections (i mean mysql_real_escaped).
Ok, here are the questions:
JQuery part:
Line 2: Can anybody change the value set like this ie. injection?
Line 3 and 11: It's clear that putting same value to as was typed before submiting is extremely XSS threat. How to make it secure without losing functionality (no html tags are intended to be copied to input)
Line 4: Can anybody change this value by injection (or any other way?)
Line 8: Can anybody change value of 'function' variable sent via POST? If so, how to prevent it?
Line 10: if POST data is escaped before putting it into database can return value (i mean echoed result of sql query) in some way changed between generating it via php script and using it in jquery?
PHP part:
Please look at third line. Is writing: '$_POST[name]' secure? I met advice to make something like this:
$sql_query = "SELECT data from table_data WHERE name = " . $_POST['name'];
instead of:
$sql_query = "SELECT data from table_data WHERE name = '$_POST[name]'";
Does it differ in some way, especially in case of security?
Next question to the same line: if i want to mysql_real_escape() $_POST['name'] what would be the best solution (consider large array of POST data, not only one element like in this example):
- to mysql_real_escape() each POST data in each query like this:
$sql_query = "SELECT data from table_data WHERE name = " . mysql_real_escape($_POST['name']);
to escape whole query before executing it
$sql_query = "SELECT data from table_data WHERE name = " . $_POST['name'];
$sql_query = mysql_real_escape($sql_query);
to write function that iterates all POST data and escapes it:
function my_function() {
foreach ( $_POST as $i => $post ) {
$_POST[$i] = mysql_real_escape($post)
}
}
What - in your opinion is best and most secure idea?
This post became quite large but xss really takes my sleep away :) Hope to get help here dudes once again :) Everything i wrote here was written, not copied so it might have some small errors, lost commas and so on so dont worry about this.
EDIT
All right so.. if I understand correctly filtering data is not necessery at level of javascript or at client side at all. Everything should be done via php.
So i have some data that goes to ajax and further to php and as a result i get some another kind of data which is outputted to the screen. I am filtering data in php, but not all data goes to mysql - part od this may be in some way changed and echoed to the screen and returned as 'html' return value of successfully called ajax. I also have to mention that I do not feel comfortable in OOP and prefering structural way. I could use PDO but still (correct me if i am wrong) i have to add filtering manually to each POST data. Ofcourse i get some speed advantages. But escaping data using mysql_real_escape looks to me for now "manual in the same level". Correct me if i am wrong. Maybe mysql_realescape is not as secure as PDO is - if so that's the reason to use it.
Also i have to mention that data that doesnt go to database has to be stripped for all malicious texts. Please advice what kind of function I should use because i find a lot of posts about this. they say "use htmlentities()" or "use htmlspecialchars()" and so on.
Consider that situation:
Ajax is called with POST attribute and calls file.php. It sends to file.php POST data i.e. $_POST['data'] = 'malicious alert()'. First thing in file.php I should do is to strip all threat parts from $_POST['data']. What do you suggest and how do you suggest I should do it. Please write an example.
XSS is Cross-site scripting. You talk about SQL injection. I will refer to the latter.
JQuery Part
It's possible to change every single JavaScript command. You can try it yourself, just install Firebug, change the source code or inject some new JavaScript code into the loaded page and do the POST request. Or, use tools like RestClient to directly send any POST request you like.
Key insight: You cannot control the client-side. You have to expect the worst and do all the validation and security stuff server-side.
PHP Part
It is always a good idea to double-check each user input. Two steps are usually mandatory:
Validate user input: This is basically checking if user input is syntactically correct (for example a regex that checks if a user submitted text is a valid email address)
Escape database queries: Always escape dynamic data when feeding it to a database query. Regardless where it's coming from. But do not escape the whole query string, that could yield in unexpected results.
Maybe (and hopefully) you will like the idea of using an ORM solution. For PHP there are Propel and Doctrine for instance. Amongst a lot of other handy things, they provide solid solutions to prevent SQL injection.
Example in Propel:
$result = TableDataQuery::create()
->addSelectColumn(TableDataPeer::DATA)
->findByName($_POST['name']);
Example in Doctrine:
$qb = $em->createQueryBuilder();
$qb->add('select', 'data')
->add('from', 'TableData')
->add('where', 'name = :name')
->setParameter('name', $_POST['name']);
$result = $qb->getResult();
As you can see, there is no need for escaping the user input manually, the ORM does that for you (this is refered as parameterized queries).
Update
You asked if PDO is also an ORM. I'd say PDO is a database abstraction layer, whereas an ORM provides more functionality. But PDO is good start anyway.
can firebug any malicious code in opened in browser page and send
trash to php script that is somwhere on the server?
Yes, absolutely!
The only reason you do validation of user input in JavaScript is a more responsive user interface and better look & feel of your web applications. You do not do it for security reasons, that's the server's job.
There is a firefox addon to test your site for XSS, it called XSS Me
Also you can go to
http://ha.ckers.org/xss.html
for most XSS attacks
and go to
http://ha.ckers.org/sqlinjection/
for most sql injection attacks
and try these on your site
table person
"person_id"
"person_name"
table email
"email_id"
"email"
"person_id"
What is the sql comment for insert data form a web form into these tables?
In the web form I have a text box for name and dynamic text box for email
Read the form values into variables, securely insert into MySQL database: http://www.php.net/manual/en/function.mysql-query.php
If you want to do this by only SQL queries, you need to code a procedure like
INSERT INTO person (person_name) VALUES ('PERSON_NAME')
INSERT INTO email (email_id,email,person_id) VAUES ('EMAIL_ID','EMAIL',(SELECT LAST_INSERT_ID()))
I assumed that you can post PERSON_NAME, EMAIL_ID, EMAIL from your web form.
I think it's easy to send both EMAIL_ID, EMAIL from your autocomplete like box.
Well assuming you are using POST and you set up your connection to the db i'd do it like this (i omit validation and so on, just the sript to insert data :
$person_name = mysql_real_escape_string($_POST['person_name']);
$email= mysql_real_escape_string($_POST['email']);
$query = sprintf("INSERT INTO person ('person_name') VALUES ('%s')'",$person_name);
$result = mysql_query($query);
// always set your variables to a default value
$success = false;
// did the query execute successfully?
if($result){
$success = true;
}
if($success){
$person_id = mysql_insert_id();
$query = sprintf("INSERT INTO email ('email','person_id') VALUES ('%s','%s')",$email,$person_id);
$resultSecond = mysql_query($query);
}
There are a few steps involved. You will first need to validate the user's input - don't just put it directly into the database. Validation should be done on the server. You can perform client-side validation with Javascript too, but this should only be done to enhance the user experience - it must not replace server-side validation. To start, you could look at PHP's Filter methods, or perhaps look for a form validation library.
When you come to insert it into the database, I highly recommend using prepared statements instead of messing around with horrible escaping.
The example given on the PHP site is quite good, and should get you started. You could also checkout:
PHP PDO prepared statements
Why you Should be using PHP’s PDO for Database Access
I'm creating a script on my main server and will use js/html to call it as an image source, passing the current tumblr page's referrer variable so I can integrate my blog's stats into my main stat-tracking db.
Anyone who looks at the source, of course, will be able to see that this script can accept a url variable via get. I'm not much of a security wonk, but I'm using the following checks on the input to this var, currently:
$previous_referrer = htmlspecialchars($_GET['ref']);
if (filter_var($previous_referrer, FILTER_VALIDATE_URL) && strpos($_SERVER['HTTP_REFERER'], $tumblelog_url)!== FALSE)
I'm guessing it isn't this simple. What other checks should perform to lock it down against injection attacks?
For inserting data safely in a database :
1) Before inserting in DB
Filter data :
Does my data had the expected type/patern (email,url ....)
The main purpose of filtering in first is to avoid processing useless data
Prevent from sql injection :
if inserting a number use function like intval(),floatval()
if inserting string use function like mysql_real_escape_string (for mysql only) or prepared statement.
2) After insertion , before display
Prevent Xss by using function like htmlspecialchars() or htmlentites().
Greetings I made the following php script so that I could edit text and it would save to a db for future use. However I'm hitting a slight snag at the update / insert queries. I'm not sure what I'm doing wrong but only one of the commands will execute. I'm not sure if this is a hosting issue or am I doing something wrong.
Any ideas?
if (isset($_SESSION["logged"]) && $_SESSION["logged"]==1){
if ($_POST['action']=="edit"){
$query=mysql_query("select * from page where active=1 AND heading='".$_POST['selectedpage']."'");
$row = mysql_fetch_array($query, MYSQL_ASSOC);
echo "<h1>HTML Editor </h1><br>";
echo "<form name='saveform' action='./action.php' method='post'>";
echo "<textarea rows='100' cols='100' name='updateBox'>".$row['content']."</textarea>";
echo "<br><input name='action' type='submit' value='save edit'>";
echo "<input name='heading' type='hidden' value='".$row['heading']."'>";
echo "</form>";
} else if($_POST['action']=="save edit"){
$query=mysql_query("UPDATE page SET active='0' where heading='".$_POST['heading']."'");
$query=mysql_query("INSERT into page(heading,content,active) values('".$_POST['heading']."','".$_POST['updateBox']."','1')");
echo "<p>Changes saved succesfully!</p>";
echo "$_POST['updateBox']";
}
}
If you call echo mysql_error($query) after each query you run, you will be able to see if there is an error with that query. There could be a problem with your query content.
You are not performing any sanitizing for SQL injection, so if your content has a quotation mark in it, it will break your query. This is fairly dangerous (your queries are vulnerable to SQL injection from user input), and you should consider using mysql_real_escape_string on all your query variables, or switching to the PDO or MySQLi drivers. These drivers support query binding, which is an excellent method to prevent SQL injection.
Edit for editorialism :)
As an aside, it's generally pretty easy to come up with a quick database wrapper or function handler to handle these kind of errors for you automatically. I use a class-based wrapper, but if you didn't want to go that far just now, you could do something like this:
//very quick-and-dirty
function queryOrDie($query)
{
$query = mysql_query($query);
if (! $query) exit(mysql_error());
return $query;
}
You could just pass all your queries through that, and you'd have an easier time of debugging it. There are a lot of database wrapper classes out there too, I'd highly recommend you take a poke around. They make life much easier. :)
What's the error?
At the start of the script add this PHP:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
Also try this:
$query=mysql_query("INSERT into page(heading,content,active) values('".$_POST['heading']."','".$_POST['updateBox']."',1)");
Also :) using data from the POST directly in the insert query is a security threat:
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
Make sure heading is not defined as key or unique. This may cause a problem in your context.
I also had the PHP (INSERT INTO) query not working:
my original query was:
mysql_query("INSERT INTO `videousers` (`user_id`,`user_name`,`user_password`,`contact_person`,`organisation`,`contact_tel`,`email`) VALUES ('','{$user}','{$pass}','{$cperson}','{$organ}','{$cphone}','{$email}'");
it was not working, so I have changed to the following query:
mysql_query("INSERT videousers SET user_name='$user',user_password='$pass', contact_person='$cperson', organisation='$organ', contact_tel='cphone', email='$email'");
and it worked. I don't know why, but since it works, I use this to finish my work.