Hopefully a simple fix but has been stumping me all weekend.
I have a simple script to connect to my MYSQL databse, then using fields from an HTML form enter a new record into the database.
The script is working just fine, but I have not defined the database columns in the script, simply used insert into and then referenced the VALUES as the HTLM form fields.
WORKING
mysql_select_db("golfingdb", $con);
mysql_query("INSERT INTO Test1
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]')");
mysql_close($con);
NOT WORKING
mysql_select_db("golfingdb", $con);
mysql_query("INSERT INTO 'Test1' (First Name, Surname, Email)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[email]')");
mysql_close($con);
However when I reference the database field names in the code then it fails to make a new record.
I have triple checked the spelling (including capitals) of the field names and it doesn't throw up any syntax errors.
Any help would be greatly appreciated.
Cheers
Paddy
You need to surround column names with backticks if the name contains a space.
(`First Name`,
Maybe it is the two word column name. You can use `First Name` or something like that when referencing the column.
Could you post the exact error MySQL gives you?
Try this
$firstname=$_POST["firstname"];
$lastname=$_POST["lastname"];
$email=$_POST["email"];
mysql_query("INSERT INTO Test1('First Name', 'Surname', 'Email')
VALUES ('$firstname','$lastname','$email')");
Make sure you have created the table structure with the right data types and lengths.
Backstick characters `` should be used to escape table and column names. Single quotes characters '' should be used to escape string values.
In your second example, the table name is escaped with single quotes instead of backsticks. In addition, the field names are not escaped at all, which probably causes a problem with the first field name that contains a space.
The correct form would be:
mysql_query("INSERT INTO `Test1` (`First Name`, `Surname`, `Email`)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[email]')");
It's also important to note that PHP's mysql_ functions have been deprecated. It's highly recommended to use one of the alternatives as discussed in Why shouldn't I use mysql_* functions in PHP?
I have tried and it doesn't grow my database. Here's the code:
<?php
// Connecting to Ganoderma genome database
include('../utils/config.php');
// Inserting new data into the table
$sql = "INSERT INTO $var2 ('$column_id', '$column_name', '$column_seq') VALUES ('$_POST[id]', '$_POST[name]', '$_POST[seq]')";
// Qualifying successful entry
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Bioinformatician,
Aizek
Related
I'm new in php and postgres sql.
I have this issue : "pg_query(): Query failed: ERROR: missing FROM-clause entry for table "manteau ^
$adresse=pg_escape_string($_POST['mail_user']);
if(isset($_POST['mail_user']))
{
$query="INSERT INTO newusers2 (email) VALUES ($adresse)";
pg_query($con,$query);
}
with mail_user = my address email manteau.b...
My table (newusers2) is really simple with only one column (email).
Can someone help me with the query?
Thanks
Put the value $adresse inside quotes:
$query="INSERT INTO newusers2 (email) VALUES ('$adresse')";
In addition to being incorrect due to lack of quoting your code is also terribly insecure.
$query="INSERT INTO newusers2 (email) VALUES ($adresse)";
pg_query($con,$query);
Imagine if someone submitted ');DELETE FROM newusers2;-- as their address? Whoops, there goes your user table.
See the PHP documentation on SQL injection and this site for details.
Use pg_query_params to solve this issue. It's very simple:
$query='INSERT INTO newusers2 (email) VALUES ($1)';
pg_query($con,$query,array($adresse));
(Note that new code in PHP really should use PDO, though).
I have a necessity to insert some record from one table1 in database1 to another table2 in database2.
So far I have this..
$records_r = mysqli_fetch_assoc(mysqli_query($conn_r, "SELECT * FROM `export` WHERE ID < 100"));
$columns_r = implode(",",array_keys($records_r));
$values_r = implode(",",array_values($records_r));
$import = mysqli_query($conn_i,"INSERT INTO NOTimport ($columns_r) values ($values_r)");
if (!$import) {
printf("Error: %s\n", mysqli_error($conn_i));
exit();}
It gives me the error:
Error: You have an error in your SQL syntax;
This is how the syntax looks:
INSERT INTO `NOTimport` ('xx,xx,xx,xx,xx,xx,xx,xx') values ('11,'11,E,2079,1931,xx,xx,x')
I am 99% sure that single quotes are causing the error, but why are there?
As per your original post https://stackoverflow.com/revisions/31116693/1 and completely overwriting your original post without marking it as an edit:
You're using the MySQL import reserved word
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
It needs to be wrapped in ticks
INSERT INTO `import` ($columns_r) values ($values_r)
or rename that table to something other than a reserved word.
Plus, $values_r may require to be quoted and depending on what's being passed through $columns_r, you may need to use ticks around that.
I.e.:
INSERT INTO `import` (`$columns_r`) values ('".$values_r."')
Even then, that is open to SQL injection.
So, as per your edit with these values values ('11,'11,E,2079,1931,xx,xx,x'), just quote the values since you have some strings in there. MySQL will differentiate between those values.
Escape your values:
$values_r = implode(",",array_values($records_r));
$values_r = mysqli_real_escape_string($conn_r, $values_r);
or $conn_i I'm getting confused as to which variable is which here. Be consistent if you're using the same db.
Edit:
As stated in comments by chris85, use prepared statements and be done with it.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
import is a reserved word in MYSQL. So, you need to use backticks (``) around it in your query.
So rewrite as follows:
$import = mysqli_query($conn_i,"INSERT INTO `import` ($columns_r) values ($values_r)");
Without Using PHP you can use MySql Query Which Will Perform Insert Operation As:-
$columns_r='`name`,`class`';
mysqli_query($conn_i,"INSERT INTO `import` ({$columns_r}) select {$columns_r} from `export`");
Getting really confused surrounding this INSERT INTO. It should insert three fields into the table, userID, activateKey and isActivated.
The activateKey is a 25 letter randomly generated key such as 63n20kw24ba1mlox34e8n2awv
The userID comes from another table and is set by auto_increment.
The isActivated is always 0 at this stage.
It seems like quite a simple INSERT statement
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
{
echo("Error description: " . mysqli_error($con));
}
However it doesn't work when I include the $activateKey field. What it does is try to search the string variable $activateKey as a column name. The error I get is:
Error description: Unknown column '63n20kw24ba1mlox34e8n2awv' in 'field list'
Of course there is no such column as 63n20kw24ba1mlox34e8n2awv, this is the data I'm trying to insert, hence why it's in the VALUES section. Any ideas why it's trying to search this as the column name?
Edit to clarify: the var is activateKey, the column name is activationKey
I would put the query in a different variable to avoid confusion, and PHP automatically substitutes variable names in strings in double quotes.
Try this:
<?php
$query = "INSERT INTO activations (userID,activationKey,isActivated) VALUES($userID,'$activateKey','0')
if (!mysqli_query($con,$query)
{
echo("Error description: " . mysqli_error($con));
}
You are not surrounding the values with quotes, that's why they get interpreted as variable names.
Use single quotes, like this:
"INSERT INTO activations (userID,activationKey,isActivated) VALUES
('".$userID."','".$activateKey."','0')"
However, be aware that stringing together query strings exposes you to SQL injection attacks, if that's a concern in your code you should use parameterized queries. In fact, using parameterized queries is always better.
Change your query to this:
"INSERT INTO activations
(userID,activationKey,isActivated)
VALUES ('$userID','$activateKey','0')"
You dont need to use the concatenation (.) operator as variables will be interpolated into the string.
The single quotes tell mysql to treat the variables as literals instead of column names.
As a side note you would be better to use parameterized queries. See How can I prevent SQL injection in PHP?
Solved!
It was a case of not properly wrapping the dynamic fields (the vars in the VALUES section) in ticks:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES ('".$userID."','".$activateKey."','0')"))
Instead of
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
Might be a difficult one to spot. The variables still need to be 'in ticks' or they won't register as strings.
As activationKey is a string column, you must use single quotes for $activationKey.
Try with:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated)
VALUES (".$userID.",'".$activateKey."','0')"))
Im pretty new to PHP and SQL and I have been following some tutorials. I am trying to insert some simple items into an existing table (and yes the names are exact on the table, login info etc...)
Here is the error I am getting:
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 ''user' ('username', 'email') VALUES ('Testname', '123')' at line 1
Here is my string:
mysql_query("INSERT INTO 'user' ('username', 'email') VALUES ('Testname', '123')") or die(mysql_error());
any ideas?
there is a difference between ' and ` sign, when you need to call columns you need to cover them with
` sign not with single quote sign '
mysql_query("INSERT INTO `user` (`username`, `email`) VALUES ('Testname', '123')") or die(mysql_error());
Replace your code:
mysql_query("INSERT INTO `user` (username, email) VALUES ('Testname', '123')") or die(mysql_error());
Replace your code to
mysql_query("INSERT INTO user VALUES ('Testname', '123')") or die(mysql_error());
Try this..
Use table name correctly (user).
mysql_query("INSERT INTO user('username', 'email') VALUES('Testname', '123')") or die(mysql_error());
There is a difference in mysql queries between the quote (') and the back-quote (`). The back quote is used to quote names of tables, databases and columns. The normal quote is used to undicate that the given value is a string and not a reference.
so your query should look like
mysql_query("INSERT INTO `user` (`username`, `email`) VALUES ('Testname', '123)")
because "user" is a preserved word as "username" so I put those around back-quotes so mysql knows it's an reference and not a function or property.
in PHP MYSQL Single quote is not use for field name and table name unlike Oracle
You can use
INSERT INTO user (username, email) VALUES ('Testname', '123')
OR
INSERT INTO `user` (`username`, `email`) VALUES ('Testname', '123')
instead of ' single quote Tiled can be used.....
if you dont want to use then its okey just use Tiled for reserve words in query like status or order etc
and as per #Andy said use mysqli driver for connection because mysql_query will bedeprecated in next version
I'm having problems with a really bizarre problem when trying to insert a record into mysql via PHP and I was wondering if anyone could shed any light on it, because I'm out of ideas now.
Database table:
Field Type Null Default Comments
UserID bigint(20) No Autoincrement
UserGUID text No
ServerID int(11) No
UserName text No
Passwrd text No
Prompt text No
Answer text No
EMail text No
Verified int(11) No 0
Language text No
Gender int(1) Yes NULL
DateOfBirth int(11) Yes NULL
Country int(11) Yes NULL
PostCode text Yes NULL
State text Yes NULL
Town text Yes NULL
Snippit of relevant PHP code...
public function signupUser($uid, $pwd, $prompt, $answer, $email, $lang, ... &$result)
{
$guid = $this->getGUID();
$serverID = 1;
$result = mysql_query("INSERT INTO User(UserGUID, ServerID, UserName, Passwrd, EMail) " +
"VALUES ('$guid', $serverID, '$uid', '$pwd', '$email')");
Before anyone tells me I should be using mysqli, parameterising my queries and the like, please be aware that this PHP/MySQL is a local test harness only, on a private network and only for development purposes until the real web service (dotNet/Oracle) comes available.
So if I call the function above with suitable parameters, $result comes back with...
"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 '0' at line 1"
but if I reduce the query to just...
$result = mysql_query("INSERT INTO User(UserGUID, ServerID, UserName, Passwrd) " +
"VALUES ('$guid', $serverID, '$uid', '$pwd')");
it works! Happily inserts the record (despite there being nulls in not null fields!?!) Just to add further complications, if I run the (original) query with suitable values e.g.
INSERT INTO User(UserGUID, ServerID, UserName, Passwrd, EMail) VALUES ('guid', serverID, 'uid', 'pwd', 'email')
directly against the database via phpMyAdmin, it also works!!
This is driving me nuts. I've tried changing field names, nullability, order, which fields I use in the query (after the first four which work), values - none of it makes a difference. It almost seems as if it doesn't want more than four fields.
Please... anyone...? I really am at a loss to understand why it won't accept the fifth field, it makes no sense that I can see. Unfortunately the error returned is of no help at all, too vague and seems to be the equivalent of the oh-so-useful "errors occurred" from MS.
If I have to change over to mysqli I will but I'd prefer not to have to re-craft the test harness if I can avoid it.
edited after a revelation: take a look in the comments that concatenation operator in php is absolutely a . not a + i would put money that is your problem right there... didnt even see it on my first look.
in the past ive run into odd troubles somewhat similar to this - and was able to solve it by encapsulating my table and column names in backticks columnX, columnY - i would also try adding a space between the table name 'User' and the parenthesis containing your column names in the SQL syntax
mysql_query("INSERT INTO User(UserGUID, ServerID, UserName, Passwrd, EMail) " +
"VALUES ('$guid', $serverID, '$uid', '$pwd', '$email')");
take a look at this question? very similar to yours with successful results
hope i could be of some assistance
If your example is literal, I doubt either works. The string concatenation operator is "." not "+" in php. Additionally, php will not interpret variables inside single quotes. Try re-writing the query like this:
$result = mysql_query("INSERT INTO User SET UserGUID = '" . $guid . "', ServerID = " . $serverID . ", UserName = '" . $uid . "', Passwrd = '" . $pwd . "'";
I always create SQL inside a string, and, if there is a problem, I insert an echo $sql or error_log($sql) statement.
Sometimes there's something very subtle. When you copy and paste the query from debug output into phpMyAdmin, you will see a more meaningful error message.
One thing is possible that the variable $email contains something that breaks out of the string. Make sure you use mysql_real_escape_string on your PBP variables before including them inside an SQL query..