I have contact form at my wordpress site which is delivered by ajax, and sent to my mail. I also wanted to save the results in a database so I wrote this query, but it gives me and syntax error, but I can't find anything wrong in this code:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql="INSERT INTO wp_contactform (Nimi, Puhelin, E-mail, Viesti, IP, Day)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The jquery script that sends it works, and the mail is sent, but this doesn't save.
Quote the column name E-mail with backticks (`). MySQL is interpreting this in two parts at the moment.
Note also, (as per my comment) that your code is wide open to SQL injection attacks. It is much better to use properly parameterised SQL queries.
SQL injection example:
"INSERT INTO table (field) VALUE ('$_POST[var]')"
If you post the value "'; DROP TABLE table; --" then you have a valid SQL string that inserts an empty string, then attempts to drop the table. Substitute whatever harmful statement you want.
and also you should use mysql_real_escape_string() or prepared statements. if your query data have any special characters it can blow your query it also help you from sql injection too.
http://php.net/mysql_real_escape_string
http://php.net/pdo
Your SQL request should be written as below:
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')"
SQL fields using non-alphanumeric characters have to be escaped with backticks (`)
This should work
<?php
$con = mysql_connect("localhost", "username", "password");
if(!$con){
die('Could not connect: '.mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('".mysql_real_escape_string($_POST['Nimi'])."','".
mysql_real_escape_string($_POST['Puhelin'])."','".
mysql_real_escape_string($_POST['Sposti'])."','".
mysql_real_escape_string($_POST['Tiedot'])."','".
mysql_real_escape_string($_POST['Gotcha'])."','".
mysql_real_escape_string($_POST['Day'])."')";
if(!mysql_query($sql, $con)){
die('Error: '.mysql_error());
}
echo "1 record added";
mysql_close($con);
Related
Can anyone help with advising what may be wrong with my insert into syntax please ?
Working except i am receiving empty query message
// values sent from form
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$postcode=$_POST['postcode'];
$gender=$_POST['gender'];
$yob=$_POST['yob'];
/*********** CONNECT TO THE DATABASE ******/
//Step 1 CONNECT TO THE DATABASE
$db=mysql_connect ("localhost", “db_username, “db_password);
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
}
//Step2 SELECT THE DATABASE
$db_select = mysql_select_db(“db_name,$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
}
echo "Welcome $first_name!";
echo " Success, connected to database but maybe not the table";
// Insert data into database
//##############################I THINK PROBLEM MUST BE HERE IN THIS INSERT STATEMENT STATEMENT###################################
$sql="INSERT INTO newsletter-subscribers(first_name, last_name, email, postcode, gender, yob)VALUES('$first_name','$last_name','$email','$postcode','$gender','$yob')";
if(mysql_query($sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysql_error($db);
}
$result=mysql_query($sql);
Your query,
$sql="INSERT INTO newsletter-subscribers(first_name, last_name, email, postcode, gender, yob)VALUES('$first_name','$last_name','$email','$postcode','$gender','$yob')";
Your new query,
$sql = "INSERT INTO `newsletter-subscribers` (first_name, last_name, email, postcode, gender, yob) VALUES ('$first_name','$last_name','$email','$postcode','$gender','$yob')";
So, what has changed?
Added ticks around your table name.
Removed spaces which you didn't need to make query clearer.
Without the backticks around your table name, MySQL is treating it as newsletter minus subscribers. Which is wrong, add the ticks to tell MySQL that it is a table name.
Edit 1
This might be a copy & paste error, I'm not sure, however...
Your db connect is incorrect too, you aren't assigning any values to it as your quotes are not closed and are smart quotes.
Your connect,
$db = mysql_connect ("localhost", “db_username, “db_password);
Your new connect,
$db = mysql_connect("localhost", "db_username"," db_password");
Also,
$db_select = mysql_select_db(“db_name,$db);
To,
$db_select = mysql_select_db("db_name", $db);
Notice the difference in the quotes.
Edit 2
Your code is prone to SQL injection, you are still using MySQL even though it has been deprecated, you should use either MySQLi or PDO with prepared statements.
Not to mention your $_POST data is being passed on to the query without being sanitized, you should start using htmlspecialchars it would make it better and prevent XSS.
Your table name contains a dash, so you need to quote it. The backtick or back-quote character is used to quote symbol names in MySQL (such as the names of tables, columns, etc), so you would need something like this:
INSERT INTO `newsletter-subscribers` (first_name, ...
I am trying to use one form to insert data into 2 tables.
I have one table, Members and another, Members.
Here is my code:
<?php
$first_name=$_POST[first_name];
$last_name=$_POST[last_name];
$email_address=$_POST[email_address];
$staff=$_POST[staff];
$type=$_POST[type];
$descr=$_POST[descr];
$time=$_POST[time];
mysql_select_db("cl49-vogclients", $con); $sql="INSERT INTO member
(first_name,last_name,email_address)
VALUES
('$first_name','$last_name','$email_address')";
if (!mysql_query($sql,$con)) { die('Error adding client ' . mysql_error()); } mysql_close($con);
echo' <h2><font color="green">Client Added Succesfuly</font> </h2>';
$sql1="INSERT INTO audit
(staff,type,descr)
VALUES
('$staff','$type','$descr')";
if (!mysql_query($sql1,$con)) { die('Audit Unsucsessful ' . mysql_error()); } mysql_close($con);
echo' <h2><font color="green">Audit Succesful</font> </h2>';
This adds the client/member but not add anything to the audit database?
This is because you are only executing the first query:
mysql_query($sql,$con)
You have to call it seperatly for $sql1
Besides that: Please bear in mind that mysql like this is heavily outdated and deprecated. You should really look into PDO and prepared statements.
http://php.net/manual/de/book.pdo.php
You have closeds SQL
You need to remove mysql_close($con);
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
}
?>
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("pilot", $con);
$sql = "INSERT INTO logs (id, userid, date, plane, from, to, blocksoff, takeoff,
landing, blockson, flighttime, traveltime, tachobefore, tachoafter, tacho,
hobbsbefore, hobbsafter, hobbs, landings) VALUES ('$nfid', '$nfuserid',
'$nfdate', '$nfplane', '$nffrom', '$nfto', '$nfblocksoff', '$nftakeoff',
'$nflanding', '$nfblockson', '$nfflighttime', '$nftraveltime', '$nftachobefore',
'$nftachoafter', '$nftacho', '$nfhobbsbefore', '$nfhobbsafter', '$nfhobbs',
'$nflandings')";
mysql_query($sql);
there ain't nothing wrong with the $sql, it seems like it just wont query.. :(
id|userid=int(11)
date=date
plane|from|to=text
blocksoff|takeoff|landing|blockson=time
flighttime|traveltime|tachobefore|tachoafter|tacho|hobbsbefore|hobbsafter|hobbs|landings=double
all of the $ variables come from a textbox (if it matters)
May be some of the column names are MySql reserved words (especially from and to). Please escape them.
INSERT INTO logs (`id`, userid, date, plane, `from`, `to` ...)
You should always be checking for errors:
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Kind of an open ended question....
Are any of your variables returning NULL values? If you are trying to insert NULL into the database, and the database column isn't set to accept NULL values, that could be causing an error.
You need to see what the query is actually doing. If you have any single quotes or other invalid character from the textbox, that could be screwing you up.
Also, for your own personal improvement, look up PDO. It helps you write much more secure queries through the use of prepared statements.
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):
"Connected to databaseError: 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 ''test' ('name') VALUES ('daniel')' at line 1"
The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?
Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.
HTML
<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
PHP (insert.php)
<?php
$dbhost = 'localhost';
$dbname = 'carbon_db';
$dbuser = 'username';
$dbpass = 'password';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
else
{
echo 'Connected to database';
}
mysql_select_db($dbname, $con);
$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Drop the quotes around the table name or change them to back ticks:
Change:
$sql="INSERT INTO 'test' ('name') VALUES ('$_POST[namefield]')";
To:
$sql="INSERT INTO test ('name') VALUES ('$_POST[namefield]')";
Or
$sql="INSERT INTO `test` ('name') VALUES ('$_POST[namefield]')";
It's often best to use backticks for MySQL as like any other storage engines it has it's own reserved names and it's own reserved insert practices.
try with
$sql = "INSERT INTO `test` (`name`) VALUES ('".$_POST['namefield']."')";
Change the single quotes surrounding the table name and the column name to backticks. Or get rid of them all together.
$sql="INSERT INTO `test` (`name`) VALUES ('{$_POST['namefield']}')";
Also, don't reference associative arrays ($_POST) directly in a string without using {} syntax or breaking up the string - what you have done there issues an E_NOTICE and should be avoided.
Read this thoroughly - you'd be amazed what you can (and can't) legally do in PHP strings...
try using ` instead of ' when refering to table/column names
$sql="INSERT INTO `test` (`name`)
VALUES ('$_POST[namefield]')";
Remove the single quotes around your sql statement and replace with back-tics (not sure even they are necessary):
$sql="INSERT INTO `test` ('name')
VALUES ('$_POST[namefield]')";