SQL Near error for inserting data through HTML form - php

I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a 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 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>

Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement

You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.

Related

PHP Insert Command not working

Hi guys can you please tell me if there is an error on this code. this is not working. it didn't add any on my database. thanks you!
$con = mysql_connect("localhost","root","pass");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mytable",$con);
if(isset($_POST['add'])){
// Variables
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('$acc_class')";
mysql_query($AddQuery, $con);
echo "Record Successfully Added!!";
};
mysql_close($con);
?>
<form action="add.php" method="post">
Account Classification:
<input required="required" placeholder="e.g Hotel, Restaurant" type="text" name='acc_class' size=15 />
<input type="submit" name='add' Value=' Add Record '/>
</form>
The column name(s) should be wrapped in backticks and not quotes
$AddQuery = "INSERT INTO mytable (`acc_class`) VALUES ('$acc_class')";
or remove the quotes
$AddQuery = "INSERT INTO mytable (acc_class) VALUES ('$acc_class')";
I suggest you move to mysqli_* functions with prepared statements or PDO.
and that you change $acc_class = $_POST['acc_class']; to
$acc_class = mysql_real_escape_string($_POST['acc_class']);
for the time being.
mysql_* functions are deprecated and will be removed from future PHP releases.
At a minimum:
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('$acc_class')";
Should be:
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('".$acc_class."')";
Also, it is unsafe to pass raw user input into to a SQL query in this way. Please read up on SQL Injection.

Insert Into mysql using php

I am working with php and mysql for the first time. The goal is to have a table that store email addresses to form a mailing list for a newsletter. my table Emails has 2 columns ID (INT auto increment) and email (varchar, 255)
I can connect to the database but I cannot write to it. I think my problem is in the syntax of my INSERT INTO statement. I have seen many examples and they seem to use different syntax specifically around the values.
form code:
<form method="post" action="email.php" class="form-container">
<div class="form-title"><h2>Sign up for my newsletter!</h2></div>
<div class="form-title">Email Address</div>
<input class="form-field" required="required" placeholder="example#mail.com" type="text" name="newEmail" /><br />
<div class="submit-container">
<input class="submit-button" type="submit" value="Submit" /></div>
</form>
php code:
<?php
$dbHost = "localhost";
$dbUser = "input";
$dbPass = "input";
$dbName = "MailingList";
$conn= mysqli_connect ($dbHost, $dbUser, $dbPass, $dbName);
if(mysqli_connect_errno()) {
die("FAIL:". mysqli_connect_error() . "(" . mysqli_connect_errno() . ")");
}
$addEmail = "mysqli_real_escape_string($_POST['newEmail'])";
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')"
mysqli_close($conn)
?>
You have missed to add the $conn i.e database link to the mysqli_real_escape_string and also, you have wrapped the mysqli_real_escape_string() inside the ", so it consider as string. So remove the " and use it. Try this,
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
......^
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')";
instead of
$addEmail = "mysqli_real_escape_string($_POST['newEmail'])";
You need to execute the query, not just write it.
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')";
mysqli_query($conn, $query);
If you use a prepared statement, you can save yourself the trouble of escaping:
$stmt = mysqli_prepare($conn, "INSERT INTO Emails (email) VALUES (?)");
mysqli_stmt_bind_param($stmt, "s", $_POST['newEmail']);
mysqli_stmt_execute($stmt);
If you want non-procedural style (aka oop), this would look like the following
$stmt = $conn->prepare("INSERT INTO Emails (email) VALUES (?)");
$stmt->bind_param("s", $_POST['newEmail']);
$stmt->execute();
Get rid of the quotes around your escape function. This turns it into a string instead of actually escaping the value:
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
http://in2.php.net/mysqli_real_escape_string
string mysqli_real_escape_string ( mysqli $link , string $escapestr )

PHP MySQL Insert Form not working

I have a MySQL database named "culvers" with a user_id INT(4) auto incrementing, a full_name varchar(20) and a user_name varchar(20). I am trying to use this HTML form to add values to the table, but it is not working. I have explored dozens of tutorials and help sites, and it still isn't working. I even put the code on another hosting provider to see if that was the problem. When I click "add" I am taken to a blank page (which is expected, since I don't have a success/error message) but the form data does not insert into the database table.
Also, I know I should sanitize my inputs, but that's not the issue right now. (At least I don't think so)
Here's the form.html code:
<html>
<head>
<title>Add User to Table</title>
</head>
<body>
<h1>Add User</h1>
<form action="adduser.php" method="POST">
<label>Full name:</label>
<input id="postname" type="text" name="fullname">
<label>Username:</label>
<input id="postuser" type="text" name="username">
<input type="submit" name="submit" value="Add">
</form>
</body>
</html>
And here's the adduser.php code:
<?php
if(isset($_POST['submit'])){
$connection = mysql_connect("localhost", "xxxx", "xxxxxxxxxx");
mysql_select_db("culvers");
$fullnameOfUser = $_POST['fullname'];
$usernameOfUser = $_POST['username'];
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
$result = mysql_query($sql, $connection);
mysql_close($connection);
}else{
echo "Error no form data";
}
?>
Thank you very much for your help!
you have error in this line :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
you did not have ending "
this line should be :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You should use mysqli_* or PDO since all functions of mysql_* are deprecated.
You miss the double Quotes at the end of SELECT Query
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
First if it is not a typo the you need to add a double quote to query.
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
if still issue remains then print query and run it directly in phpmyadmin to see there is not issue with query.
Note: you are using mysql_* function. Please used PDO or Mysqli as your current code is prone to Sql Injection.
PDO Link: http://php.net/manual/en/book.pdo.php
Before submitting your form data, you need to start the mysql server.
you can start mysql server by the use of xampp software. once you have started your mysql server through xampp software, you can find the mysql server port number also.
the actual format of including the database is,
mysql_connect("localhost:port/database","username","password");
You forgot to close the double quotes !
'$fullnameOfUser', '$usernameOfUser')";
----^ // Add one there
The right code.
$sql = "INSERT INTO `users` (`full_name`, `user_name`) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You need to switch to PreparedStatements seriously as the above code of yours is directly prone to SQL Injection.

MySQL error on form submission

I'm getting a mysql error saying "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..."
Here's the basics of my code:
First I'm populating the select menu options with rows from the categories table. This is working fine:
<select id="dropdown-select" name="Name">
<option value="" id="dropdown-option">Please select a category.</option>
<?php
$query_categories = "SELECT * FROM categories";
$result_categories = mysql_query($query_categories) or die(mysql_error());
while($categories_row = mysql_fetch_array($result_categories)) {
echo '<option id="dropdown-option" value="' . $categories_row['cat_name'] . '">' . $categories_row['cat_name'] . '</option>';
}
?>
</select>
Later, when I go submit the form to the transactions table (the above table I pulled data from was the categories table, could this be a problem?) is when I get the error. I think its related to the above code bc if I remove this element from my form submission, it writes the rest of the values to the database without any errors.
if(!isset($_POST['Name'])) {
die('You must select an income or expense from the drop down menu.');
} else {
$Name = $_POST['Name'];
}
//create query
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
$result = mysql_query($query) or die("Error in query: $query. " . mysql_error());
Thanks for any help you can provide.
You are missing a single quote in your insert statement before $Budgeted
INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', '$Budgeted', '$Actual')"
If you have some fields which are defined in Database as VARCHAR, CHAR.
Also, if you are inserting a string value in Database from a PHP script, you need to add an enclosing single quote (') around it.
In your case, you are inserting a string without semicolons, so, it showing error in MySQL.
Your statement should be corrected by adding a single quote around $budget as:
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month',
'$Name', '$Budgeted', '$Actual')";
------^
The error "You have an error in your SQL syntax" is exactly correct!
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual)
VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
Look here, you missed something ----^
There is a ' missing from your statement causing the syntax error. Put the single quote in and you should be good to go!

Insert into MySQL Table PHP

I am having some trouble making a simple form to insert data into a MySQL table. I keep getting this SQL 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 'stock ('ItemNumber', 'Stock') VALUES ('#4','3'')' at line 1"
My HTML for the form is:
<form action="database.php" method="post">
Item Number: <input type="text" name="ItemNumber">
Stock: <input type="text" name="Stock">
<input type="submit">
</form>
And the PHP is:
<?php
$con=mysqli_connect("localhost","root","root","inventory");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
try this
you should not use quotes of parameter around POST . and you should use them inside POST
$sql = "INSERT INTO `current stock` (ItemNumber, Stock)
VALUES
('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";
you should escape your variables before you insert them to mysql like that
Note that the example does not call mysqli_real_escape_string. You would only need to use mysqli_real_escape_string if you were embedding the string directly in the query, but I would advise you to never do this. Always use parameters whenever possible.
You have an extra quote and you need ticks around your table name as it contains a space.
INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";
should be:
INSERT INTO `current stock` (`ItemNumber`, `Stock`)
VALUES
('$_POST[ItemNumber]','$_POST[Stock]')";
FYI, you also wide open to SQL injections
?php
$conn=new mysqli("localhost","root","","inventory")
or die("not connected".mysqli_connect_error());
if(isset($_POST['submit']{
$ItemNumber=$_POST['ItemNumber'];
$Stock=$_POST['Stock'];
$sql="insert into current stock(ItemNumber,Stock) values('$ItemNumber','$Stock')";
$query=mysqli_query($conn,$sql);
if($query){
echo"1 row inserted";
}else{
echo mysqli_error($conn);
}
}
?>
Please learn to use parameter binding. You are creating code with security vulnerabilities.
Here's how to do your code in mysqli:
$sql = "INSERT INTO current stock (ItemNumber, Stock) VALUES (?, ?)";
if (!($stmt = mysqli_prepare($con, $sql))) {
die('Error: ' . mysqli_error($con));
}
if (!mysqli_stmt_bind_param($stmt, "ii", $_POST[ItemNumber], $_POST[Stock])) {
die('Error: ' . mysqli_stmt_error($stmt));
}
if (!mysqli_stmt_execute($stmt)) {
die('Error: ' . mysqli_stmt_error($stmt));
}
It's easier to use bound parameters than to get all confused with quotes-within-quotes.
<form action="database.php" method="post">
Item Number: <input type="text" name="ItemNumber">
Stock: <input type="text" name="Stock">
<input type="submit" name="submit">
</form>`

Categories