MySQL syntax:You have an error in your SQL syntax… - php

I am receiving the following error from the code below.
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 '#doe.com,username,5f4dcc3b5aa765d61d8327deb882cf99,09/05/2011 1:11:13 AM)' at line 1
$username = $_GET['username'];
$password = md5($_GET['password']);
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
$email = $_GET['email'];
$date = uk_date();
$conn = mysql_connect('localhost', 'myuser', 'mypass');
mysql_select_db('dbname');
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES (". $firstname . ",". $lastname ."," . $email . "," . $username . "," . $password . "," . $date . ")";
$result = mysql_query($query) or die(mysql_error());
echo 'Success';
mysql_close($result);
Please could you let me know what my problem is? I am new to MySQL and PHP so please can you provide an explanation to what I have done wrong for later reference.

You haven't quoted any of the values in your INSERT, you should be saying something more like this:
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('". $firstname . "','". $lastname ."','" . $email . "','" . $username . "','" . $password . "','" . $date . "')";
You should also be using mysql_real_escape_string on all those variables to make sure that any embedded quotes and such are properly encoded.
A better version would be something like this:
$query = sprintf("INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname),
mysql_real_escape_string($email),
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($date));
You should also listen to BoltClock and use PDO and placeholders so you don't have to worry about your quotes and escaping so much. PDO will also make it easier to switch databases.

Probably user input have a single quote character, so it will be safe to escape special character before send it as query to database, this will prevent your script from sql injection.
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('$firstname', '$lastname', '$email','$username','$password', '$date')";

Once you have escaped your variables like suggested by other, you need to surround them with quotes if they are string varialbles :
mysql_select_db('dbname');
$query = "INSERT INTO accounts
(FirstName, LastName, Email, Username, Password, LastLoginDate)
VALUES ('". $firstname . "','". $lastname ."','" . $email . "','" .
$username . "','" . $password . "','" . $date . "')";
$result = mysql_query($query) or die(mysql_error());
echo 'Success'; mysql_close($result);
In this case i added single quotes. you shouldnt have any errors now

Related

Error in Inserting Values into PostgreSQL table through php

I'm trying to insert received values into postgresql table using php. I can't figure out why this statement doesn't work
$query = "INSERT INTO user_info (name, emailAddress, phoneNumber, jobDesc) VALUES ('" . $name . "," . $emailAddr . "," . $phoneNumber . "," . $jobDesc ."')";
I get this error:
Query failed: ERROR: column "emailaddress" of relation "user_info" does not exist
However, I tried this one:
$query = "INSERT INTO user_info VALUES ('" . $name . "," . $emailAddr . "," . $phoneNumber . "," . $jobDesc ."')";
It works, but it inserts all values into first column!
I'm not sure what I'm missing here!
I think you are missing a whole host of single quotes in your VALUES list...
$query = "INSERT INTO user_info (name, emailAddress, phoneNumber, jobDesc) VALUES ('" . $name . "','" . $emailAddr . "','" . $phoneNumber . "','" . $jobDesc ."')";

Unable to locate sql error in php

Error message i've been recieving
Parse error: syntax error, unexpected 'INTO' (T_STRING) in D:\ServerFolders\Web\tokens\insert.php on line 17
Line 17
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
Full code
<?php
//Connect to DB
$con=mysql_connect(localhost,root, "",APROJECT) or die (mysql_error());
// Check connection
if (mysql_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
// escape variables for security
$Forename = mysql_real_escape_string($con, $_POST['Forename']);
$Surname = mysql_real_escape_string($con, $_POST['Surname']);
$Email = mysql_real_escape_string($con, $_POST['Email']);
$Username = mysql_real_escape_string($con, $_POST['Username']);
$Password = mysql_real_escape_string($con, $_POST['Password']);
$DOB = mysql_real_escape_string($con, $_POST['DOB']);
//SQL query to add data to DB
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB);
if (!mysql_query($con,$sql)) {
die('Error: ' . mysql_error($con));
}
echo "1 record added";
mysql_close($con);
?>
First of all, mysql_* is not supported anymore and advised to use PDO or mysqli_* instead.
You should put query into quotes;
$sql= "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
It may not work! Because you have to put values into single quotes. So better approach is using parameterized query.
For this time only I suggest using sprintf() function.
$sql= sprintf("INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')", $Forename, $Surname, $Email, $Username, $Password, $DOB);
Try adding quotes
$sql= "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB);
The above line needs to be a string and in one line (variables in strings which start and end in " can be directly written into it):
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
If you want it to be in multiple lines for better readability, you can use the nowdoc syntax with variables embeded in {}:
$sql <<<'EOD'
INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ({$Forename}, {$Surname}, {$Email}, {$Username}, {$Password}, {$DOB})
EOD;
Last approach would be to concat the string with .:
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) " .
"VALUES (" . $Forename . ", " . $Surname . ", " . $Email . ", " . $Username . ", " . $Password . ", " . $DOB . ")";
See this reference: http://php.net/manual/de/language.types.string.php
On a side note, don't forget to escape your variables in your mysql query with mysql_real_escape_string to prevent SQL Injection!
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) " .
"VALUES (" . mysql_real_escape_string($Forename) . ", " . mysql_real_escape_string($Surname) . ", " . mysql_real_escape_string($Email) . ", " . mysql_real_escape_string($Username) . ", " . mysql_real_escape_string($Password) . ", " . mysql_real_escape_string($DOB) . ")";
It looks like you're just missing some quote around your sql query.
Something like
$sql= "INSERT INTO `users`(`Forename`, `Surname`, `Email`, `Username`, `Password`, `DOB`)
VALUES (".$Forename.", ".$Surname.", ".$Email.", ".$Username.", ".$Password.", ".$DOB.")";
Should fix your error.
It's also worth nothing that mysql_query is depreciated and can be pretty unsecure. It might be worth looking at PDO preapred statements if this is something that's going to be used in production. Check out http://php.net/manual/en/ref.pdo-mysql.php and Dream in Code PDO

Form data not being sent to MySql database

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.

MySQL query failing due to reserved keyword?

Edit: If you're coming here from Google, this issue is a result of the word int being a reserved keyword in PHP. See the end of the accepted answer.
I'm still learning PHP/MySQL and for the life of me I can't figure out what's wrong with my code.
I'm trying to take some data from an html page and add it to a table in my database. I'm passing the data with a GET request, then retrieving it with PHP's $_GET.
I've tested this and the variables are passed correctly to the PHP script but they don't appear in the database. The script dies on this line:
mysql_query($query) or die('data entry failed');
$database='a9293297_blog';
$con = mysql_connect('mysql2.000webhost.com','my_username','my_password');
mysql_select_db($database,$con) or die('failed to connect to database');
$username = $_GET['username'];
$password = $_GET['password'];
$charName = $_GET['charName'];
$sex = $_GET['sex'];
$class = $_GET['class'];
$race = $_GET['race'];
$str = $_GET['str'];
$sta = $_GET['sta'];
$dex = $_GET['dex'];
$int = $_GET['int'];
$cha = $_GET['cha'];
$query = "INSERT INTO Players (username, password, charName, sex, class, race, str, sta, dex, int, cha)
VALUES ('" . $username . "', '" . $password . "', '" . $charName . "', '" . $sex . "', '" . $class . "', '" . $race . "', '" . $str . "', '" . $sta ."', '" . $dex . "', '" . $int . "', '". $cha . "')";
mysql_query($query) or die('data entry failed'); // Fails here
mysql_close($con);
To know better what's wrong with your SQL query, use mysql_error():
mysql_query($query) or die(mysql_error());
Escape your string variables with mysql_real_escape_string(). Example:
$query = "INSERT INTO MYTABLE(MYFIELD) VALUES ('".mysql_real_escape_string($myVar)."');
EDIT
int seems to be a reserved MySQL keyword. Escape it with backquotes:
INSERT INTO Players (username, password, ..., str, sta, dex, `int`, cha) ...
im not sure but try this
Your Code
$query="INSERT INTO Players (username, password, charName, sex, class, race, str, sta, dex, int, cha)VALUES ('".$username."', '".$password."', '".$charName."', '".$sex."', '".$class."', '".$race."', '".$str."', '".$sta."', '".$dex."', '".$int."', '".$cha."')";
In this code
$query="INSERT INTO Players (username, password, charName, sex, class, race, str, sta, dex, int, cha)VALUES ('$username', '$password', '$charName', '$sex', '$class', '$race', '$str', '$sta', '$dex', '$int', '$cha')";
Maybe this helps if you remove " and .

html insertion in sql table

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

Categories