I'm trying to insert a value into my sql table that has html in it: like follows
<?
$story ="<div class='post'><p class='date'>$mont<b>$day</b></p><h2 class='title'>lkjljt</h2><p class='meta'><small>Posted $name | $school, $date | Rating</small></p><div class='entry'>$message</div></div>";
$db = mysql_connect("host", "user", "password");
mysql_select_db("db", $db);
if (!$db)
{
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story', '$school','$location', '$sex', '$zipcode', '$name');";
$result = mysql_query($sql);
if($result)
{ $success = " Your hookup has been submitted ";}
else{
$error = "something went horribly wrong" . mysql_error();}
?>
I keep getting a syntax error when I submit this page, and if I comment $story out, the query runs fine. How can I fix this?
The most likely reason is that $story contains single quotes, which will break the query.
Protect it using mysql_real_escape_string
In general, this is a bad idea as it is open to SQL injection.
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story',
'$school','$location', '$sex', '$zipcode', '$name');";
At least, use mysql_real_escape_string which will protect the input for characters that have special meaning in a MySQL query. Use it on all textual columns.
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '" .
mysql_real_escape_string($story) . "','".
mysql_real_escape_string($school) . "','".
mysql_real_escape_string($location) . "', '$sex', '$zipcode', '" .
mysql_real_escape_string($name) ."');";
If you didn't care about SQL Injection ( though I dont know why would you wouldnt ) you could also use htmlspecialchars to fix your problem. mysql_real_escape_string is obviously the better choice though like #cyberkiwi said
Related
Im having a problem with my PHP code, it says the error is "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 ')' at line 1"
It connects to the database ok as it echos "Database Connection Successful" but it dosnt insert the data into the database. This worked fine before, but now all of a sudden its stopped working. Can anyone help?
<?php
$username = "student";
$password = "student";
$hostname = "localhost";
$db = "details";
$link = new mysqli($hostname, $username, $password, $db);
if ($link->connect_errno)
printf("Connect failed: %s\n", $link->connect_error);
else
echo "Database Connection Successful \n";
echo nl2br("\n");
$Urgency = "Urgency";
if(isset($_POST['submit'])){
$TypeOfProblem = $_POST['problemtype'];
$ProblemDescription = $_POST['problem'];
$RoomNo = $_POST['roomno'];
$Problem = $_POST['reporter'];
$Urgency = $_POST['Urgency'];
$Date = $_POST['date'];
//Insert into Database
$sql = "INSERT INTO `details`.`problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`,`Date` ) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)";
if (!mysqli_query($link, $sql))
{
die('Error: ' . mysqli_error($link));
}
echo "\n Thank you. Your Helpdesk Call has been submitted.";
mysqli_close($link);
}//////// end isset submit if ////////
?>
Thanks
Try using this, the problem is the single quote ` should be '
$sql = "INSERT INTO 'details'.'problem' ('Type Of Problem', 'Problem Description', 'RoomNo', 'Urgency', 'UserIDProblem','Date' ) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', '$Date')"
Or try to set an echo $sql and test the query directly on de dbms
The date '$Problem', $Date)"; needs single-quotes '$Problem', '$Date')";
First, it is a good idea to leave out the database name:
$sql = "INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)";
Are you sure, that your column names have spaces in it? I mean this would work, but this is not a good idea, I think.
I cannot find another problem in your query, maybe you should quote the date:
$sql = "INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', '$Date')";
Otherwise, please provide us with the full query:
die("INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)");
And you SHOULD notice, that your code is exploitable with SQL-Injections! Use mysqli_real_escape_string.
For debugging this, output the actual SQL text that is being submitted to the database, using echo or vardump e.g.
$sql = "INSERT INTO ...";
echo "SQL=" . $sql ;
That will show you the actual statement that's going to be submitted to the database, and you can usually debug the problem from there.
If date isn't a numeric, if it represents a DATE datatype or a string, the value needs to be enclosed in single quotes. Otherwise, it's likely going to be interpreted in a numeric context.
Note that this code appears to be vulnerable to SQL Injection, because it includes potentially unsafe values in the SQL text. Consider what happens when a value contains "special" characters, like a single quote, or comma.
Potentially unsafe values must be properly escaped. With mysqli, you can use the mysqli_real_escape_string function.
A better pattern is to use a prepared statement with bind placeholders.
As an example of what that would look like (before it's cluttered up with code to checks for errors from the return of the mysqli_ function calls)
$sql = "INSERT INTO `details`.`problem`
(`Type Of Problem`,`Problem Description`,`RoomNo`,`Urgency`,`UserIDProblem`,`Date`)
VALUES (?,?,?,?,?,?)";
$sth = mysqli_prepare($link,$sql);
if (!$sth) {
echo "error:" . mysqli_error($link);
)
mysqli_stmt_bind_param($sth,"ssssss"
,$TypeOfProblem,$ProblemDescription,$RoomNo,$Urgency,$Problem,$Date);
mysqli_stmt_execute($sth);
Thanks for your help, let me know if you need anything else.
details in the title.
<?php
$subject = $_POST['subject'];
$comment = $_POST['comment'];
$submit = $_POST['submit'];
if ($submit)
{
$connect = mysql_connect("host","un","psw");
mysql_select_db("rebeler_comment");
$query = mysql_query("INSERT INTO table VALUES('','$subject','$comment')");
}
?>
<form action="form.php" method="POST">
<label>Subject</label></br>
<input type="text" name="subject"</br>
<label>Comment</label></br>
<textarea name="comment"></textarea></br>
<input type="submit" name="submit" value="Submit">
updated with my html
Firstly, the use of MySQL_ is deprecated. Use MySQLi_ and/or PDO.
Now, you're not specifiying "where" to put your data in your table.
Assuming your columns are named subject and comment respectively.
Also, the word table is a reserved word. Therefore if your table is indeed called table, you need to wrap in inside back ticks,
like this: `table`
$query = mysql_query("INSERT INTO table (`subject`, `comment`)
VALUES ('$subject','$comment')");
If table name is called "table":
Use:
$query = mysql_query("INSERT INTO `table` (`subject`, `comment`)
VALUES ('$subject','$comment')");
Deleted '', from ('','$subject','$comment') because you only have 2 values going in DB.
You may even want to concatenate such as:
VALUES ('" . $subject . "','" . $comment . "')");
To echo a success message:
$query = mysql_query("INSERT INTO `table` (`subject`, `comment`)
VALUES ('$subject','$comment')");
echo "Data successfully written to DB";
}
else{
echo "Sorry, there was a problem.";
}
EDIT 2:
<?php
$subject = $_POST['subject'];
$comment = $_POST['comment'];
if(isset($_POST['submit']))
{
$connect = mysql_connect("host","un","psw");
mysql_select_db("rebeler_comment");
$query = mysql_query("INSERT INTO `table` (`subject`, `comment`) VALUES ('" . $subject . "','" . $comment . "')");
$retval = mysql_query( $query, $connection ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); }
echo "Entered data successfully\n";
mysql_close($connection);
}
?>
EDIT 1:
$query = mysql_query("INSERT INTO `table` (`subject`, `comment`) VALUES ('" . $subject . "','" . $comment . "')");
$retval = mysql_query( $query, $connection ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); }
echo "Entered data successfully\n";
mysql_close($connection);
Fix your SQL insert (among some things), define the columns to insert into, instead of blindly throwing stuff into the dark.
Ex:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Also use mysql_error() for get errors. I would also suggest leveraging a php framework to get around injection issues and other stuff you might miss doing mysql by hand.
Have a simple registration form that is being linked to a php file in order to send the info to a database but everytime i try it the data isnt showing up in the phpMyAdmin database??
<?php
$name = $_POST['name'];
$address = $_POST['address'];
$number = $_POST['number'];
$email = $_POST['email'];
$details = $_POST['details'];
$user="root";
$password="secure";
$database="darrenweircharity";
mysql_connect("localhost",$user,$password);
#mysql_select_db($database) or die ("Unable to select database");
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('$name', '$address', '$number', '$email', '$details' NOW())";
mysql_query($query);
mysql_close();
?>
Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Try with:
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('" . $name . "', '" . $address . "', '" . $number . "', '" . $email . "', '" . $details . "');";
You have NOW() at the end of the query that shouldn't be there.
Also note that your code has an SQL injection vulnerability (see mysql_real_escape_string()), I suggest you to prepare queries via PDO.
protect from possible SQL injection:
$name = mysql_real_escape_string($name);
$address = mysql_real_escape_string($address);
$number = mysql_real_escape_string($number);
$email = mysql_real_escape_string($email);
$details = mysql_real_escape_string($details);
replace with:
$query = "
INSERT INTO registrationdetails (`name`, `address`, `number`, `email`, `details`)
VALUES ('$name', '$address', '$number', '$email', '$details')");
$query = "
INSERT INTO registrationdetails (name, address, number, email, details, date_time)
VALUES ('{$name}', '{$address}', '{$number}', '{$email}', '{$details}', NOW())
";
Replace the date_time with your column_name. And remember to escape all submitted values with mysql_real_escape_string before inserting them into the database.
I've looked at other examples on here, but everyone else's syntax is different from what I have, so I have no clue where to put "mysql_real_escape_string".
Here is my current code:
include("dbconnect.php");
mysql_select_db("scratch", $con);
$sql= "INSERT INTO stories (author, story_name, story)
VALUES
('$_POST[author]','$_POST[story_name]', '$_POST[story]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Story Submitted!";
mysql_close($con)
Where would I add that string in this?
You need to escape any variable values you're including in your query. So in your code these would be:
$_POST['author']
$_POST['story_name']
$_POST['story']
So change your $sql variable to look like:
$author = mysql_real_escape_string($_POST['author']);
$story_name = mysql_real_escape_string($_POST['story_name']);
$story = mysql_real_escape_string($_POST['story']);
$sql= "
INSERT INTO stories (author, story_name, story)
VALUES ('$author','$story_name', '$story')
";
You should probably also add isset or empty checks when using the $_POST variables to avoid notices if they don't exist. Finally, you'd be better served to use PDO with prepared statements than the less robust mysql extension.
//USE IN THIS WAY THE QUERY WILL RUN PROPERLY WITH mysql_real_escape_string
$sql= 'INSERT INTO stories (author, story_name, story)
VALUES
('.mysql_real_escape_string($_POST[author]).',
'.mysql_real_escape_string($_POST[story_name]).',
'.mysql_real_escape_string($_POST[story]).')';
put POST variables into new variables and then apply mysql_real_escape_string, and finally put new variables into the SQL statement
Here's the code:
include("dbconnect.php");
mysql_select_db("scratch", $con);
$author = mysql_real_escape_string($_POST[author]);
$story_name = mysql_real_escape_string($_POST[story_name]);
$story=mysql_real_escape_string($_POST[story]);
$sql= "INSERT INTO stories (author, story_name, story)
VALUES
('$author','$story_name', '$story')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Story Submitted!";
mysql_close($con);
mysql_query("INSERT INTO contact_forms(name,ts,ip,email,option,msg)
VALUES('".$name."',
NOW(),
'".$_SERVER['REMOTE_ADDR']."',
'".$email."',
'".$option."',
'".$message."')");
For some reason this thing doesn't work. It throws no errors but it just doesn't work. Can someone tell me why?
Assuming you are doing this in PHP, which is what it appears to be, try changing your code to this to see if you get an error that might be able to add a little more information:
mysql_query("INSERT INTO contact_forms(name,ts,ip,email,option,msg)
VALUES('".$name."',
NOW(),
'".$_SERVER['REMOTE_ADDR']."',
'".$email."',
'".$option."',
'".$message."')", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "<br>";
In this example the variable $link is your database connection string.
See http://php.net/manual/en/function.mysql-error.php for more information on usage.
Put mysql_error() as zerkms suggested.
Update
option is a MySQL [link=http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html]reserved word[/link] and you can not use it unless you enclose it with back tick (`).
mysql_query("INSERT INTO contact_forms(name,ts,ip,email,`option`,msg)
VALUES('".$name."',
NOW(),
'".$_SERVER['REMOTE_ADDR']."',
'".$email."',
'".$option."',
'".$message."')");
Always use mysql_error() to debug query issues. It is not a good practice to use reserve words in database schema.
Try
$date = now();
$ip = $_SERVER['REMOTE_ADDR'];
$query = "INSERT INTO contact_forms (name,ts,ip,email,option,msg)
VALUES('$name',
'$date',
'$ip',
'$email',
'$option',
'$message')";