post to database - php

So i have so code that takes a message/post users insert and its meant to post it to a database and this then displays and a seperate page. Ive got the displaying park working fine its just trying to insert to database which is the problem
This code...
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$time = time();
mysql_query "INSERT INTO threads (title, message, author, dated);"
VALUES (NULL,'$_POST[title]','$_POST[message]','$_POST[author]','0','$time');
echo "Thread Posted.<br><a href='Untitled9.php'>Return</a>";
?>
wont post the infomation into the database!
Why is this and how can it be resolved?
id int(11) No None AUTO_INCREMENT
title varchar(255) latin1_swedish_ci No None
message text latin1_swedish_ci No None
author varchar(255) latin1_swedish_ci No None
replies int(11) No None
posted varchar(255) latin1_swedish_ci No None
votes_up int(11) No 0
votes_down int(11) No 0

Update:
Should be posted not dated.
Heres your problem:
mysql_query "INSERT INTO threads (title, message, author, posted);"
VALUES (NULL,'$_POST[title]','$_POST[message]','$_POST[author]','0','$time');
Change it to:
mysql_query("INSERT INTO threads (title, message, author, posted) VALUES ('$_POST[title]','$_POST[message]','$_POST[author]','$time');");
I see you have null values also, this makes me believe your using an ID with an auto increment, if this is the case, you need to supply this also. Example:
Edit: Here
mysql_query("INSERT INTO threads (id,title, message, author, posted) VALUES (NULL,'$_POST[title]','$_POST[message]','$_POST[author]','$time');");
Note inserting values straight from post data is unsafe and leaves you open to various attacks.

The values you are trying to add to the new row are more that the assigned values .
mysql_query "INSERT INTO threads (title, message, author, dated);"
that are 4 values you want to set
VALUES (NULL,'$_POST[title]','$_POST[message]','$_POST[author]','0','$time');
and you are assigning 6 values.
which is not possible
Also validate $_POST data = read this Never trust user input.
And read the manual PHP & MYSQL

The semicolon was ending your sql statment. Your query wasn't finished. You still needed to specify the values you wanted to insert.

mysql_query "INSERT INTO threads (title, message, author, dated);"
VALUES ('$_POST[title]','$_POST[message]','$_POST[author]','$time');
You ended the String to early. Should be:
mysql_query("INSERT INTO threads (title, message, author, dated)
VALUES ('$_POST[title]','$_POST[message]','$_POST[author]','$time')");
Also, your code is very likely to become a target of SQL-Injections. You should use the MySQLi-class and a PreparedStatement to insert your posts.

Number of issues :
if you put $_POST[] inside a string you need to put it in braces {$_POST[]} or PHP will not decipher the variable
next the names of the variables in the $_POST[] need to be quoted so that PHP does not think they are CONSTANTS, so they need to be like $_POST['title'] or $_POST["title"]
As others have said you need to protect against SQL injection by filtering the posted vars. Safest way to do this is to use PDO and I have included an example below. You can improve on this.
turn on error reporting so you can see errors while debugging
Here's tested code:
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$user='root';
$pass='';
$dsn = 'mysql:dbname=test;host=localhost'; //for PDO later
mysql_connect("localhost",$user , $pass);
mysql_select_db("test");
$time = time();
if (isset($_POST) && !empty($_POST))
{
// using braces {}
$sql=<<<SQL
INSERT INTO threads (title, message, author, posted)
VALUES ('{$_POST['title']}','{$_POST['message']}','{$_POST['author']}','$time')
SQL;
echo "$_POST[title]"."Thread Posted.<br><a href='Untitled9.php'>Return</a>";
// now a PDO version of the same
try {
$pdo = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();die;
}
$sth = $pdo->prepare("INSERT ino threads (title, message, author, posted)
VALUES (:title,:message,:author,:posted)");
$sth->execute(array(':title' => $_POST['title'],':message' => $_POST['message'], ':author' => $_POST['author'] ,':posted' => $time));
echo "Affected rows=".$sth->rowCount().",we are on line=".__LINE__."<br />";
echo $_POST['title']." Thread Posted.<br><a href='Untitled9.php'>Return</a>";
} // close if $_POST

Related

MySQL Error in SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
I am trying to insert a sample blog post into my 'posts' table in MySQL (using PHP) however I receive a syntax error whenever a large character post is submitted. If I submit content of say 20 characters it works but something like 500 characters will throw the following 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 ''uid', 'username', 'p_date', 'title', 'content') VALUES('1','Mark Twain', '2014-' at line 1
The 'content' is to be inserted into the database via a varchar(1000) variable. The table is defined in mysql as:
CREATE TABLE posts
(
pid int NOT NULL AUTO_INCREMENT,
uid int NOT NULL,
username varchar(100) NOT NULL,
p_date date NOT NULL,
title varchar(225) NOT NULL,
content varchar(10000) NOT NULL,
PRIMARY KEY(pid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
The actual content I am trying to submit is this:
Secondly, these missionaries would gradually, and without creating suspicion or exciting alarm, introduce a rudimentary cleanliness among the nobility, and from them it would work down to the people, if the priests could be kept quiet. This would undermine the Church. I mean would be a step toward that. Next, education -- next, freedom -- and then she would begin to crumble. It being my conviction that any Established Church is an established crime, an established slave-pen, I had no scruples, but was willing to assail it in any way or with any weapon that promised to hurt it. Why, in my own former day -- in remote centuries not yet stirring in the womb of time -- there were old Englishmen who imagined that they had been born in a free country: a "free" country with the Corporation Act and the Test still in force in it -- timbers propped against men's liberties and dishonored consciences to shore up an Established Anachronism with.
The insert statement for this is the following:
$sql = "INSERT INTO posts ('uid', 'username', 'p_date', 'title', 'content') VALUES('$uid','$uname', '$date', '$title', '$content')";
if(!mysql_query($sql,$con)){
echo "Oops! Something went wrong during the posting process. Please try again. ";
die('Error: ' . mysql_error($con));
header('Refresh: 1; URL=postingform.php');
}else{
// Now return the user to their post page
header('Refresh: 0; URL=postlist.php?uid='.$uid.'');
}
For some reason it is error-ing out during the INSERT process. The one thing strange I notice is that the date is cut off in the error. To call the date I am using. $date = date("Y-m-d");
I have used this same syntax before without issues.
****Edit
A few posters have pointed out that there are single quotations in my INSERT column statements. I have changed these to back tics and completely removed them but the error still results.
New 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 's Court', 'Secondly, these missionaries would gradually, and without creating su' at line 1
There is something still wrong with my insert syntax but everything I am reading says it should be correct.
$sql = "INSERT INTO posts (`uid`, `username`, `p_date`, `title`, `content`) VALUES('$uid','$uname', '$p_date', '$title', '$content')";
Remove all the quotes in (for your columns)
('uid', 'username', 'p_date', 'title', 'content')
Those aren't the correct column identifiers
http://dev.mysql.com/doc/refman/5.5/en/identifiers.html
use
(uid, username, p_date, title, content)
or use backticks.
(`uid`, `username`, `p_date`, `title`, `content`)
However and as a quick FYI, backticks are mostly used for reserved keywords, or if a table/column contains spaces, hyphens.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
The error message was letting you know here
check the manual that corresponds to your MySQL server version for the right syntax to use near ''uid',
^--« right there
Notice the quote just before 'uid'? That's where the problem starts.
Edit:
Try the following using prepared statements and replace xxx with your own credentials.
This should take care of the quotes issue from your input values.
You will need to add the variables according to your inputs.
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
$uid = ""; // replace with proper value
$uname = ""; // replace with proper value
$date = ""; // replace with proper value
$title = ""; // replace with proper value
$content = ""; // replace with proper value
$stmt = $conn->prepare("INSERT INTO posts (`uid`, `username`, `p_date`, `title`, `content`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $uid, $uname, $date, $title, $content);
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else{
echo "Success";
}
$stmt->close(); // Statement
$conn->close(); // MySQLi
Footnotes:
In order to allow single and/or double quotes, based yourself on the following, while using the stripslashes() function.
$content = stripslashes($_POST['content']);
This will enter in DB properly:
Bob's sister was here today and said: "Bob, what lovely hair you have!".

Insert result into multiple tables

EDIT:
Im trying to submit a form with a title and body but i want the title to go to one table and body to go to another table, this in itself i can do but i need the ID generated from the title being inserted into its table to then be inserted into a field in the table the body is inserted so as to keep them linked.
What i have so far: I know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
if (#$_POST['post'])
{
$body = #$_POST['body'];
$title = #$_POST['title'];
$BoardID = #$_POST['BoardID'];
$MemberID = #$_POST['MemberID'];
$date = date("Y-m-d H:i:s");
include ('connect.php');
$insert = mysql_query("INSERT INTO threads VALUES ('','$BoardID','$title','$date','$MemberID','','')");
if($insert) {
header("location: ?p=posts&thread=$Thread_ID");
exit();
}
}
I need to somehow get $Thread_ID which has been generated in the insert and add that to a second insert for adding body to the post table, if that makes sense.
I tried getting the latest $Thread_ID and adding +1 but if multiple threads are posted at once they might get crossed over.
How would i go about fixing this?
The PHP manual tell us:
This extension Mysql is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
(see ref.)
You must use mysqli or PDO, to make a connection between PHP and a MySQL database.
mysqli
If you want the id of the inserted row, you can use $mysqli->insert_id (ref)
Example:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
PDO
If you want the id of the inserted row, you can use $dbh->lastInsertId(); (ref)
And don't forget to sanatize all your inputs.
You need to execute both insert queries separately.
$insert = "INSERT INTO threads VALUES ('','$BoardID','$title','$date','$MemberID','','')";
$result = #mysql_query($insert);
$Thread_ID=#mysql_insert_id();
$insert = "INSERT INTO posts VALUES ('','$BoardID',$Thread_ID','$body','$date','$MemberID')";
$result = #mysql_query($insert);
Thanks,

PHP MySQL - Am I doing anything wrong?

For two hours now, I'm trying to insert a value into a table. I don't get any error and I can't find out the problem!
The value that I'm trying to insert:
$query = "INSERT INTO banlist (banid, active, ip, by, date, reason) VALUES (NULL, 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')";
mysql_query($query);
An example value that works perfectly:
$query = "INSERT INTO accounts (username, password, email, regdate) VALUES ('test', 'test', 'test#test.test', 't-t-t t:t:t')";
mysql_query($query);
I can't find the problem! Am I missing anything? Both tables exist.
The issue is that the name you've chose for a field "by" is a reserved word. You'll have to update it to a word that's not on this list.
Also, in future you can easily see what's wrong by checking if mysql_query() returned false, and then calling mysql_error() for an error message.
Try this:
CREATE TABLE ban (
banid int auto_increment primary key,
active int,
ip varchar (20),
`by` varchar (20),
`date` varchar(8),
reason varchar(20)
);
INSERT INTO ban (active, ip, `by`, `date`, reason)
VALUES
(1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')
;
SELECT * FROM ban;
http://www.sqlfiddle.com/#!2/1959f/1
Some remarks:
Like several others (e.g. #wintercounter, #user1909426 ) have pointed out you are using restricted words in MySQL. If you do use a restricted word then use `` (back ticks) or just use them on every column.
I think that using a null in your first part of you insert gives a problem. This column is probably an integer column with auto_increment. See #wintercounter answer.
Fortunately date is not a restricted name. B.T.W. you could use use a date value instead of you varchar value now.
With regard to the comments from #tadman using mysql instead of mysqli or PDO is not recommended. The mysql library is depreciated from version PHP 5.5 onwards, see the php manual. You will also need to include error handling.
For completeness sake, this is the php code when using MySQLi:
$link = mysqli_connect($hostname, $username, $password, $database);
if (!$link){
echo('Unable to connect to database');
}
else{
mysqli_query("INSERT INTO ban (active, ip, `by`, `date`, reason) VALUES (1,'10.25.47.88', 'AUTOBAN', '12-12-45', 'test'))", $link);
}
mysqli_close($link);
For mysql version:
$hostname = "hostname";
$username = "username";
$username = "password";
$database = "database";
$link = mysql_connect($hostname, $username, $password);
mysql_database ($database)
if (!$link){
echo('Unable to connect to database');
}
else{
mysql_query("INSERT INTO ban (active, ip, `by`, `date`, reason) VALUES (1,'10.25.47.88', 'AUTOBAN', '12-12-45', 'test')");
}
mysql_close($link);
use mysql error statement in each variable for know which line your mistake occured.
The query probably doesn't display an error because error_reporting is turned of in your php.ini:
try setting error_reporting to E_ALL.
Also the query might not work because you are sending "NULL" as value for banid which is probably a either a primary key or a foreign key / index that doesn't allow a NULL value.
Try this:
INSERT INTO `banlist` (`banid`, `active`, `ip`, `by`, `date`, `reason`) VALUES ('', 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')
As stated, 'by' is reserved keyword, but you can help to MySQL in the parse so it'll know if it's a field name or a command.
EDIT:
I've changed NULL to ''. I'm not sure in this, never tried, but if it's an AI field, maybe you can't use NULL there, just use an empty content as a placeholder for ID field.
Just try this:
INSERT INTO banlist VALUES (NULL, 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')

SQL syntax error, I just can't see it

Here is my code:
<?php
$con = mysql_connect("localhost","solidarity","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO show_reviews (username, date, content, show) VALUES (".addslashes($_POST[username]).",".addslashes($_POST[date]).",".addslashes($_POST[content]).",".addslashes($_POST[show]).")";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
So I have used fsprint and now I have just used the w3schools code and this is my output with both pieces of code:
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 'show) VALUES (Solidarity, 17:02 - Wed, 1st Aug 2012,Testing,kr1971)' at line 1
I use a very similar syntax for a commenting system and do not have this problem. If it helps also, I have tried on a local sql server and remote also, still no luck.
Please help me :(.
Put the values inside of single quotes:
$sql=" INSERT INTO show_reviews (username, date, content, show)
VALUES ('".addslashes($_POST[username])."','".addslashes($_POST[date])."','".addslashes($_POST[content])."','".addslashes($_POST[show])."')";
Additionally, as others have said show is a reserved keyword in MySQL. You can see the full list of reserved keywords for MySQL 5.5 at http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You can quote reserved words using the backtick in order to be able to use them:
INSERT INTO show_reviews (username, date, content, `show`)
Quoting Identifiers:
http://dev.mysql.com/doc/refman/5.5/en/identifiers.html
And finally, to summarize the comments about using addslashes() for escaping. I will let Chris Shiflett explain why it is bad: http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string
You really should be jumping aboard the prepared statements/parameterized queries bandwagon with PDO or at minimum, MySQLi. Here is an example of how you query could look:
$dbh = new PDO($connection_string);
$sql = "INSERT INTO show_reviews (username, date, content, show) VALUES (?, ?, ?, ?)";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($_POST['username'],
$_POST['date'],
$_POST['content'],
$_POST['show']
));
while ($row = $stmt->fetch()) {
print_r($row);
}
This is purely an example, it is still a good idea to do your sanitizing of $_POST variables and do your best to ensure the data you received is exactly what you were trying to get. These prepared statements take care of escaping for you properly and, if using PDO, the proper way for your specific database engine.
show is a mysql keyword. So, it cannot be a column name. You will have to escape it, if you want to use show as a column name.
show is a reserved keyword in SQL. You have to enclose it with backticks to use as a column name.
Please use this query
$sql= 'INSERT INTO show_reviews (username, date, content, show)
VALUES ("'.addslashes($_POST[username]).'",".'addslashes($_POST[date]).'","'.addslashes($_POST[content]).'","'.addslashes($_POST[show]).'")';
Your values need to be wrapped in quotes.
$sql="INSERT INTO show_reviews (username, date, content, show) VALUES ('".addslashes($_POST[username])."','".addslashes($_POST[date])."','".addslashes($_POST[content])."','".addslashes($_POST[show])."')";
Also show is a reserved word, so you need to encase it in backticks.
To elaborate on Sebastian's comment, use PDO: it is more resilient (or immune?) to SQL injection attacks. The code will look something like this:
<?php
try {
$handle = new PDO('mysql:host=localhost;dbname=myDatabaseName', 'username','password');
$prepared = $handle->prepare("INSERT INTO show_reviews (username, date, content, show) VALUES (?,?,?,?)");
if($prepared->execute(array($_POST['username'], $_POST['date'], $_POST['content'], $_POST['show']))) {
echo "1 record inserted...";
}else {
echo "insert failed...";
}
}catch(PDOException $ex) {
// error connecting to database
}
?>

PHP/MySQL insert row then get 'id'

The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
Another way would be to run both queries in one go, and using MySQL's LAST_INSERT_ID() method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See #Luke's answer for MySQLi). To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

Categories