This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I want to take the POST data from the three form tags and upload variables to mySQL. When I run the PHP on the second page I get a "Parse error: syntax error, unexpected 'VALUES' (T_STRING) in C:\xampp\htdocs\PHPtest\signUpTRUE.php on line 32"
I can try to post the HTML Form Tags and the PHP..
The HTML form tags:
<div id="headingText"><p> New Fan Club Registration</p></div>
<form action="signUpTRUE.php" method="post" >
<div id="firstNameField">First Name:<input type="text" name="fname"></br></div>
<div id="lastNameField">Last Name: <input type="text" name="lname"></br></div>
<div id="emailField">Email: <input type="text" name="email"></br></div>
<div id="checkboxField"><input type="checkbox" name="terms" value="agree" id="checkboxField" required> *Agree to the terms and conditions </input></div>
<button type="submit" value="Submit" id="button">Submit</button>
</form>
Here is the PHP running calls to mySQL:
<?php
$FN = htmlspecialchars($_POST['fname']);
$LN = htmlspecialchars($_POST['lname']);
$EM = htmlspecialchars($_POST['email']);
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "fanClub";
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$sql = "INSERT INTO userInfo (email, firstname, lastname)"
VALUES ($EM, $FN, $LN);
if ($conn->query($sql) === TRUE) {
echo "<p> data enrty has been logged like whoa</p>";
}else {
echo"<p>error in code.</p>";
}
$conn-close();
?>
I get the
"Parse error: syntax error, unexpected 'VALUES' (T_STRING) in C:\xampp\htdocs\PHPtest\signUpTRUE.php on line 32"
when I try to run this.
Thanks a lot for looking at this :D!
$sql = "INSERT INTO userInfo (email, firstname, lastname)"
VALUES ($EM, $FN, $LN);
This line is wrong. It should be:
$sql = "INSERT INTO userInfo (email, firstname, lastname) VALUES ($EM, $FN, $LN)";
Anyways your code is vulnerable to sql injection
The statement
$sql = "INSERT INTO userInfo (email, firstname, lastname)"
VALUES ($EM, $FN, $LN);
should be
$sql = "INSERT INTO userInfo (email, firstname, lastname)
VALUES ($EM, $FN, $LN)";
(Note where the closing quote is.)
Actually, it should be
$sql = "INSERT INTO userInfo (email, firstname, lastname)
VALUES (?, ?, ?)";
and then you can use it as a prepared statement:
$stmt = $conn->prepare($query);
$stmt->bind_param('sss', $EM, $FN, $LN);
$stmt->execute();
The reason why you're seeing that specific error is because on line 32, you're incorrectly calling the close method of your conn class:
$conn-close();
This is missing the closing angle bracket, and should be:
$conn->close();
After you fix this error, you will then most likely see an error for the incorrect SQL formatting as pointed out in the other answers. This will most likely be a function not defined error, as you probably don't have a function called VALUE($a, $b, $c) somewhere.
You have two issues in query
extra double quotes between columns and values.
not using single quotes between string values.
Modified query:
$sql = "INSERT INTO userInfo (email, firstname, lastname) VALUES ('$EM', '$FN', '$LN')";
Side note:
Also check the close function as mentioned in other answer correct your typo error.
The displayed error can be corrected as follows:
$sql = "INSERT INTO userInfo (email, firstname, lastname) VALUES ($EM, $FN, $LN)";
Also please correct the last line as follows:
$conn->close();
Related
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 3 years ago.
When I try to connect to my database, I get this error:
Parse error: syntax error, unexpected 'values' (T_STRING) in
E:\xampp\htdocs\study\connect.php on line 13
This is my php code:
<?php
$firstName = $_POST['fname'];
$middleName = $_POST['mname'];
$lastName = $_POST['lname'];
$password = $_POST['pwd'];
//Database Connection
$conn = new mysqli ('localhost','root','','task1');
if($conn->connect_error){
die('connection failed :' .$conn->connect_error);
}else{
$stmt = $conn->prepare("insert to registration(firstName, middleName, lastName, password")
values(?,?,?,?)
$stmt ->bind_param("ssss",$firstName,$middleName, $lastName, $password);
$stmt ->execute();
echo "Registration Successful..";
$stmt ->close();
$conn ->close();
}
?>
$stmt = $conn->prepare("insert to registration(firstName, middleName, lastName, password")
values(?,?,?,?)
I think you made a mistake.
Try this instead of your code, you missed out ");
$stmt = $conn->prepare("insert to registration(firstName, middleName, lastName, password")
values(?,?,?,?)");
Closing double quote issue, use it as
$stmt = $conn->prepare("insert to registration(firstName, middleName, lastName,
password)
values(?,?,?,?)");
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I have checked for similar questions regarding the error however they didn't match the issue I seem to be having.
Getting the following error when attempting to insert data into database:
Column count doesn't match value count at row 1?
Here is a screenshot of the database table:
In the HTML a form, with an action of the php file, has multiple inputs with the names: name, surname, DateOfBirth, email, password, confirm-password
PHP:
<?php
// Only process the form if $_POST isn't empty
if ( ! empty( $_POST ) ) {
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', '', 'pptpp' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = "INSERT INTO user ( Forename, Surname, DateOfBirth, Email, Password ) VALUES ( '{$mysqli->real_escape_string($_POST['name, surname, DateOfBirth, email, password '])}' )";
$insert = $mysqli->query($sql);
// Print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
// Close our connection
$mysqli->close();
}
?>
The following part
$mysqli->real_escape_string($_POST['name, surname, DateOfBirth, email, password ']
is invalid for two reasons:
mysqli::real_escape_string() takes only 1 argument at a time, a string (unless using procedural, mysqli_real_escape_string(), then the first is the connection, then the string as the second)
The $_POST can't be accessed in that way, I highly doubt you have one field named all that. You'll have to specify the index, as $_POST['name'] etc.
The solution is to match each column with the respective escaped value from $_POST,
like $mysqli->real_escape_string($_POST['name']) for the name,
$mysqli->real_escape_string($_POST['email']) for the email and so on, an example could be assigning it to variables, and using those in the query, as shown below.
$name = $mysqli->real_escape_string($_POST['name']);
$surname = $mysqli->real_escape_string($_POST['surname']);
$dob = $mysqli->real_escape_string($_POST['DateOfBirth']);
$email = $mysqli->real_escape_string($_POST['email']);
$password = $mysqli->real_escape_string($_POST['password']);
$sql = "INSERT INTO user (Forename, Surname, DateOfBirth, Email, Password) VALUES ('$name', '$surname', '$dob', '$email', '$password')";
$insert = $mysqli->query($sql);
Then you should note that even with mysqli::real_escape_string(), it's not secure against SQL injection, and that you should use parameterized queries. An example of that is given below.
// Insert our data
$sql = "INSERT INTO user (Forename, Surname, DateOfBirth, Email, Password) VALUES (?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("sssss", $_POST['name'], $_POST['surname'], $_POST['DateOfBirth'], $_POST['email'], $_POST['password']);
if (!$stmt->execute())
die("Execution failed: ".$stmt->error);
echo "Success! Row ID: ".$stmt->insert_id;
$stmt->close();
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
Usage of PHP error-reporting would've likely mentioned something about undefined indexes when you use the current escape. Always (in development) let PHP give you the errors, by enabling error-reporting with error_reporting(E_ALL); ini_set("display_errors", 1); at the top of your file.
Also note that storing passwords in plain-text is a big no. You should use functions like password_hash() / password_verify() to properly and securely store your users passwords.
References
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/mysqli-stmt.prepare.php
How can I prevent SQL injection in PHP?
I'm trying to pull information from an HTML form and put this into a database using the following code:
$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page
ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', 'test#email.com', '2003-02-01'
'address'). Column count doesn't match value count at row 1
I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on.
There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately!
Given the syntax error you have in your query, being a missing comma in '$dob' '$addr'; you are open to an SQL injection and should be using a prepared statement.
Therefore, I am submitting this complementary answer for your own safety.
Here is an example of a prepared statement using the MySQLi API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
// assuming these are the POST arrays taken from your HTML form if you're using one.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$addr = $_POST['addr'];
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
$stmt = $link->prepare($sql) or die("Failed Execution");
$stmt->bind_param('ssss', $fullname, $email, $dob, $addr);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
References:
How can I prevent SQL injection in PHP?
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Foonotes:
If using the following failed because of the AI'd column:
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
You may also try: (I used id as the AI'd column as an example)
$sql = ("INSERT INTO interest (id, name, email, dob, address) VALUES ('', ?, ?, ?, ?)");
This could be the case, as I have seen this type of SQL failure behaviour before.
You have missed comma here:
VALUES ('$fullname', '$email', '$dob' '$addr')
Thus (as it was clearly said in error text) column count doesn't mach values count.
It should be
VALUES ('$fullname', '$email', '$dob', '$addr')
You missed a comma
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob', '$addr')";
^here
You missed a comma:
VALUES ('$fullname', '$email', '$dob' '$addr')
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.
I'm sending data from a form to a php script which should connect to a database and then update the table. It's basically a database of all registered users. For some reason, the database table is not getting updated with the values.
The form code is :
<body>
<div class="header">
Registration
</div>
<div class="content" style="text-align:center";>
<form name="input" action="success.php" method="post"><br>
First name: <input type="text" name="firstname"><br/>
Last name: <input type="text" name="lastname"><br/>
Age: <input type="text" name="age"><br/>
Date of Birth: <input type="text" name="dateofbirth"><br/>
Email: <input type="text" name="email"><br/>
<input type="submit" value="Submit"><br/><br>
</form>
</div>
<br><br><a href="index.html" style="font-size: 22px";>Back</a>
</body>
And the php code I have is:
<?php
$con=mysqli_connect("example.com","myname","123","database1");
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
mysqli_query($sql);
mysqli_close($con);
?>
Can someone please tell me where I'm going wrong?? The Database is not getting updated. There are no values being entered into my table.
Firstly, PLEASE use something like PDO or mySQLi's prepared statements.
Secondly, the database isn't getting updated because you need to concatenate (again, don't do this, please!) the values, like so:
$sql="INSERT INTO user (...) VALUES (".$_POST['firstname'].",".$_POST[]."...)";
This is very dangerous though, so I highly...highly recommend looking into PDO.
Also
The syntax for mysqli_query is wrong as stated in the comments on your post.
Try putting curly braces around the $_POST[...]
Like
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('{$_POST[firstname]}','...
change
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
to
$sql="INSERT INTO user
(fname, lname, age, dob, email) VALUES
('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['age']."','".$_POST['dateofbirth']."','".$_POST['email']."')";
Always check for errors when you run SQL statements. You'll never know what's going wrong unless you check whether the query was successful or not, and then print the error.
Also as other folks have commented, please don't include $_GET or $_POST variables directly in your SQL. This exposes you to getting hacked.
Here's an example of the proper way to code this:
<?php
$con=mysqli_connect("example.com","myname","123","database1");
if ($con->connect_error) {
trigger_error($con->connect_error, E_USER_ERROR);
}
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES (?, ?, ?, ?, ?)";
if (($stmt = $con->prepare($sql)) === false) {
trigger_error($con->error, E_USER_ERROR);
}
$stmt->bind_param("sssss", $_POST["firstname"], $_POST["lastname"],
$_POST["age"], $_POST["dateofbirth"], $_POST["email"]);
if ($stmt->execute() === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
$con->close();
?>
Now if there's a problem preparing or executing the query, it'll report it to you.
Create prepared statements is not that hard. Simply copy paste and you are good. I added some extra security with escapeshellarg, which should be more used then it is since prepared statements isn't always 100% secure.
<?php
$firstname = escapeshellarg($_POST["firstname"]);
$lastname = escapeshellarg($_POST["lastname"]);
$age = escapeshellarg($_POST["age"]);
$dateofbirth = escapeshellarg($_POST["dateofbirth"]);
$email = escapeshellarg($_POST["email"]);
$con=mysqli_connect("example.com","myname","123","database1");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_stmt_init($con);
$query = "INSERT INTO user (fname, lname, age, dob, email) VALUES (?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "sssss", $firstname, $lastname, $age, $dateofbirth, $email);
if(mysqli_stmt_execute($stmt))
{
mysqli_close($con);
}
?>
Note that "sssss" stands for Strings. If your age is an int variable then use "ssiss" instead.
PS. A simple mistake I had once with WAMP (Apache) was that the user didn't have the right privileges. It took me way too many hours to find that, don't do the same mistake ;)
Tested
I created a table with the same entries that you posted and have come to this conclusion.
But first; as others have pointed out and it's been said time and time again, the use of MySQL_ is being deprecated and will be deleted in the very near future. Therefore using MySQLi_ and/or PDO is strongly and highly recommended.
To quickly fix your problem, you are not telling it to connect to your DB when passing query.
Change:
mysqli_query($sql);
to:
mysqli_query($con, $sql);
and it will work. It worked for me, therefore theoretically it will work for you also.
I suggest you use Bill Karwin's version for better security.