I am making a dynamic web page that allows people to post their favorite recipes. Below each recipe is a link that allows you to make a comment on the recipe. If you make a comment, the comment will be posted in the database UNLESS the comment has any apostrophes in it. Here's the code for the addcomment.inc.php page:
<?php
$con = mysql_connect("localhost", "test", "test") or die('Sorry, could not connect to database server');
mysql_select_db("recipe", $con) or die('Sorry, could not connect to database');
$recipeid = $_GET['id'];
$query = "select title from recipes where recipeid = $recipeid";
$result = mysql_query($query) or die('Could not retrieve file: ' . mysql_error());
echo "<form action=\"index.php\" method=\"post\">\n";
if (mysql_num_rows($result) == 0) {
$title = "Unknown Title";
}
else {
while($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
$title = $row['title'];
}
}
echo "<h2>Enter your comment for the recipe \"$title.\" </h2>";
echo "<textarea rows=\"10\" cols=\"50\" name=\"comment\"></textarea><br>\n";
echo "Submitted by:<input type=\"text\" name=\"poster\"><br>\n";
echo "<input type=\"hidden\" name=\"recipeid\" value=\"$recipeid\">\n";
echo "<input type=\"hidden\" name=\"content\" value=\"addcomment\">\n";
echo "<br><input type=\"submit\" value=\"Submit\">\n";
echo "</form>\n";
?>
A different php file called addcomment.inc.php retrieves the information. This is the code below:
<?php
$recipeid = $_POST['recipeid'];
$poster = $_POST['poster'];
$comment = htmlspecialchars($_POST['comment']);
$date = date("Y-m-d");
$con = mysql_connect("localhost", "test", "test") or die('Could not connect to server');
mysql_select_db("recipe", $con) or die('Could not connect to database');
$query = "INSERT INTO comments (recipeid, poster, date, comment) " .
" VALUES ($recipeid, '$poster', '$date', '$comment')";
$result = mysql_query($query) or die('Could not query databse. ' . mysql_error());
if ($result)
echo "<h2>Comment posted</h2>\n";
else
echo "<h2>Sorry, there was a problem posting your comment</h2>\n";
echo "Return to recipe\n";
?>
How can I make this code properly handle single quotes if inputted into a comment form?
Before you glue anything into the MySql query pass it through mysql_real_escape_string()
Before you glue anything into HTML pass it through htmlspecialchars()
This way you can prevent SQL injections, JavaScript/HTML injections and wildfires.
You have to use mysql_real_escape_string()
$comment = mysql_real_escape_string($_POST['comment']);
You have to escape the input when you pass it on to MySQL with mysql_real_escape_string(), to avoid that the user can perform an SQL injection and do stuff evil with your database.
Example:
// wrong
$query = "select title from recipes where recipeid = $recipeid";
// correct
$query = "select title from recipes where recipeid = " . mysql_real_escape_string($recipeid);
You also have to escape the output when you pass it on to the browser with htmlspecialchars() (or urlencode() in URLs), otherwise someone could insert some malicious HTML or JavaScript code in your database, and then attack your other users with a XSS attack.
Example:
// wrong
echo "<input type=\"hidden\" name=\"recipeid\" value=\"$recipeid\">\n";
echo "Return to recipe\n";
// correct
echo "<input type=\"hidden\" name=\"recipeid\" value=\"" . htmlspecialchars($recipeid) . "\">\n";
echo "Return to recipe\n";
Related
Essentially I want to:
pull info from mySQL server
create a table of students with their name, phone number, and exam date
I want a checkbox next to each student pulled from mySQL and when the checkbox is clicked and the user hits submit, it inserts a value into mySQL column 'contacted'under that specific student. The value will either be "yes" or "NULL"
I used primary key (id) which auto increments to create unique checkbox names for each student
application: The user will retrieve a table of our students and their exam dates. The user will call (via phone) the students and ask about their exam. Once the user has contacted that student, they check the checkbox to show that that particular student has already been contacted. That information will be stored in mySQL for that particular student to show that student was contacted.
here is my code:
<?php
define('DB_NAME', 'Students');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
$sql = sprintf("SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
$result = mysql_query($sql);
$table_count = 0;
$student_id = array();
echo "<script>
function DoTheThing()
{
" .
for($x = 0; $student_id[$x] != NULL; $x++)
{
$in = sprintf("INSERT INTO Student_data (contacted) VALUES ('". $_POST[$row['id']] ."') WHERE id = '" . $row['id'] . "';" );
$db_selected->mysql_query($in)
}
. "
}
</script>";
echo "<table width= 400 border=1><form action=\"DoTheThing()\" method=\"POST\">
<tr>
<th width='175' scope='col'>Name</th>
<th width='150' scope='col'>Phone</th>
<th width='125' scope='col'>Exam Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><center>" . $row['f_name'] . " ". $row['l_name']. "</center></td>";
echo "<td><center>". $row['phone'] ."</center></td>";
echo "<td><center>". $row['exam_date'] ."<input type=\"checkbox\" name=\"" . $row['id'] . "\" value=\"yes\"></center></td>";
echo "</tr>";
$student_id[$table_count] = $row['id']
$table_count = +1;
}
echo "</form></table>
<br/><br/><input style = \"height:35px;width:95px;font-size:20px;\" type=\"submit\" name=\"submit\" value=\"Submit\">
";
mysql_close($link);
?>
edit: Sorry, realized I never posted my question
It stopped working when I attempted to insert the "yes" or "NULL" value into mySQL. I am very new to mySQL and was wondering if any of my statements were wrong.
This should be a very big boost of help, basically a shell. All that is left to do is inserting the data into your SQL server.
I commented the code so you could see what was going on, when, and where.
Also, you should definitely stay AWAY from mysql_* as it's deprecated. My example was made using mysqli_*. Another options would be PDO.
<?php
//Set variables (Can be done on another file for more security)
$Host = "Localhost";
$User = "admin";
$Pass = "password";
$DB = "Students";
//Connect to the databse using mysqli. NOT MYSQL WHICH IS DEPRECATED
$con = mysqli_connect($Host, $User, $Pass, $DB);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//if submitted
if(isSet($_POST['submit'])) {
//submit data using mysqli_query and then reload the page.
//clear POST variables before you reload the page.
unset($_POST);
//reload the page
echo "<META http-equiv='refresh' content='0'>";
} else { //if not submitted
//define search variable, and query it.
$db_selected = mysqli_query($con, "SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
//Start table
echo "<form method='POST'>";
echo " <table>";
echo " <tr>";
echo " <th>Name</th>";
echo " <th>Phone</th>";
echo " <th>Exam Date</th>";
echo " <th></th>";
echo " </tr>";
//Loop through sql database
while($row = mysqli_fetch_array($check)) {
echo " <tr>";
echo " <td>".$row['f_name']." ".$row['l_name']."</td>";
echo " <td>".$row['phone']."</td>";
echo " <td>".$row['exam_date']."</td>";
echo " <td><input type='checkbox' name='checkbox['".$row['id']."']' value='1'></td>";
echo " </tr>";
}
//end table
echo " </table>";
echo "<input type='submit' value='Submit' name='submit'>";
echo "</form>";
}
?>
management.php is the code which get information in php by a table.
And managementdel.php is the code which del the information.
I use mysql_fetch_array to show all data,and beside every information have a herf to delete
echo data in database.
When I del ,there no error inside.but database information haven't delete.
management.php
$con1 = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql1 = "Select LoginID , Password , Permission
from loginacc where Permission = 2 ";
$results = mysql_query($sql1,$con1);
echo "<tr><th>會員帳號</th></tr>";
echo "<table border=5 cellpadding=10>";
echo "<tr><th></th><th>帳號</th><th>密碼</th><th>權限</th><th></th><th></th></tr>";
while($row = mysql_fetch_array($results)) {
echo "<tr><td>
<a href='searchtable.php?lid=$row[0]'>get information</a></td><td>$row[0]</td><td><input type=text id='row1' name='row1' value='$row[1]' /></td>
<td>$row[2]</td><td>
<a href='searchtable.php?lid=$row[0]'>Change</a></td><td>
<a href='managementdel.php?lid=$row[0]'>Delete</a></td></tr>";
}
echo "</table>";
managementdel.php
<?php
$ac = $_GET['rowname'];
$con = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql = "delete from loginacc where LoginID = '$ac'";
if(mysql_query($sql))
{
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
else
{
echo 'fail!';
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
echo mysql_error()
?>
There is so much stuff wrong with your script, I won't address it all. What I will do is answer your question that you asked which is: "Why it won't delete from database."
What is wrong in your script:
Using depreciated mysql_* library (See notes below)
Using meta refresh to redirect instead of something like header('Location: link');
Not sanitizing user input -> $_GET['lid'].
Posting user password in the table. (Hopefully not being stored as plaintext)
As stated, you're trying to get:
$_GET['rowname']
When you are sending lid -> managementdel.php?lid=$row[0]. You have to change that to:
$ac = $_GET['lid'];
NOTES
Please stay away from mysql_* functions as the library is depreciated.
Use either of the following two instead:
PDO
Mysqli Prepared Statements
And if you aren't going to do that, atleast try and sanitize your user inputs to prevent SQL Injections.
Using functions like intval() and mysql_real_escape_string() will help you but won't be as comprehensive as PDO/mysqli.
in managementdel.php file instead of
$ac = $_GET['rowname'];
there should be
$ac = $_GET['lid'];
Try
management.php
<?php
$con1 = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql1 = "Select LoginID , Password , Permission
from loginacc where Permission = 2 ";
$results = mysql_query($sql1,$con1);
echo "<tr><th>會員帳號</th></tr>";
echo "<table border=5 cellpadding=10>";
echo "<tr><th></th><th>帳號</th><th>密碼</th><th>權限</th><th></th><th></th></tr>";
while($row = mysql_fetch_array($results)) {
echo "<tr><td>
<a href='searchtable.php?lid= " . $row[0] . "'>get information</a></td><td>" . $row[0] . "</td><td><input type=text id='row1' name='row1' value='" . $row[1] . "' /></td>
<td>" . $row[2] . "</td><td>
<a href='searchtable.php?lid=" . $row[0] . "'>Change</a></td><td>
<a href='managementdel.php?lid=" . $row[0] . "'>Delete</a></td></tr>";
}
echo "</table>";
?>
managementdel.php
<?php
$ac = $_GET['lid'];
$con = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql = "delete from loginacc where LoginID = '$ac'";
if(mysql_query($sql))
{
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
else
{
echo 'fail!';
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
echo mysql_error()
?>
Ok, so I basically have an HTML form that consists of a hidden input and a submit button. When the button is pressed it will remove a specific row in my MySQL table. The code all actually does the function it should. However, I keep getting a syntax error displaying when I run it. Once I get the error, if I go back the row is gone, which is what I want. I am just not sure how to make it redirect after running like it should, rather than getting the error.
The error:
Error: 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 '1' at line 1
Line 1 seems fine to me (hence the confusion).
The PHP code that is running(campaignPostDelete.php):
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$postID = $_POST['postID'];
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID=" . $postID);
if (!mysqli_query($con,$delete))
{
die('Error: ' . mysqli_error($con));
}
header("Location: index.php");
die();
mysqli_close($con);
?>
the HTML form with PHP in case it's needed:
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$campaignID = $_SESSION['campaignID'];
$result = mysqli_query($con,"SELECT posts.postID, posts.postDate, posts.postName, posts.postEntry FROM posts
INNER JOIN campaigns ON posts.campaignID= $campaignID
AND posts.campaignID= campaigns.campaignID ORDER BY postDate desc");
while($row = mysqli_fetch_array($result))
{
echo "<div id='campaignPostContainer'>";
echo "<ul class='campaignPostBox'>";
echo "<p class='postInfo'>";
echo "<form name='postDelete' action='campaignPostDelete.php' method='post'>
<input type='hidden' name='postID' value=" . $row['postID'] . ">
<input type='submit'>
</form>";
echo "Posted on:";
echo "<li>" . $row['postDate'] . "</li>";
echo "</p>";
echo "<p class='postInfo'>";
echo "Posted by:";
echo "<li>" . $row['postName'] . "</li>";
echo "</p>";
echo "<li class='postEntry'>" . $row['postEntry'] . "</li>";
echo "</ul>";
echo "</div>";
echo "<hr>";
}
mysqli_close($con);
?>
You are enclosing the ID in single quotes. It is an integer so shouldn't be enclosed in quotes.
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID='$postID'");
should be:
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID=$postID");
However, you are also passing the connection string twice. So instead do this:
$delete = "DELETE FROM posts WHERE postID=$postID";
if (!mysqli_query($con, $delete))
{
die('Error: ' . mysqli_error($con));
}
But this still leaves you vulnerable to SQL injection. Do at least this to improve this overall:
$delete = sprintf("DELETE FROM posts WHERE postID=%s", mysql_real_escape_string($postID));
if (!mysqli_query($con, $delete))
{
die('Error: ' . mysqli_error($con));
}
You'll also want to sanitize your other inputs.
I have to following form
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM novinky";
$result = mysqli_query($connection, $sql);
echo "<div id='newsbox'>";
while($zaznam = mysqli_fetch_row($result)):
echo "<form class='newsholder'>";
echo "<input id='displaynadpis' value='$zaznam[1]'>";
echo "<input id='displaybold' value='$zaznam[2]'>";
echo "<textarea id='displaytext'>$zaznam[3]</textarea>";
echo "<div class='buttonsholder'>";
echo "<button class='deletebutton'>Smazat</button>";
echo "<button class='updatebutton'>Upravit</button>";
echo "<input id='prime' type='hidden' attr='id' value='$zaznam[0]'>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
echo "</div>";
mysqli_close($connection);
that displays data from the database in order to update them upon the .updatebutton click.
The data is passed by jquery ajax
$('.updatebutton').on('click', function(){
var idVal = $(this).closest('.newsholder').find('#prime').val();
var displaynadpisVal = $(this).closest('.newsholder').find('#displaynadpis').val();
var displayboldVal = $(this).closest('.newsholder').find('#displaybold').val();
var displaytextVal = $(this).closest('.newsholder').find('#displaytext').val();
alert(displaynadpisVal);
$.ajax({url:"updaterecord.php",
type:"POST",
cache:false,
data:{id: idVal, displaynadpis: displaynadpisVal, displaybold: displayboldVal, displaytext: displaytextVal}
}); });
to the php script
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$updatenadpis = $_POST['displaynadpis'];
$updatetextbold = $_POST['displaybold'];
$updatetext = $_POST['displaytext'];
echo $updatetext;
$sql = "UPDATE novinky SET nadpis='$updatenadpis',
textbold='$updatetextbold',
text='$updatetext'
WHERE id = '$id'"
;
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_connect_error());
}
echo "Entered data successfully\n";
mysqli_close($connection);
to update the database. The problem is, that it only works sometimes, but in about 70% of cases it doesn't make any change. The data is stored in js variables just fine, when tested by alert(), they exist everytime. So the problem must be in the mysqli_query() possibly? Or the AJAX method? I have tried a lot of options and recommendations from other posts but no luck. Thanks for your help...
Biggest problem here is fact that you are passing raw user input to query. Assigning it to variable doesn't change anything!
You should filter everything received from user and use prepared statements to be sure that you are safe.
Also don't use mysqli_connect_error() to check query errors. Use mysqli_error().
I've got a query that displays a table with information about a message, I also have a column that gives the option to select the messages that the user wants to delete with a checkbox, once they have ticked the messages they want to delete, they then click on a submit button which takes them to the process page where the SQL statement to delete each selected message is made; however, the statement doesn't seem to work, this is what I have so far:
THE MESSAGE DISPLAY PAGE:
if ($_SESSION['user_session'] == "$current_user")
{
{
echo "<table border='1'>
<tr>
<th>Message ID</th>
<th>Username</th>
<th>Subject</th>
<th>Message</th>
<th>Delete?</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['message_id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['sub'] . "</td>";
echo "<td>" . $row['message'] . "</td>";
echo "<td><input type='checkbox' name='check_list[]' value='" . $row['message_id'] . "' /></td>";
echo "</tr>";
}
echo "</table>";
}
}
THE PROCESS PAGE WITH SQL STATEMENT:
if(!empty($_POST['check_list']))
{
foreach($_POST['check_list'] as $check)
{
//connection to the database
$dbhandle = mysql_connect("XXX", "XXX", "XXX")
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("XXX",$dbhandle)
or die("Could not select examples");
//execute the SQL query to update the "returned" field to 1 wherever the loan_id is checked.
$result = mysql_query("DELETE FROM message WHERE message_id='$check'");
}
if ($result)
{
echo 'Messages Deleted';
}
}
if(!empty($_POST['check_list']))
{
$dbhandle = mysql_connect("XXX", "XXX", "XXX") or die("Unable to connect to MySQL");
$selected = mysql_select_db("XXX",$dbhandle) or die("Could not select examples");
$result = mysql_query("DELETE FROM message WHERE message_id IN (" . implode(',', $_POST['check_list']) . ")", $dbhandle);
if ($result !== false)
echo 'Messages deleted.';
}
You obviously should implement some more testing of the contents of $_POST['check_list'] before executing the query. We don't want evil people to do silly stuff.
As far as I can see there's nothing wrong with your code, you should really try a var_dump($check) before the SQL query to output what it contains, and a var_dump($_POST['check_list']) at the very beggining of the second page.
Also, I suggest you to take out the database connection of the foreach as you are doing multiple innecesary connections, like this:
if(!empty($_POST['check_list'])) {
// Output the variable $_POST['check_list']
var_dump($_POST['check_list']);
//connection to the database
$dbhandle = mysql_connect("XXX", "XXX", "XXX") or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("XXX",$dbhandle) or die("Could not select examples");
foreach($_POST['check_list'] as $check) {
// Output the $check variable to see what it contains
var_dump($check);
//execute the SQL query to update the "returned" field to 1 wherever the loan_id is checked.
$result = mysql_query("DELETE FROM message WHERE message_id='$check'");
// For each $check, verify what message_id got deleted
if ($result) {
echo 'Message ID Deleted: ' . $check;
}
}
}