HTML code
<form id="form1" name="addAnnouncement" method="post" action="ownerAddAnnouncement_exec.php" onsubmit="return validateForm()">
<label style="font-size:18px">Title:
<input type="text" name="title" />
</label>
<p>
<label style="margin-left: -36px; font-size:18px;">Description:
<textarea name="description" rows="6" cols="60"></textarea>
</label>
</p>
<label style="font-size:18px">Date & Time: <br>
From
<input type="text" name="from" /> <br>
To <input type="text" name="to" />
</label> <br>
<label style="font-size:18px">Venue
<input type="text" name="venue" />
</label>
<p>
<label>
<input type="submit" name="Submit" value="Submit" />
</label>
</p>
</fieldset>
</form>
PHP code
<?php
$title = $_POST['title'];
$description = $_POST['description'];
$from = $_POST['from'];
$to = $_POST['to'];
$venue = $_POST['venue'];
$link = mysql_connect("localhost","root","") or die();
$db = mysql_select_db("condo") or die("no database found");
$insert_sql="INSERT INTO announcement (title, description, from, to,venue, status)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
$sql_result=mysql_query($insert_sql) or die("Error in inserting data due to ".mysql_error());
if($sql_result)
echo "Succesfully insert new data. Please log in back";
else
echo "Error in inserting new data";
?>
an error like this ("Error in inserting data due to 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 'from, to, status) VALUES('melvin', 'sdsaadsd', 'wew', 'ewrerw', 'we3', 'Pendi' at line 1" )
is show out when try to insert a data into database.
Anyone please help me fix the code.i have been stuck at here for 1 hour.
Display the field names with in ``.
Convert the insert statement to
$insert_sql="INSERT INTO announcement (`title`, `description`, `from`, `to`,`venue`, `status`)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
You should escape reserved keywords using backticks. Currently, you are using the following reserved keywords - From and To Try this :-
$insert_sql="INSERT INTO `announcement` (`title`, `description`, `from`, `to`,`venue`, `status`)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
From is a keyword. And also To. It is not recommended to use them. But if you can't avoid it and still want to use them, add backquote ` like below in your insert query :
INSERT INTO announcement (`title`, `description`, `from`, `to`, `status`)
VALUES('$title', '$description', '$from', '$to', 'Pending')
Hope this helped.
Regarding current error it is about reserved keywords like from as field name, so to avoid it either rename your db column or enclose it in back-quotes like `from`
further you may face other errors as you are ignoring many good practices in your code, for example
Validate user input before inserting into db
remember to escape user input (sql injection)
enclose field names in back-quotes
and many others see http://code.tutsplus.com/tutorials/30-php-best-practices-for-beginners--net-6194
Related
I am trying to post some data from my HTML form into my mysql database.
Here is my HTML code:
<!doctype html>
<html>
<head>
</head>
<body style="background-color:#BCB7B7">
<form id="form1" name="form1" method="post" style="text-align:center" action="post.php">
<input type="text" name="name" id="name" placeholder="Name">
<p></p>
<input type="text" name="age" id="age" placeholder="Age">
<p></p>
<input type="text" name="food" id="food" placeholder="Food">
<p></p>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</body>
</html>
and here is my php code:
<?php
$connect = mysql_connect("localhost","myusername","mypassword","mydbname");
mysql_select_db("mydbname",$connect);
mysql_query("INSERT INTO myTable VALUES Name = $_POST[name], Age = $_POST[age], Food = $_POST[food]");
?>
but the data does not get saved
Strings in SQL must be quoted. You are dumping your variables into the SQL without quotes.
Your syntax is also wrong. The format is INSERT INTO table_name (column_name, column_name) VALUES value, value.
You are also failing to escape the data, so you are vulnerable to SQL Injection attacks.
To fix your problems:
Stop using the deprecated mysql_ library and switch to mysqli_ or PDI
Use bound arguments to insert variables into your SQL
Use the correct syntax
This question about preventing SQL injection has examples of how to use those libraries safely.
There are 2 different versions of the INSERT command - you are using neither.
Either:
INSERT INTO myTable SET Name = "Peter",
Age = 15, Food = "pizza"
or
INSERT INTO myTable (Name, Age, Food) VALUES
("Peter", 15, "pizza")
You have to quote the values:
mysql_query("INSERT INTO myTable VALUES Name = '$_POST[name]', Age = '$_POST[age]', Food = '$_POST[food]'");
Hint: You should use mysqli_ or PDO_ functions as mysql_ functions are deprecated
try this
<?php
$connect = mysql_connect("localhost","myusername","mypassword","mydbname") or die("error while connecting to the database");
mysql_select_db("mydbname",$connect) or die("error while selecting the database");
mysql_query("INSERT INTO myTable VALUES ('" . mysql_real_escape_string($_POST[name]) . "', '" . mysql_real_escape_string($_POST[age]) . "', '". mysql_real_escape_string($_POST[food]) . "')");
?>
This question already has answers here:
PHP not posting information from database
(2 answers)
Closed 8 years ago.
I'm trying to add information to a database via PHP. However, when you submit the form it says "Error adding program." I've looked at the code and can't seem to find what's causing the error. Any advice?
Here's the form code:
<form name="Add" id="Add" method="post" action="programadd.php">
<p>Program Name:
<input name="program" type="text" id="program" />
</p>
<p>Air Date
<input name="air date" type="text" id="airdate" />
</p>
<p>Description
<input name="description" type="text" id="description" />
</p>
<p>Production
<input name="production" type="text" id="production" />
</p>
<p>Promotions
<input name="promotion" type="text" id="promotion" />
</p>
<p>Community
<input name="community" type="text" id="community" />
</p>
<p>Web
<input name="web" type="text" id="web" />
</p>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
And here's the code that adds the info into the db.
<?php require_once("db_connx.php");
$program = $_POST['Program'];
$airdate = $_POST['Air Date'];
$description = $_POST['Description'];
$production = $_POST['Production'];
$promotion = $_POST['Promotions'];
$community = $_POST['Community'];
$web = $_POST['Web'];
if (mysql_query ("INSERT INTO 'Content Calendar' (Program, 'Air Date', Description, Production, Promotions, Community, 'Web') VALUES ('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')"))
{ echo "Program successfully added to the database <br />";
}
else
{ echo "Error adding program"; }
require_once("db_connx_close.php");
?>
Do not use single quotes on column names , use backticks instead or let them be as it is.
The right way...
mysql_query ("INSERT INTO `Content Calendar` (`Program`, `Air Date`, `Description`, `Production`, `Promotions`, `Community`, `Web`) VALUES ('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')")
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !
Here is the issues
INSERT INTO
'Content Calendar' <--
(
Program,
'Air Date', <--
Description,
Production,
Promotions,
Community,
'Web' <--
They should all be enclosed with `` as
INSERT INTO
`Content Calendar`
(
Program,
`Air Date`,
Description,
Production,
Promotions,
Community,
Web
Thumb rules :
if you have a table name or colum name as "Some Name" meaning a space
in between then you must enclose them with back ticks ``
If you are using any reserved keywords they also must be enclosed
within backticks
http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
Change these lines
if (mysql_query ("INSERT INTO 'Content Calendar' (Program, 'Air Date', Description, Production, Promotions, Community, 'Web') VALUES ('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')"))
{ echo "Program successfully added to the database <br />";
}
else
{ echo "Error adding program"; }
To
if (mysql_query ("INSERT INTO `Content Calendar` (`Program`, `Air Date`, `Description`, `Production`, `Promotions`, `Community`, `Web`) VALUES ('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')"))
{ echo "Program successfully added to the database <br />";
}
else
{ echo "Error adding program"; }
<form method="post" action="updatescreen(2).php">
Name of company:<br />
<input type="text" name="artid" id="artid" size="50" /><br /><br />
<input type="submit" name="Insert" id="Insert" value="Insert" /><br /><br />
<?php
if(isset($_POST['Insert'])){
$id = $_POST['artid'];
mysql_query("INSERT INTO test (id) VALUES ('$id', )");
}
?></form>
The connection to the database is included so not mentioned here. The connection is working fine, that's not the problem.
The problem is: the php code doesn't work. The php code doesn't insert the data into my database. What's wrong?
You had a , after '$id':
mysql_query("INSERT INTO test (id) VALUES ('$id')");
Your code is also open to SQL injection. You should be using something like PDO instead of the mysql_* functions, which are deprecated. With PDO, you can guard against SQL injections by using prepared statements.
Change
mysql_query("INSERT INTO test (id) VALUES ('$id', )");
to
mysql_query("INSERT INTO test (id) VALUES ('$id')");
You have one comma too many.
mysql_query("INSERT INTO test (id) VALUES ('$id')");
In future, try printing the error, which will help you debug the problem yourself:
mysql_query("INSERT INTO test (id) VALUES ('$id')") or die(mysql_error());
And please use PDO or mysqli instead of the mysql_ functions, which are insecure and deprecated.
Try
<?php if(isset($_POST['Insert'])){
$id = $_POST['artid'];
mysql_query("INSERT INTO test (id) VALUES ('".$id."')")or die(mysql_error());
}?>
<form method="post" action="updatescreen(2).php">
Name of company:<br />
<input type="text" name="artid" id="artid" size="50" /><br /><br />
<input type="submit" name="Insert" id="Insert" value="Insert" /><br /><br />
And => think about the safety!
Errors:
mysql_query("INSERT INTO test (id) VALUES ('$id', )");
^---not secure, potencial sql injection
^----not need ","
Use this code for more security (most of all better pdo or mysqli):
if(isset($_POST['Insert'])){
$id = mysql_real_escape_string($_POST['artid']);
mysql_query("INSERT INTO test (id) VALUES ('$id')");
}
<?php
$conn= new mysqli("localhost", "my_user", "my_password", "world"); //changed for the sake of this question
$username = $_POST['Username'];
$password = sha1($_POST['Password']);
$email = $_POST['Email'];
$firstname = $_POST['FirstName'];
$lastname = $_POST['LastName'];
$insert = 'INSERT INTO User(FirstName, LastName, Email, Username, Password, Type) VALUES ("'.$firstname.'", "'.$lastname.'", "'.$email.'", "'.$username.'", "'.$password.'", 'User');';
$result = $conn->query($insert);
?>
<form method='post' action='regprocess.php'>
<fieldset class="register">
<h2>Register</h2>
<ul>
<li><label for="FirstName">First Name: </label> <input type="text" name="FirstName" id="FirstName"></li>
<li><label for="LastName">Last Name: </label> <input type="text" name="LastName" id="LastName"></li>
<li><label for="Email">Email: </label><input type="email" name="Email" id="Email"></li>
<li><label for="Username">Username: </label><input type="text" name="Username" id="Username"></li>
<li><label for="Password">Password: </label><input type="password" name="Password" id="Password"></li>
<li><input type="submit" value="Register"></li>
</ul>
</fieldset></form>
The form and the top sql code are in separate files.
Hello everybody, I'm trying to insert into an mysql table, and it won't insert into my table. I'm trying to get it to insert through a registration table. And I'm not quite sure why it's not working. Some insight would be great. If you need me to provide the table I will, but I don't think it's part of the reason it's not working.
It's a good thing you're using mysqli, but you're using it incorrectly and are exposing yourself to a number of very serious SQL injection bugs, the consequences of which could be severe.
This is what you should be doing to actually fix the numerous problems present in your example:
$stmt = $conn->prepare('INSERT INTO User(FirstName, LastName, Email, Username, Password, Type) VALUES (?,?,?,?,?,?)');
$stmt->bind_param($firstname, $lastname, $email, $username, $password, 'User');
$stmt->execute();
$result = $stmt->get_result();
The primary advantage of placeholders is not having to worry about how to properly quote data, it's done for you automatically. It also largely avoids having to use two different kinds of quotes within your statement.
If you do not use placeholders for ANY and ALL data being put into your SQL you may end up in serious trouble. You must be vigilant about this.
Your last parameter value is in single quotes. Replace with double quotes so that it reads ..."'.$password.'", "User");';
I don't know PHP. I will try helping you with MySQL though.
I think there is a problem with quotation marks in the insert query.
Try removing single quotes from your values clause.
As an advice, always use " from the start to the end of the sql query text;
$insert = 'INSERT INTO User(FirstName, LastName, Email, Username, Password, Type) VALUES ("'.$firstname.'", "'.$lastname.'", "'.$email.'", "'.$username.'", "'.$password.'", 'User');';
put it like:
$insert = "INSERT INTO User(`FirstName`, `LastName`, `Email`, `Username`, `Password`, `Type`) VALUES ('$firstname', '$lastname', '$email', '$username', '$password', 'User');";
In your query, you had 'User' and you need to escape the ' as \'
And dont forget to always sanitize your content before adding it to the database
My DB has columns: ID, first_name, email, password, level
I have a form that i am trying to update the 'level' column based on the 'email address' entered of the existing user.
Right now i have a basic form that just inserts the info, but i need it to update existing users based on the email value.
This is what i have
<form action="update.php" method="post">
<input type="hidden" name="action" value="update" />
<fieldset>
<label for="email" />Email Address:</label>
<input value="" type="text" name="email" id="email" />
<label for="level" />Level:</label>
<input value="vip" type="text" name="level" id="level" />
<input class="button" type="image" src="/img/right/get-started-button.png" />
</fieldset>
</form>
----update.php------
<?php
$email = $_POST['email'];
$level = $_POST['level'];
mysql_connect ("localhost", "username", "pass") or die ('Error: ' . mysql_error());
mysql_select_db ("db_name");
$query="INSERT INTO users (email, level)VALUES ('".$email."','".$level."')";
mysql_query($query) or die ('Error updating database');
echo "Database Updated With: " .$email. " ".$level ;
?>
Not knowing what version of MySQL your using, you can use INSERT ON DUPLICATE KEY UPDATE syntax if your on 5+: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If your using an older version then a simple select id limit 1 should suffice to find if the record exists.
BTW: you should be using mysql_real_escape_string (or similar) before you execute your sql statement. Its also a good idea to always use back ticks ` around your field names just in case you hit a reserved word or invalid symbol in your field names.
I'm not sure If i uderstand your question correctly, but if you are looking for the sql update:
UPDATE users Set level='some_value' WHERE email="some_email_address"
So you could do:
$query="UPDATE users SET level='" .$level."' WHERE email='" .$email."'";
That is if I understood your question correctly.
As in you are trying to update an existing table, based on the email address typed into the form.