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.
Related
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!)
I am adding some server-side form validations (using php) in case one of the users of my site has javascript turned off. On one form, there are 10 separate input fields that can be changed. Could someone please tell me which protocol will use less system resources? In the first, I write some mySQL variables to check the user's current settings, and compare these with the posted settings. If all 10 posted values are identical to the current values, don't UPDATE database, else UPDATE the database:
$login_id = $_SESSION['login_id'];
$sql1 = mysql_fetch_assoc(mysql_query("SELECT value1 FROM login WHERE login_id =
'$login_id'"));
$sql1a = $sql1['value1'];
// Eight More, then
$sql10 = mysql_fetch_assoc(mysql_query("SELECT value10 FROM login WHERE login_id =
'$login_id'"));
$sql10a = $sql10['value10'];
$Value1 = $_POST['Value1'];
// Eight More, then
$Value10 = $_POST['Value10'];
//Other validations then the following
if (($sql1a == $Value1)&&($sql2a == $Value2)&&.......($sql10a == $Value10)) {
echo "<script>
alert ('You haven't made any changes to your profile');
location = 'currentpage.php';
</script>";
}
else {
$sqlUpdate = mysql_query("UPDATE login SET value1 = '$Value1',....value10 = '$Value10'
WHERE login_id = '$login_id'");
echo "<script>
alert ('Your profile has been updated!');
location = 'currentpage.php';
</script>";
}//End php
OR is it less expensive to just use the user-posted values (keep the $_POST variables) and avoid checking with the comparison line: (($sql1a == $Value1)&&($sql2a == $Value2)&&.......($sql10a == $Value10)) and just go right to
//Other validations then the following
$sqlUpdate = mysql_query("UPDATE login SET value1 = '$Value1',....value10 = '$Value10'
WHERE login_id = '$login_id'");
echo "<script>
alert ('Your profile has been updated!');
location = 'currentpage.php';
</script>";
Thanks for any input on this!
If I understand correctly, your question is whether it's OK for performance to check the profile for modifications. For me, after I've checked your code, this is about much more than just performance...
Let's start with the performance: AFAIK MySQL queries are slower than basic PHP comparisions, that's true - but on this scale, I really don't think it matters much. We're talking about two very basic queries which won't handle a lot of data.
Let's think about what the end user will see (UX): in the second scenario, the user will not have the most exact feedback telling him/her that no modification has been done. On a profile modification screen, I suppose that might not be intentional, so I would tell that we haven't modified anything. (Also, performing an unnecessary UPDATE query is not the most elegant.)
#aehiilrs is right, please pay attention to that comment. This style of MySQL usage is particularly bad for security - if you keep going with this, you will create a lot of security holes in your PHP code. And those are really easy to discover and exploit, so please, have a good look on the alternatives, starting with PDO as mentioned. Any good PHP book out there will show you the way. You can also have a look at a great Q/A here on StackOverflow: How can I prevent SQL injection in PHP?
I wonder whether it's a good idea to try to update the user interface like you did - I would strongly prefer loading another PHP without any <script> magic in the output. In the result PHP, you can always display something like a CSS-styled statusbar for displaying info like that.
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
I'm using the following query to pull records from a database:
$query = "SELECT password, salt, 'jobseeker' as type
FROM ip_jobseekers
WHERE ipJ_username = '$username'
UNION
SELECT password, salt, 'company' as type
FROM ip_companies
WHERE ipC_username = '$username';";
$result = mysql_query($query);
//No Such User
if (mysql_num_rows($result) < 1) {
header('Location: login.php?login=fail'); exit;}
to create a new session:
//login successful
else {$_SESSION['user'] = $username;}
I want to include the type of user in the session so that I can specify what content is displated to the user. Is it possible to make use of the "'company' as type" and "'jobseeker' as type" parts of that query to do this? I've make a few attempts at doing it but I've had no success.
Any help would be greatly appreciated.
Thanks.
Kai.
There is absolutely no difference between "regular" and aliased fields. You can use the latter as well as any other.
to find any error in your query you can run the query like below
$result = mysql_query($query) or trigger_error(mysql_error()." ".$query);
for testing you can use above and you ca redirect to custom error page in production environment.
My personal suggestion is to use PDO. make use of Object oriented Programs to run your code faster and to have standard structure.
First of all, you're using the mysql_ set of functions, which are highly dangerous, and you should move over all your code from ASAP.
Next, you should NOT be stringing up queries like this, because your application will grow into this behemoth of SQL everywhere (in the HTML, in the Views, EVERYWHERE), you should probably be using some kind of class/object system where you wrap around the SQL.
And, you should know about the SQL AND clause (I feel horrible linking w3schools, but, that's all I can find right now).
I'm still new to php and working my way around it but i'm stuck at the following piece:
code for deleting a row in my table
i have a link directing towards this piece of my script. i run through the first half just fine but when i press on submit and try to execute my delete query it won't go to my second if statement let alone get to the delete query.
$pgd is the page id
my hunch is there is problem with the action in the form i'm building after my while statement
forgive me for the wierd formatting of my msg but its 2am and very tired, i promise to format my questions in the future better! any help is appreciated
edit: ok other then the obvious mistake of missing method=post #.#;
edit:
hey everyone,
first of all, i'd like to thank everyone for their response.
i just started coding in php last weekend so forgive my messy codes. the code is still running locally and my main goal was to finish the functions and then work on securing my code.
now back to the issue, i'm sorry if i was vague about my problem. i'll try to reiterate it.
my issue isn´t selecting an item i want to delete, the issue is that it won´t get to the 2nd if statement.
Re-edit:
this time with my current code:
if($_GET['delete'] == "y")
{
//content hier verwijderen
$sqlcont1="SELECT * FROM content where id ='".$_GET['id']."'";
echo $sqlcont1;
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while($rowcont1= mysql_fetch_array($resultcont1)){
echo '<form class="niceforms" action="?pg='.$pgd.'&delete=y&remove=y&id='.$_GET['id'].'" method="post">';
echo '<h1>'.$rowcont1['Titel'].'</h1>';
echo '<p>'.$rowcont1['Content'].'</p>';
echo '<input type="submit" value="Delete article">';
echo '</form>';
}
if($_GET['remove']=="y"){
echo 'rararara';
$id=$_GET['id'];
$sqlrem="DELETE FROM content WHERE id="$id;
echo $sqlrem;
mysql_query($sqlrem);
}
}
echoing $sqlrem gives me the following now:
DELETE FROM content WHERE id=8
that being my current code, i get in to the second IF statement but now to get it to delete!
#everyone:
ok maybe thinking out loud or following my steps worked but the code works, i know its very messy and it needs fine tuning. i'd like to thank everyone for their help and feedback. i'm liking this and you'll probably see me alot more often with nubby questions and messy codes with no escapes :(
First of all, you have SQL injection vulnerability in your script. Anyone can add some string that will be attached to your query, possibly altering it in a way that can make almost anything with the data from your database.
Escape your values with one of anti-SQL-injection methods. Read more for example on php.net/manual/en/function.mysql-query.php
To the point...
Your deletion code will be executed only if you invoke URL with two params (remove and delete set to y. That means your URL should look similar to something.php?delete=y&remove=y. Maybe you just did not spot it.
Please give details about any errors that occured and tell me whether the above mentioned solution helped.
mysql_fetch_array() returns an array
your while statement acts as an if, and does not iterate thru the array returned as you think it does
you need something like
$all_rows = mysql_fetch_array($result);
foreach ($all_rows as $row) {
$sql = "delete from table where id = " . $row['id'];
}
It looks to me like you're mixing two forms together here: you're wanting to see if you went to the delete row form (the first few lines), and you're trying to present the delete row form (the while loop.) I would break these two things apart. Have a page that simply displays your forms for row deletes, and another page that processes those requests. And another page that brings you to the delete rows page.
For now, just echo all the values you're expecting to receive in $_GET[] and see if they are what you expect them to be.
You have a lot of problems in that script alone, so just to make things easier (considering you uploaded a pic), put an
echo $sqlrem;
in your second if statement, see if the query is displayed. If not, it means it doesn't even get to that part of code, if it gets displayed, copy it and run it in phpmyadmin. That should output a more coherent error message. Tell us what that is and we'll work it through.
I also noticed that your DELETE SQL query might have an issue. If your $pgd' id is a integer, you shouldn't include the ' single quote, that is for string only.
**Correction**
$sqlrem = "DELETE FROM content WHERE id = " . controw1['id'];
EDIT
Anyway, just to help out everyone, I typed out his code for easier viewing.
I think his error is $rowcont1['Tilel'] --> that might caused PHP to have an error because that column doesn't exist. I assumed, it should be `Title' causing an typo error.
if(_$GET['delete'] == "y") {
$sqlcont1 = "SELECT * FROM content where id ='" . $_GET['id'] . "'";
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while ($rowcont1 = mysql_fetch_array($resultcont1)) {
echo '<form class = "niceforms" action = "?pg=' .$pgd . '&delete=y&remove=y">';
echo '<h1>' . $rowcont1['Title'] . '<h1>'; // <-- error here
echo '<p>' . $rowcont1['Content'] . '</p>';
echo '<input type = "submit" value = "Delete article">';
echo '</form>';
}
if ($_GET['remove'] == "y"){
$sqlrem = "DELETE FROM content WHERE id = " . $rowcont1['id'];
mysql_query ($sqlrem);
}
}