Variable not working with SQL - php

My issue I believe is fairly simple but after a whole day trying different variations I have resorted to bothering you guys, please excuse me if this has been covered but I could not find a close enough example
I have a php file that is a processing file for a simple html form
Process.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host="1.2.3.4:3306"or die("wrong server"); // Host name
$username="username"or die("wrong Username"); // Mysql username
$password="password"or die("Wrong Password"); // Mysql password
$db_name="db-name"or die("wrong DB"); // Database name
$tbl_name="banned"or die("Wrong table"); // Table name
$member = isset($_REQUEST['member']) ? $_REQUEST['member'] : "";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$find_member = mysql_query("SELECT member FROM banned WHERE member='$member'")or
die(mysql_error());
$ban = mysql_fetch_array($find_member);
if($member == $ban['member']){
echo ("this member is banned");
}
else {
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' style='display:none;' value='<?php echo
htmlspecialchars($member);?'/>'
<button type='submit'>Continue</button>");
}
?>
Form.html:
<form method="post" action="http://example.com/process.php">
<input type="text" name="member">
<input type="submit">
</form>
What im trying to accomplish:
A user would type their member number in the form.html and click submit, process.php will catch POST and either echo the text "this member is banned" or if member number is not on banned sql table, then display a html button with with a hidden input field that will carry the $member variable on to the next page
What is actually happening
no matter what number is entered into the form.html it always displays the html button. there is one number on the blacklist but when entered still displays the button
Error reporting
php and sql error reporting displays no errors
Side note
DB structure
member VARCHAR(20) / id (auto increment) / Time (timestamp - defalt:current time stamp)
The member number is Alphanumeric and is max 15 characters
example: +ayw7394
The initial error of using:
if($member = $ban['member']){
was replaced with:
if($member == $ban['member']){
but produces the opposite effect of echoing the "banned member" message regardless of which number is being inputed
It seems as though the
if statements are being ignored
Can anyone please provide me with some advice?
thank you for your help so far

"no matter what number is entered into the form.html it always displays the html button. there is one number on the blacklist but when entered still displays the button"
The reason being is this:
In this if($member = $ban['member']) you're assigning = instead of comparing == to compare $member against the "member" row.
Change that to if($member == $ban['member'])
I must note that your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Footnotes:
</input> isn't a valid closing tag and can be safely removed.
Edit:
Also this code block:
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' style='display:none;' value='<?php echo
htmlspecialchars($member);?'/>'
<button type='submit'>Continue</button>");
You're already in PHP, so there's no need for the <?php echo and ?>
Change it to:
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' value='".htmlspecialchars($member)."'/>
<button type='submit'>Continue</button>");
Which could explain why it shows "banned" because you're probably re-clicking on it after.
I suggest you just remove it and do a redirection instead.
Example, and by replacing it with the echo'd button:
else{
header("Location: your_form.html");
exit;
}

Your problem is at the line
if($member = $ban['member']){
This is actually always true because you are setting $member to be equal to $ban['member']. Did you mean ?
if($member == $ban['member']){

Echo $member and $ban['member'] to see if they are the same or different value.
Another step, other than guarding against SQL injection like someone else said, would be to run TRIM commands on your input and on your MYSQL fields to ensure spaces aren't an issue.

Related

php code not working as expected form will not submit the correct data

so I've got this code that supposedly sends you an email after you entered a valid one and answered a security question. My problem is the fact that the form won't submit the answer i've given it. It always echoes "submit" on the begging of the second php block. Also if u can spot any other errors i might have missed let me know please. Thanks anticipated.
<?php
define ('DB_SERVER','fenrir');
define ('DB_USERNAME','ArchivrTW');
define ('DB_PASSWORD','vPOZOa1txS');
define ('DB_DATABASE','ArchivrTW');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$connection)
{
die('Could not connect because: ' . mysql_error());
}
?>
<?php
$test = $_POST['email'];
$query = "SELECT 'EMAIL' FROM 'USERS' WHERE 'EMAIL'=$test";
echo(strlen($query));
if(strlen($query) > 42)
{
$query1 = "SELECT 'SecurityQ' from 'USERS' WHERE 'EMAIL' =$test";
$query2 = "SELECT 'SecurityA' from 'USERS' WHERE 'EMAIL' =$test";
$result = mysqli_query($connection,$query);
$result1 = mysqli_query($connection,$query1);
$Results = mysqli_fetch_assoc($result);
$Results1 = mysqli_fetch_assoc($result1);
$Results2 = mysqli_fetch_assoc($result2);
echo($Results1);
}
?>
<form action="recover.php" method="post">
<p>Security Question Answer: <input type="text" name="answer" placeholder="Type your answer here" /> </p>
<p><input type="submit" name="answer" id="answer" /> </p>
</form>
<?php
$answer=$_POST['answer'];
echo($answer);
if (count($Results) >= 1 && strcmp($_POST['answer'],$Results2) == 0)
{
$REQ_STATUS = 1;
$new_passwd = rand(1,1000000);
$to = $email;
$subject = "Archivr-Forgot Password";
$msg = "Use this generated password to log in then change it using the Edit Profile Menu";
mail($to, $subject, $msg);
}
else
{
$message="Account not found or wrong security question answer";
}
if($REQ_STATUS == 1)
{
$update_query="UPDATE USERS set PASSWORD =".$new_passwd." where EMAIL ='". $to ."'";
}
?>
</body>
</html>
The first block works, problem is the form or the second block.
You are vulnerable to sql injection attacks;
You have duplicate field names:
<p>Security Question Answer: <input type="text" name="answer" placeholder="Type your answer here" /> </p>
^^^^^^^^^^^^
<p><input type="submit" name="answer" id="answer" /> </p>
^^^^^^^^^^^^^
Since the field names are the same, the submit button overwrites/replaces the text field, and you end up submitting a blank value.
You're using the incorrect identifier qualifiers for all your tables and columns being single quotes and not wrapping the $test variable in quotes; it's a string.
This one for example:
SELECT 'EMAIL' FROM 'USERS' WHERE 'EMAIL'=$test
should read as
SELECT `EMAIL` FROM `USERS` WHERE `EMAIL`='$test'
where you may have seen a tutorial somewhere, that the ticks resembled regular single quotes. They are not the same; those are two different animals altogether.
You will then need to follow the same method above and do the same for the rest of your queries.
Using this for example:
$result = mysqli_query($connection,$query) or die(mysqli_error($connection));
would have signaled a syntax error.
Then this mysql_error() - That should read as mysqli_error($connection). You cannot mix MySQL APIs. They do not intermix with each other.
You also don't seem to be doing anything with:
$update_query="UPDATE USERS set PASSWORD =".$new_passwd." where EMAIL ='". $to ."'";
Whether it's relevant to the question or not, you're not actually executing that query.
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.
References:
https://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
http://php.net/manual/en/mysqli.error.php
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Plus, since you're using the entire code in one file, you will get warnings to the effect of "Undefined index xxx....", therefore you will need to use a conditional isset() and or !empty() around your executable code and for the POST arrays.
Passwords:
I'm hoping you're using a modern-day password hashing method, since this looks to me, being related to resetting passwords.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Both your form field and your submit button have a name of "answer". Rename your submit button name to "submit" or something else.

Struggling with UPDATE in MySQL

Beginner here.
The issue I am facing is getting rather tedious now despite me doing this a hobby, I have been stuck at this point for the last few days and have tried searching everywhere for a solution.
I have even completely reworking the code I have, following other examples/tutorials.
This is the closest I get to.
Everything is filled out, form submitted. It states successful but when I return back to the page, the field hasn't been updated. I have even checked the database directly to ensure the output display isn't wrong. But it doesn't appear there either.
(I do have other entries in the table, but I only want this page to edit one of them).
Any help pointing me to my error and why would be greatly appreciated. Best to learn where I have gone wrong so I can look out for it in the future.
<?php
$host="****"; // Host name
$username="****"; // Mysql username
$password="****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="****"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id from the address bar
$id=$_GET['id'];
// get value of modname from the form
$modname=$_POST['modname'];
// update data in mysql database
$sql = "UPDATE $tbl_name SET modname='$modname' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='edit.php'>Return to overview</a>";
}
else {
echo "ERROR";
}
?>
The page with the form.
<?php
$host="****"; // Host name
$username="****"; // Mysql username
$password="****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="****"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
// Retrieve data from database
$sql="SELECT modname FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<form name="form1" method="post" action="update_ac.php">
<input name="modname" type="text" id="modname"></td>
<br>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
<br>
<input type="submit" name="Submit" value="Submit">
</form>
In this case, your query is solid and syntax is correct, but your variables don't contain the values you are expecting. Since you are learning, I'd like to offer some advice and example code.
While your code is still somewhat simple, change to the mysqli API. The syntax is similar but it is not depracated like mysql and you can use prepared statements.
When in the development stage, always turn on error reporting for your functions/conditions.
ALWAYS be sure to verify that your variables contain the values you are expecting before you try to use them with isset(), empty(), etc.
Always validate/sanitize/escape user input before inserting into your database.
Sample:
So it seems you are getting the id from a query string initially, such as http://domain.com/get_id.php?id=1? If so, your code should work, just make sure your URL is formed properly. If you are getting the id here from your <form>, then it should be $_POST instead.
// get value of id from the address bar
if(!empty($_GET['id'])) {
$id=$_GET['id'];
} else {
echo "ID is empty";
}
// get value of modname from the form
if(!empty($_POST['modname'])) {
$modname=$_POST['modname'];
} else {
echo "ID is empty";
}
// update data in mysql database
$sql = "UPDATE $tbl_name SET modname='$modname' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='edit.php'>Return to overview</a>";
}
else {
echo mysql_error();
}
On your form, you need to select the id before you will be able to echo it.
// Retrieve data from database
$sql="SELECT id,modname FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<form name="form1" method="post" action="update_ac.php">
<input name="modname" type="text" id="modname"></td>
<br>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
<br>
<input type="submit" name="Submit" value="Submit">
</form>
Even though your id field is a hidden field in your form it is still sent as a POST attribute, so you need $_POST['id'] to retrieve the value (not $_GET['id']).
Also, you should put table and column names in ` commas, like this;
$sql = "UPDATE `$tbl_name` SET `modname`='$modname' WHERE `id`='$id'";
However, your code is also wide open to SQL injection. Read this question and rewrite your code.
This should fix your issue.
$sql = "UPDATE {$tbl_name} SET modname='{$modname}' WHERE id='{$id}'";
Hope it helps!

Check existence of a record in MySQL(with PHP)?

I made a small database(1 table) in phpMyAdmin. One of the fields I want to check is "Name".
I want to verify through PHP if a name that user types in a form exists in the database. In the html a list of names from DB appears, but the user might type wrong the name in the form.
The problem is the answer whether it exists or not varies.
I have 2 PHP files:
Connection.php and welcome.php
Connection
<html>
<head>
<title>Project</title>
</head>
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("e-card");
$sql=mysql_query("SELECT * FROM person");
$dbname="name";
#$formula_adr="formula_adr";
#$adress="adr";
$line=mysql_fetch_assoc($sql);
echo'Choose a name to whom you send e-card:<br/><br/>';
echo $line[$dbname].'<br/>';
while($line=mysql_fetch_assoc($sql))
echo $line[$dbname].'<br/>';
?>
<form action="welcome.php" method="POST">
Nume: <input type="text" name="fname" />
<input type="submit" value="Verify existance in DB"/>
</form>
</body>
</html>
And welcome:
<?php
mysql_connect("localhost","root","");
mysql_select_db("e-card");
$sql=mysql_query("SELECT * FROM persoana");
$dbname="name";
$formula_adr="formula_adr";
$adresa="adr";
$linie=mysql_fetch_assoc($sql);
if ($_SERVER['REQUEST_METHOD']=='POST' and isset($_POST['fname']))
{
$name = $_POST['fname'];
while($line=mysql_fetch_assoc($sql))
{
if(strcmp($name,$line[$dbname]))
{
echo 'Found';
}
else
{
echo 'This name doesn't exist in DB';
}
}
}
?>
THANK YOU IN ADVANCE ^_-
<?php
mysql_connect(HOST, USERNAME, PASSWORD);
mysql_select_db(DB_NAME);
if($_POST) {
$name = $_POST['fname'];
// check if name exists in db
$sql = "SELECT name FROM person WHERE name=' . mysql_real_escape_string($name) . '";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) {
// user exists
} else {
// user does not exist
}
}
The above script will work and will also protect your script against SQL injection by using the built-in mysql_real_escape_string method. I would also recommend against using a wildcard (*) selector when verifying data in this manner as it's a waste of resources to query any additional information that is unused.
Don't get all data from the table to compare for a name.
Do it this way:
$sql=mysql_query("SELECT * FROM persoana where name like '$name%'");
You will get result only if you have a match
I would follow these steps high level steps.
1 - use javascript to initially check on client side that something was entered BEFORE calling the DB. You can use a filter in your javascript to check that form field.
2 - If you verify that something *useful was entered - pass the form field value to another page or object that will parse the value and then query the table.
3 - Use the parsed value against the db table column that contains your data. If records are found, return them.
Use a SQL injection technique to prevent malicious intend by users who may type something evil into your form field.

Display usernames at random

I’m trying to create a script for a user to enter in their username, and then have other logged in usernames randomly show, in a chatroulette fashion.
So, you will enter in your name and hit submit, then your name will be stored in a database and someone else’s name will be pulled out at random and shown. Then the user can hit a next button to see another random user name. When the user closes the page, their name will be unloaded from the system.
What I have tried is creating a simple post submission form which will return you to the same page logged in with your name, and it inserts your name into a mysql database. That worked.
Then I added some PHP code to detect that the name variable has been set and to find a random username in the database by finding the amount of users in the database and using a random integer to pick one out. I’m pretty sure it worked, however I was unable to get the user name to show with echo "$name";.
Then I tried adding an automatic logout by using:
<body onUnload=<?php session_destroy();?>>
That didn’t work. I didn’t get around to creating a next button because I was having a few problems, because I figured out that the logout wouldn’t work because I would be dropping rows from the database that wouldn’t be filled in again as new rows were added to the SQL database with an auto increment function causing blank pages to be shown.
Here is my code:
<html>
<head>
<title>random name</title>
</head>
<body>
<center>
<h1>random name</h1>
<h5>By DingleNutZ</h5>
</center>
<?php
if (!isset($_POST['name'])){
echo "<form action=\"index.php\" method=\"POST\" name=\"form\"><center><h4>name:</h4><input name=\"name\" id=\"name\" type=\"text\"/><br/>
<input type=\"submit\" name=\"submit\" value=\"Play!\"/></center></form>";
}else{
$name = $_POST['name'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="ftr"; // Database name
$tbl_name="players"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// To protect MySQL injection (more detail about MySQL injection)
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$sql="SELECT * FROM $tbl_name WHERE name='$name'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
session_register("name");
session_start();
if(session_is_registered(name)){
$players=mysql_query("SELECT MAX (id) FROM $tbl_name");
$chooserand=rand(1,$players);
$callee=mysql_query("SELECT name FROM $tbl_name WHERE id=$chooserand");
echo "$callee";
echo "Logout";
if (isset($playing)){
if ($playing == 1){
$drop_name=mysql_query("DELETE FROM $tbl_name WHERE name=$name");
}}
}
}
echo "show random name here";
}
?>
</body>
</html>
There is a variable in there called $playing which was an attempt at a logout system.
I would be very grateful for any answers. Many thanks in advance.
as i didnt make it obvious (sorry guys) i need to fix my main problem which is being able to show a random user without ever showing a blank page due to the rows being dropped from the database. it is essential that usernames are removed from the system for privacy
You have a few issues in your code, not all are errors as such, some code is unneeded, other code is potentially dangerous.
$name = stripslashes($name); <<-- delete this line.
$name = mysql_real_escape_string($name); <<-- this is all you need.
mysql_real_escape_string() is all you need. No other escaping is need to protect against SQL-injection.
A few caveats apply, which I will discuss below.
$sql="SELECT * FROM $tbl_name WHERE name='$name'";
$result=mysql_query($sql);
Select * is an anti-pattern, never use it in production code. Explicitly select the fields you need.
You are using dynamic tablenames, I fail to see the need for this and it's also a dangerous SQL-injection hole.
Never use it but if you must, see this question how to secure your code: How to prevent SQL injection with dynamic tablenames?
You do the query, but you don't test if it succeeds, put a test in there:
$sql = "SELECT id FROM users WHERE name='$name' ";
$result = mysql_query($sql);
if ($result)
{
$row = mysql_fetch_array($result);
$user_id = $row['id'];
}
else { do stuff to handle failure }
You are trying to get data out of the database, but this is not the way to do it:
$players = mysql_query("SELECT MAX (id) FROM $tbl_name");
$chooserand = rand(1,$players);
$callee = mysql_query("SELECT name FROM $tbl_name WHERE id=$chooserand");
echo "$callee";
But I see a few issues:
Please stop using dyname tablenames, it is a really bad idea.
The return value of mysql_query is a query_handle, not the actual data you're quering.
I would suggest escaping all values, whether from outside or inside your code; I know this is paranoid, but that way, if you code design changes, you cannot forget to put the escaping in.
Never ever ever echo unsanitized data in an echo statement.
If you echo a $var, always sanitize it using htmlentities. If you don't XSS security holes will be your fate.
See: What are the best practices for avoiding xss attacks in a PHP site
rewrite the code to:
$result = mysql_query("SELECT MAX (id) as player_id FROM users");
$row = mysql_fetch_array($result);
$max_player = $row['player_id'];
$chooserand = mysql_real_escape_string(rand(1,$max_player));
//not needed here, but if you change the code, the escaping will already be there.
//this also makes code review trivial for people who are not hep to SQL-injection.
$result = mysql_query("SELECT name FROM users WHERE id = '$chooserand' ");
$row = mysql_fetch_array($result);
$callee = $row['name'];
echo "callee is ".htmlentities($callee);
Finally you are deleting rows from a table, this looks like a very strange thing to do, but it is possible, however your code does not work:
$drop_name = mysql_query("DELETE FROM $tbl_name WHERE name=$name");
As discussed mysql_query does not return values.
On top of that only a SELECT query returns a resultset, a DELETE just returns success or failure.
All $vars must be quoted, this is a syntax error at best and an SQL-injection hole at worst.
Technically integers don't have to be, but I insist on quoting and escaping them anyway, because it makes your code consistent and thus much easier to check for correctness and it elimiates the chance of making errors when changing code
Rewrite the code to:
$drop_name = $name;
$result = mysql_query("DELETE FROM users WHERE id = '$user_id' ");
//user_id (see above) is unique, username might not be.
//better to use unique id's when deleting.
$deleted_row_count = mysql_affected_rows($result);
if ($deleted_row_count == 0)
{
echo "no user deleted";
} else {
echo "user: ".htmlentities($drop_name)." has been deleted";
}

Insert Into - php mysql

HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.

Categories