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
Related
I am submitting form values into a database using PHP but I am running into an issue when user's enter special characters such as an apostrophe. For example if someone enters Bill's Pet Supply into organization, there will be an SQL error.
Here is my code:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$organization = $_POST['organization'];
$sql = $conn->prepare("INSERT INTO submissions VALUES (:firstname, :lastname, :email, :organization)");
$sql->bindValue(':firstname', $firstname);
$sql->bindValue(':lastname', $lastname);
$sql->bindValue(':email', $email);
$sql->bindValue(':organization', $organization);
$sql->execute();
}
$conn->close();
How can I change this code so that apostrophes and other special characters will be supported?
Use prepared statements with bind placeholders. Both PDO and mysqli provide support for those.
Your SQL text would look like this:
$sql = "INSERT INTO submissions (firstname, lastname, email, organization)
VALUES (?, ?, ?, ?)";
If you are using mysqli
mysqli_prepare
myslqi_bind_param
myslqi_execute
$sth = $mysqli->prepare($sql);
if(!$sth) {
// handle error
}
$sth->bind_param("ssss", $firstname, $lastname, $email, $organization);
if( $res = $sth->execute() ) {
// process resultset
}
Similar functions available in PDO, but you can use "bind value" instead of "bind param".
If there's some reason you can't use prepared statements with bind placeholders, then at a minimum, you will need to properly escape any potentially unsafe values included in the SQL text.
If you are using mysqli, then generating the SQL text would look something like this:
$sql = "INSERT INTO submissions (firstname, lastname, email, organization)
VALUES ('" . $mysqli->real_escape_string( $firstname )
. "', '" . $mysqli->real_escape_string( $lastname )
. "', '" . $mysqli->real_escape_string( $email )
. "', '" . $mysqli->real_escape_string( $organization )
. "')";
But don't do that. Use a prepared statement with bind placeholders.
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I have create a sign-up form which receives username, email and password.
I coded like this:
include_once 'sqlConnect.php';
$userName = $_POST['userName'];
$eMail = $_POST['eMail'];
$passWord = $_POST['passWord'];
$day = date("d-m-Y");
$time = date("h:i:sa");
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')';
$result = mysql_query($dbINSERTuser);
if ($result) {
echo "New record created successfully";
}
else {
echo mysql_error($dbINSERTuser);
}
In the end, it gave me this error:
Parse error: syntax error, unexpected '$userName' (T_VARIABLE) in G:\XAMPP\htdocs\Project EVO 1.0\signup.php on line 17
I have been looking at this for hours and still not finding any solution. Please help!
PHP will evaluate variables values in the string, only when your string is wrapped with double quotes.
Change this:
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')';
To this:
$dbINSERTuser = "INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')";
But be aware - this code is vulnerable to SQL injections!
UPDATE:
Learn how to use PHP's PDO and prepared statements to make you queries safe.
Just replace ' with " in your insert query
$dbINSERTuser = "INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')";
To prevent sql injection use
$dbINSERTuser = "INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('".$userName."', '".$eMail."', '".$passWord."', '".$time."')";
IN mysqli you can use like that way
<?php
$link = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$userName = $_POST['userName'];
$eMail = $_POST['eMail'];
$passWord = $_POST['passWord'];
$day = date("d-m-Y");
$time = date("h:i:sa");
$dbINSERTuser = "INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('".$userName."', '".$eMail."', '".$passWord."', '".$time."')";
mysqli_query($link, $query);
Read mysqli manual
you forgot to concat string
change
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')';
to
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE (' . $userName . ', ' . $eMail . ', ' . $passWord . ', ' . $time .')';
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE (''.$userName.'', ''.$eMail.'', ''.$passWord.'', ''.$time.'')';
Change as above
Try This.
<?php
$userName = mysql_real_escape_string($_POST['userName']);
$eMail = mysql_real_escape_string($_POST['eMail']);
$passWord = mysql_real_escape_string($_POST['passWord']);
$day = mysql_real_escape_string(date("d-m-Y"));
$time = mysql_real_escape_string(date("h:i:sa"));
?>
Does anyone see anything that is wrong with this. It isn't posting to database at all. There is a basic form asking for name and address on the page. But after submitting the form it just goes to a blank page.
Here is my code. There is stuff above this that reaches out to an API to validate the address data and declares the variables. The dedup part of the code is working in case that matters.
if(empty($errorMessage))
{
// Dedupe the entry into the form
$dupesql = "SELECT * FROM formData WHERE (name = '$full_name' AND address = '$primary_number' AND city = '$city_name' AND state = '$state_abbreviation' AND zip = '$zipcode_full' )";
$duperaw = $mysqli->query($dupesql);
if($duperaw->num_rows > 0) {
$dupe .= "$full_name already exists on $primary_number \n";
}
else {
$sql = "INSERT INTO formData(name, address, city, state, zip, date) VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssssss", $full_name, $primary_number, $city_name, $state_abbreviation, $zipcode_full, $date);
$stmt->execute();
header("location: index.php?success=1");
exit();
}
}
I have also tried using a query instead of a prepared statement but this just gives the success message and doesnt post to the DB
$sql = "INSERT INTO fromData (name, address, city, state, zip, date) VALUES (".
$full_name . ", " .
$primary_number . ", " .
$city_name . ", " .
$state_abbreviation . ", " .
$zipcode_full . ", " .
$date . ")";
$mysqli->query($sql);
Any help would be great!
Try this SQL
$sql = "INSERT INTO fromData (name, address, city, state, zip, date) VALUES ('$full_name', '$primary_number', '$city_name', '$state_abbreviation', '$zipcode_full', '$date')";
$mysqli->query($sql);
cHao was hinting towards it
So I am trying to create a form that puts data in a table, and I got it to work, but when it goes to the table, it just creates empty rows. Here is my code, please help me out.
form.php
<form action="tableinsert.php" method="post">
First Name:<input type="text" name="fname"> <br/>
Last Name:<input type="text" name="lname"><br/>
Username:<input type="text" name="uname"><br/>
Password:<input type="text" name="password"><br/>
Email:<input type="text" name="email"><br/>
</form>
tableinsert.php
<?php
$sc = mysqli_connect ("localhost" , "dbname" , "password");
if (mysqli_errno($sc))
{
echo "Sorry, I couldn't connect to the database. If you keep getting this error, please email the webmaster at natashaharrell#hotmail.com " . mysql_error;
}
$si = "INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ('$_POST[fname]' , '$_POST[lname]' , '$_POST[uname]' , '$_POST[password]' , '$_POST[email]' )";
if (!mysqli_query($sc, $si))
{
echo "Sorry there seems to be a problem: " . mysqli_errno($sc) ;
}
else
{
echo "1 record added.";
}
mysqli_close($sc);
?>
Try that
$si = "INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ('".$_POST["fname"]."' , '".$_POST["lname"]."' , '".$_POST["uname"]."' , '".$_POST["password"]."' , '".$_POST["email"]."' )";
you might be getting empty row because the form is getting filled with empty values and gets submitted automatically each time you load the page. you should use submit button.
Use mysqli prepare() http://php.net/manual/en/mysqli.prepare.php to insert data into your SQL queries.
There are a lot of simple mistakes that novices can make, to render their code vunerable to security issues, thats why mysql_* has been depreciated
<?php
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO sdb_users (fname, lname, uname, password, email) VALUES ( ?, ?, ?, ?, ? )")) {
/* bind parameters for markers */
$stmt->bind_param("s", $_POST["fname"]);
$stmt->bind_param("s", $_POST["lname"]);
$stmt->bind_param("s", $_POST["uname"]);
$stmt->bind_param("s", $_POST["password"]);
$stmt->bind_param("s", $_POST["email"];
/* execute query */
$stmt->execute();
?>
Replace this
$si = "INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ('$_POST[fname]' , '$_POST[lname]' , '$_POST[uname]' , '$_POST[password]' , '$_POST[email]')";
With this:
$si = 'INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ("' . $_POST['fname'] . '", "' . $_POST['lname'] . '" , "' . $_POST['uname'] . '", "' . $_POST['password'] . '", "' . $_POST['email'] . '")';
That fixes your actual problem, but as an aside, wrap each of those POST values in MySQLi's string escaping function (I'm a PDO user, but I believe it's MySQLi::real_escape_string). That helps protect you from SQL injection.
The reason it wasn't working is you didn't put the array key in quotes. I changed from double quotes to single, because it's easier to escape values and saves PHP having to process the magic-quoted string.
Firstly, it is a a convention to store the values obtained from the form fields into variables. Do that. Then after that you must clean up the values you got from the text fields. Basically you must clear it of all unexpected stuff like SQL injections (complex stuff). To do that you must use MySQL real escape string. After that is done, substitute the variables in the place of your earlier variables such as $_POST['fname'] or $_POST['lname'].
Hopefully after this you will have a script that works fully.
The values you are using in the query are not correct. Try it this way.
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$pwd = $_POST['password'];
$email = $_POST['email']
$si = "INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ('$fname' , '$lname' , '$uname' , '$pwd' , '$email' )";
EDIT:
Use mysql_real_escape_string() function to sanatize the data before inserting.
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