Issue with PHP insert to SQL - php

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

Related

SQL Syntax Error when executing mysqli_query

I have an PHP registration script with MySQLi and OOP.
But i get an mysql syntax error when executing an query.
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 '-mail, ip_register, ip_lastlogin, lastlogin) VALUES ('', Aarivex, ******, ****' at line 1
PHP Code:
$register_sql = "INSERT INTO users (id, username, password, pin, e-mail, ip_register, ip_lastlogin, lastlogin) VALUES ('', $username, $password, $pin, $email, $ip, $ip, $lastlogin)";
Wheres the problem?
...for the right syntax to use near '-mail
SQL's telling you where error starts ^ the offending character
You need to wrap/encapsulate the e-mail column in backticks since it contains a hyphen.
SQL figures you want to do math which translates to: e minus mail
Plus, missing quotes in your values
$register_sql = "INSERT INTO users (id, username, password, pin, `e-mail`, ip_register, ip_lastlogin, lastlogin) VALUES ('', '$username', '$password', '$pin', '$email', '$ip', '$ip', '$lastlogin')";
Those are strings and must be inside quotes.
Another option would be to rename your column to e_mail using an underscore as you did for some of the other columns. That way, you would not need to use backticks.
Look into using one of the following also:
Prepared statements
PDO with prepared statements.
Having used or die(mysqli_error($con)) to mysqli_query() would have signaled the error(s).
$con being your DB connection, this could/stand to be different than yours.
Adjust accordingly.
Identifiers (table/columns)
More on this topic: http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
Tip:
Try and avoid using hyphens, or spaces or any other character that SQL may complain about, this includes using a space in between words.
I.e.:
INSERT INTO your_table (column 1, column-2) <= will cause/throw an error
you would need to use backticks:
INSERT INTO your_table (`column 1`, `column-2`) <= correct / valid
Although spaces are allowed (yet discouraged), they too need to be encapsulated in backticks.
If you're going to have a dash in a column identifier (which is a bad idea) you must wrap it in ticks. Otherwise you are subtracting the value of the mail column from the e column which not not valid in an INSERT statement.
You're also missing quotes around your string values.
$register_sql = "INSERT INTO users (id, username, password, pin, `e-mail`, ip_register, ip_lastlogin, lastlogin) VALUES ('', '$username', '$password', '$pin', '$email', '$ip', '$ip', '$lastlogin')";
Try changing e-mail fieldname to email OR you need to encompass your that field name with back quotes like this:
`e-mail`
I suppose your id is set to Auto Increment.
If it is just remove the first column from the insert statement and it should work fine.
$register_sql = "INSERT INTO users (username, password, pin, e-mail, ip_register, ip_lastlogin, lastlogin) VALUES ($username, $password, $pin, $email, $ip, $ip, $lastlogin)";
And yes, change the e-mail field to `e-mail`.

Insert record into MYSQL database with PHP

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

Error with MySql query [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am having problems with this MySql query:
INSERT INTO groups (NAME, DESC, TIME, OWNER) VALUES ('$GNAME', '$DESC', '$TIME', '$UID')
Essentially, the script adds the Group Name, Decription, Time and the Username of the person who registered the Group, into the mysql database.
Full script:
<?php
include_once('include/session.php');
$GNAME = $_POST['groupname'];
$DESC = $_POST['desc'];
$SPAM = $_POST['spam'];
$UID = $_POST['UID'];
$TIME = date('Y-m-d H:i:s');
if($SPAM == "queuee"){
$query ="INSERT INTO groups (NAME, DESC, TIME, OWNER) VALUES ('$GNAME','$DESC','$TIME', '$UID')";
$result = mysql_query($query) or die("There as been an Error! <hr>Error:<hr>".mysql_error() ."<br><hr>Go Back");
header("Location: ../group.php?id=$GNAME");
}else{
?>
The Security Question was wrong. Try Again.
<?
}
?>
I ran the Query directly into MySql itself using Phpmyadmin. However it still threw an error.
The error is:
#1064 - 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 'DESC, TIME, OWNER) VALUES ('$GNAME', '$DESC', '$TIME', '$UID')' at line 1
Any help at all is much appreciated and perhaps I am being a complete fool and not noticing an obvious mistake. If you need any more information just ask!
Many Thanks.
"DESC" is a keyword. Put it in backquotes.
..., `DESC`, ...
DESC is a reserved keyword. If you must use it for a column name, wrap it in backticks:
`DESC`
Try:
INSERT INTO groups (`NAME`, `DESC`, `TIME`, `OWNER`) VALUES ('$GNAME','$DESC','$TIME', '$UID')";
You're using reserved words as column names - PHP gets terribly confused in that case.
I should also add that your code is open to SQL injection, and you should look at moving away from using the mysql_* functions.
The quickstart guide for mysqli is at http://www.php.net/manual/en/mysqli.quickstart.php
PDO is another option; the information on prepared statements is at http://www.php.net/manual/en/pdo.prepared-statements.php
DESC is SQL keyword, use `` to escape column names:
$query ="INSERT INTO `groups` (`NAME`, `DESC`, `TIME`, `OWNER`) VALUES ('$GNAME','$DESC','$TIME', '$UID')";
According to MySQL Reserved Words, the word `DESC can't be used as a field name, unless you enclose it with backticks.
Put single (or double maybe) quotes around DESC in the "INSERT INTO groups" part. DESC is a reserved word and must be quoted.
use
$DESCRIPTION = $_POST['desc'];
inseted of
$DESC = $_POST['desc'];
$DESCRIPTION variable use in you query
$query ="INSERT INTO groups (NAME, DESC, TIME, OWNER) VALUES ('$GNAME','$DESCRIPTION','$TIME', '$UID')";

why is my MySQL query failing

I can't get this to work, keep getting an error message.
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 '-mail, password,
birth_date, age, sex, profile_text, zip_code, zip_code_state, c' at line 1
Code
mysql_query("INSERT INTO users (username, e-mail, password, birth_date, age, sex,
profile_text, zip_code, zip_code_state, coins, rank, profile_visits,
profile_likes, profile_image, profile_points, activated, deleted, reg_time,
last_active_time, reg_ip)
VALUES ('$randomName', 'awduhawd#hotmail.com', 'awd', '21/05/1990','0','2',
'0','4306','Sandnes','0','user','0','0','$image','0','0','0','$time',
'$time','0')")
or die(mysql_error());
Surround e-mail with backticks...
`e-mail`,
You can't drop a - there otherwise.
the - sign is a reserved symbol in SQL, need to wrap e-mail in backticks i.e. `e-mail``
Rule of thumb: column names in backticks and concatenate the string variables for readability, the MySQL date format is Y-m-d (1990-05-21)
mysql_query("INSERT INTO users (`username`, `e-mail`, `password`, `birth_date`, `age`,`sex`,
`profile_text`, `zip_code`, `zip_code_state`, `coins`, `rank`, `profile_visits`,
`profile_likes`, `profile_image`, `profile_points`, `activated`, `deleted`, `reg_time`,
`last_active_time`, `reg_ip`)
VALUES ('".$randomName."', 'awduhawd#hotmail.com', 'awd', '1990-05-21','0','2',
'0','4306','Sandnes','0','user','0','0','".$image."','0','0','0','".$time."',
'".$time."','0')")
or die(mysql_error());
If you are using php for this dont use single quotes arround variables, they wont be parsed.
'$randomName' = wrong
either use "$randomName"
or use "'.$randomName.'"

Can't figure out what's wrong with my php/sql statement

So this is probably a dumb beginner question, but I've been looking at it and can't figure it out. A bit of background: just practicing making a web app, a form on page 1 takes in some values from the user, posts them to the next page which contains the code to connect to the DB and populate the relevant tables.
I establish the DB connection successfully, here's the code that contains the query:
$conn->query("SET NAMES 'utf9'");
$query_str = "INSERT INTO 'qa'.'users' ('id', 'user_name','password' ,'email' ,'dob' ,'sx') VALUES (NULL, $username, $password, $email, $dob, $sx);";
$result = #$conn->query($query_str);
Here's the error that is returned:Insert query failed: 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 ''qa'.'users' ('id', 'user_name' ,'password' ,'email' ,'dob' ,'s' at line 1
Thanks in advance!
Unless it's changed since I did MySQL in PHP, escape your db/column/table names with backticks (`), not apostrophes (').
A good general trouble-shooting technique is to make the query work via another interface to the database. For example, phpMyAdmin. If it works there, you have some confidence going forward. or you may find how to fix your SQL. (phpMyAdmin is handy because it will convert your SQL into a ready-made string for PHP.)
You need to escape your column names with a backtick (`) instead of (')
You also need to properly escape the actual values you are inserting as well (use a single quote)
OMG not a single right answer
$query_str = "
INSERT INTO `qa`.`users` (`id`, `user_name`,`password` ,`email` ,`dob` ,`sx`)
VALUES (NULL, '$username', '$password', '$email', '$dob', '$sx')";
identifiers being quoted with backticks, while strings being quoted with apostrophes!
and I hope you have passed all your variables through mysql_real_escape string BEFORE putting it into query, i.e.:
$username = mysql_real_escape string($username);
and so on

Categories