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 6 years ago.
I am trying save to database row. But I get always error.
My code is:
function save_activation_key($connection, $username, $key) {
$date = time();
$is_used = 0;
$query = "INSERT INTO account_activation_key ( key, date, is_used)
VALUES ( '" . $username . "',"
. " '" . $date . "',"
. " '" . $is_used . "')";
$retval = mysql_query($query, $connection);
echo $retval;
$retval = mysql_query( $query, $connection );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
In $connection is valid connection to database.
Database structure:
id : int
key: varcha(45)
date: date
is_used: tinyint(1)
When I call my code I get error:
Could not enter data: 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 'key, date, is_used) VALUES ( 'uzivatelsky_jmeno', '1459971829', '0')' at line 1
Where is a problem?
Thanks for help
key is a MYSQL reserved word and should not really be used as column names.
MYSQL Reserved Words List can be found here https://dev.mysql.com/doc/refman/5.7/en/keywords.html
However if you wrap these column names in backticks you can get away with it.
You can also simplify your query string concatenation like the following, which makes it a lot easier to debug.
function save_activation_key($connection, $username, $key) {
$date = time();
$is_used = 0;
$query = "INSERT INTO `account_activation_key`
( `key`, `date`, `is_used`)
VALUES ( '$username', '$date', '$is_used')";
$retval = mysql_query($query, $connection);
echo $retval;
$retval = mysql_query( $query, $connection );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
BIG NOTE
Please dont use the mysql_ database extension, it
is deprecated (gone for ever in PHP7) Which means this code will never run when all that is available is PHP7 or greater.
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
probably your query contains an error at the place where you are giving integer as a string , like your string
'" . $username . "',"
. " '" . $date . "',"
. " '" . $is_used . "'
should be :
'" . $username . "',"." . $date . ","." . $is_used . "
the integers should'nt be with single qoutes " ' "
probably this is the mistake!
Related
I am running this query on my MySQL Database - with mysql_query it throws me an error but the data is still properly inserted into the table. If I enter it in PhpMyAdmin it works without error.
INSERT INTO `kommentare` VALUES(NULL,'1','MyName','MyEmail','MyText','2014-08-05');
PHP :
$name = mysql_escape_string($name);
$email = mysql_escape_string($email);
$kommentar = mysql_escape_string($kommentar);
$datum = mysql_escape_string($datum);
$reiseid = str_replace("/", "", $reiseid);
$query = "INSERT INTO kommentare VALUES(NULL,'" . $reiseid . "','" . $name . "','" . $email . "','" . $kommentar . "','" . $datum . "');";
$result = mysql_query($query) or die(mysql_error());
echo $query;
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 '' at line 1
How is that possible? I am experienced with MySQL but this wrecks my nerves - it works but says it doesn't?!
UPDATE:
It just happens when I have more than one entry in the table. ANd even if I remove all the ' it gives me the same error, saying I should check near the '
If the first column is a auto-increment primary key, you don't pass it NULL, you pass it DEFAULT:
INSERT INTO kommentare VALUES
(DEFAULT,'$reiseid','$name','$email','$kommentar','$datum');
But really you should instead be naming your columns and skipping those that you don't have a value for:
INSERT INTO kommentare
(reiseid, name, email, kommentar, datum)
VALUES
('$reiseid','$name','$email','$kommentar','$datum');
SOLUTION:
My id has been passed not as 1 but as 1/ for some reason. This caused MySQL to crash although it was not shown to me. I replace the / with "" now and everything works fine!
Here's the table structure
CREATE TABLE IF NOT EXISTS `result` (
`res_id` int(11) NOT NULL AUTO_INCREMENT,
`s_id` int(10) NOT NULL,
`i_id` int(6) NOT NULL,
`r_status` text NOT NULL,
`r_score` decimal(6,0) NOT NULL,
PRIMARY KEY (`res_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
I've searched for a solution and have tried on different occasions, building the table from scratch, drop and import it back, checked the index. As you can see, I've renamed the id to res_id but when I run it on the browser the error still shows r_id.
If it makes a difference, when the id is not set to auto increment, the same error pops up.
Here's the code snippet for the page where I want to insert into the database.
//retrieve existing r_id
$sql_res = "SELECT res_id FROM result ORDER BY res_id DESC LIMIT 1";
$query_res = mysql_query($sql_res) or die("MySQL Error: " . mysql_error());
$data_res = mysql_fetch_assoc($query_res);
$resid_count = $data_res['res_id']+1;
//echo "<br>Result: " . $resid_count;
// insert result to table
$sql_result = "INSERT INTO result (res_id, r_score, s_id, i_id) VALUES ('" . $resid_count . "', '" . $correct . "', '" . $id . "', '" . $ins_id . "')";
mysql_query($sql_result) or die ("Error: " . mysql_error());
EDIT: I changed the code like you guys suggested. Took the res_id out from the INSERT. It still says duplicate entry for r_id. I went ahead for trial and error and created another table 'score' with the same structure to replace 'result'. Was wondering if the same table name was giving it problem (could running the page many times cause this?). Same outcome with the score table.
Any help would be greatly appreciated. I'm stuck here and cannot proceed with my project. Thanks.
Atikah
Since res_idis AUTO_INCREMENTI suggest that you replace your insert query by this:
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ('". $correct . "', '" . $id . "', '" . $ins_id . "')";
try this
$sql_result = "INSERT INTO result ( r_score, s_id, i_id) VALUES ( '" . $correct . "', '" . $id . "', '" . $ins_id . "')";
res_id will be automatically inserted without your inserting
EDIT.
If you want just insert then you dont need those lines , just remove them, because you are using them for knowing the last res_id . since res_id as i said before its auto_increment. it will increment automatically
$sql_res = "SELECT res_id FROM result ORDER BY res_id DESC LIMIT 1";
$query_res = mysql_query($sql_res) or die("MySQL Error: " . mysql_error());
$data_res = mysql_fetch_assoc($query_res);
$resid_count = $data_res['res_id']+1;
Make sure you don't use apostrophes in your SQL where you use numerics (int). This could cause trouble. And res_id should not be involved at all, because that's the point with having autoincremental columns (You don't have search for the next id in the database with PHP-code, DB takes care of that)
Your code could be translated into two lines:
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES (" . $correct . ", " . $id . ", " . $ins_id . ")";
mysql_query($sql_result) or die ("Error: " . mysql_error());
OR (variables inside quotes gives the actual values)
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ($correct, $id, $ins_id)";
mysql_query($sql_result) or die ("Error: " . mysql_error());
and of course - don't use mysql_* - functions, cause they're deprecated. Use PDO or Mysqli instead with parameters so you could avoid SQL injection in a safe way. The code you've got is vulnerable to SQL injections.
I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Sometimes an input field in the HTML form will be left empty and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:
Home team: Blue team
Away team: [empty]
Result: Won
The following is inserted into my database:
Home team: Blue team
Away team: ' '
Result: Won
What I want to be inserted/not inserted is:
Home team: Blue team
Away team: NULL
Result: Won
I've hunted hours for a solution. Can anyone help? Thank you.
You can use the NULLIF function from mysql database. What it does is, it takes 2 parameters and return null if they are same. So basically you can change your code to be like following:
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
(NULLIF('" . mysql_real_escape_string($_POST['hometeam']) . "', ''),
NULLIF('" . mysql_real_escape_string($_POST['awayteam']) . "', ''),
NULLIF('" . mysql_real_escape_string($_POST['result']) . "', ''))";
It will basically check if the entered value is ''(empty string), and if that's the case, it would instead save NULL in the database. You can even trim leading or trailing spaces from your variables before passing onto NULLIF, so if someone only enters spaces in your input boxes, it still saved NULL.
Also, as Michael said, it would be safer and better if you move on to PDO or mysqli extension. Hope my answer helps.
In your code, replace:
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
With:
if($_POST['awayteam'] == '')
$awayteam = 'NULL';
else
$awaytem = "'" . mysql_real_escape_string($_POST['awayteam']) "'";
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
" . $awayteam . ",
'" . mysql_real_escape_string($_POST['result']) . "')";
Don't quote them inside your query. Instead, build variables first, and append quotes to the escaped string values outside the query, giving you the ability to insert NULL keywords if your strings are empty:
// If any is not set or empty in the POST, assign the string "NULL" unquoted to a variable
// which will be passed to MySQL as the unquoted NULL keyword.
// Otherwise escape the value from $_POST and surround the escaped value in single quotes
$ateam = !empty($_POST['awayteam']) ? "'" . mysql_real_escape_string($_POST['awayteam']) . "'" : "NULL";
$hteam = !empty($_POST['hometeam']) ? "'" . mysql_real_escape_string($_POST['hometeam']) . "'" : "NULL";
$result = !empty($_POST['result']) ? "'" . mysql_real_escape_string($_POST['result']) . "'" : "NULL";
// Then pass the three variables (already quoted if necessary) directly to the query.
$sql="INSERT INTO scores (hometeam, awayteam, result) VALUES ($hteam, $ateam, $result);
In the long run, it is recommended to begin using a MySQL API which supports prepared statements, like PDO or MySQLi. They offer better security, can handle input NULLs more elegantly, and the old mysql_*() functions are soon to be deprecated.
Or if you have access to db alter the columns( that are optional) and set them as NULL by default.
i.e. if nothing is inserted in that column NULL will be displayed by default.
Why not replace ' ' and other invalid forms of data with 'null'?
OR
Check if $_POST['data'] is equal to ' ' or '' and if true, set them to 'null'.
Also,
Instead of mysql_real_escape_string, use the PHP function 'addslashes'.
I am have created a web app that will use PHP to insert a row into an Oracle database. I am using Zend Framework to connect to the database. When I test it I dont get any errors but I dont see that added row in the table.
Here is my code:
$remote = $_SERVER['REMOTE_ADDR'];
// Connect with PDO
$db = Zend_Db::factory('PDO_OCI',
array(
'dbname' => $dbname,
'username' => $dbuser,
'password' => $dbpass
)
);
$req = "INSERT INTO " . $dbtable . " (id, url, adddate, addip) VALUES ('', '" . $safeurl . "', SYSDATE, '" . $remote . "')";
$res = $db->prepare($req);
$res->execute();
$safeurl is generated by user input, and it is sanitized.
id is autogenerated when you insert the row.
Please help me solve this. Thanks!
You have to commit. Each update/insert/delete begins a new transaction if it's not started. So issue another COMMIT statement after inserting a record (or a bunch of records). Oracle doesn't have autocommit mode.
after
$res = $db->prepare($req);
do echo $req->__toString(); to get the generated query then copy it and execute it in SQL Plus
if it works then your only issue is that you need to commit:
$db->beginTransaction();
$req = "INSERT INTO " . $dbtable . " (id, url, adddate, addip) VALUES ('', '" . $safeurl . "', SYSDATE, '" . $remote . "')";
$res = $db->prepare($req);
$res->execute();
$db->commit();
My sql query when I check manually in phpmyadmin works fine, but when I try to handle it through php mysql_query throw me a syntax error. How to solve this issue?
Error message:
Invalid 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 'INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ))' at line 1
Whole query:
INSERT INTO users (id_fb, name, first_name, last_name, email, link, first_login)
VALUES ('1000001010101010', 'Bart Roza', 'Bart', 'Roza', 'lalalala#gmail.com','http://www.facebook.com/profile.php?id=1000001010101010','2011-05-07 11:15:24');
INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ));
My php function:
public function createUser()
{
$time = date("Y-m-d H:i:s");
$insert = "INSERT INTO users (id_fb, name, first_name, last_name, email, link, first_login) VALUES (" .
"'" . $this->me['id'] . "', " .
"'" . $this->me['name'] . "', " .
"'" . $this->me['first_name'] . "', " .
"'" . $this->me['last_name'] . "', " .
"'" . $this->me['email'] . "'," .
"'" . $this->me['link'] . "'," .
"'" . $time . "'); " .
"INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ));";
$result = mysql_query($insert);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $insert;
die($message);
}
}
EDIT:
Thanks for the solution!
Since mysql_query accepts only one query you need to split your query string into 2 separated queries and perform it with 2 mysql_query calls.
You can not run multiple queries in once using mysql_query function. you have to run these two queries with separate mysql_query call
mysql_query() sends a unique query
(multiple queries are not supported)
AS #zerkms and #Shakti said, mysql_query does not support multiple queries. If you want to use such functionality, consider migrating to mysqli. It supports multiple queries in a single packet by mysqli_multi_query