Mysql datetime entry with php - php

I cant enter now() to MySQL column which has datetime stamp option:
$sth = mysql_query("INSERT INTO data (id, user_id,data,datetime,desc) ".
"VALUES ('', '$userid','$data',now(),'$desc')",$link)
or die("Query failed ");
MySQL:
4 datetime timestamp No CURRENT_TIMESTAMP
Output:
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) VALUES ('', '','',NOW(),'')'
at line 1

Remove quotes for now() as it is a MYSQL function. Also it is not now(), it is NOW().
$sth = mysql_query("INSERT INTO data (id, user_id,data,datetime,desc) VALUES ('', '$userid','$data',NOW()),'$desc'",$link) or die("Query failed ");

I guess the problem is because desc and datetime are a reserved words, and if id is AUTOINCREMENT you can remove from values. Try this:
$sth = mysql_query("INSERT INTO data (user_id, `data`,`datetime`,`desc`) ".
"VALUES ('$userid','$data',NOW(),'$desc')",$link)
or die(mysql_error());
And remember that mysql extension is deprecated, check mysqli or PDO.
Edited: Added some error detection

Related

same sql query works using phpmyadmin but does not work using php

I entered the following sql query in phpmyadmin, it successfully inserted a new record.
INSERT INTO `table` (id, timestamp) VALUES (1, '2013-09-18 13:00')
However, when I try to use it using php.
//...connection
$query = "INSERT INTO `table` (id, timestamp) VALUES (1, '2013-09-18 13:00')";
$result = mysql_query($query, $cms2013) or die("error:".mysql_error());
It throws error like this:
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 '13:00)' at line...
Can someone provide me some hints? Thank you.
your query is working fine i have checked it from my end.
Please execute the following.
$sql = "INSERT INTO tables (id, timestamp) VALUES (1, '2013-09-18 13:00')";
mysql_query($sql) or die("! sql");
Have you selected the database before mysql_query()?
Try query using:
$query = "INSERT INTO `db_name`.`table` (id, timestamp) VALUES (1, '2013-09-18 13:00')";
$result = mysql_query($query, $cms2013) or die("error:".mysql_error());

Wrong SQL Syntax? [duplicate]

This question already has answers here:
MySQL, safely using reserved word in query [duplicate]
(2 answers)
Closed 9 years ago.
I am building a small Twitter clone for personal use, and I have so trouble with it.
Fist, I want to show you my SQL structure of the table "poke_history":
http://puu.sh/3Sci0.png
This is the command I use to insert the values into a table (in PHP):
$insert = "INSERT INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
This is the annoying error that 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 'from, time, reason) VALUES ( '1'' at line 3.
Let me clarify some things.
$to_id is a number.
$from_id is a number.
$time is a number (coming from PHP's time()).
$reason is a text string.
I am using MySQL and PHP5.
Try to quote your column identifiers like
INSERT INTO poke_history (`id`, `from`, `time`, `reason`) ...
Everything inside `` is considered to be a "identifier" not a language keyword. From the SQL-syntax it should be clear that after INSERT INTO tablename cannot come a FROM, but the MySQL sometimes needs this kind of guidance (and other sql parsers, too).
credit to mario as well:
from is a reserved keyword. Use backticks to escape them.
for example
`from`
INSERT INTO table (`from`) ....
So your code would like this:
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES (".$to_id.", ".$from_id.", ".$time.", '".$reason."')";
mysql_query($insert) or die(mysql_error());
Numbers don't need to be quoted. Only strings.
Also don't use mysql, it's deprecated. Better use PDO, with prepared statements, to avoid issues like this.
You should try to use prepared statements to prevent SQL injection.
$query = "
INSERT INTO
poke_history (`id`, `from`, `time`, `reason`)
VALUES
(:id, :from, :time, :reason)";
$db = new PDO("mssql:host=sqlserver;dbname=database", "username", "password");
$statement = $db->prepare($query);
$parameters = array(
":id" => $name,
":from" => $from,
":time" => $time,
":reason" => $reason
);
$statement->execute($parameters);
I think that you forgot to add * in between INSERT and INTO, here is the fixed script:
$insert = "INSERT * INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
The reason why you are getting the error is because you are trying to use a built in function name for one of your columns. Say you have the following CREATE TABLE...
CREATE TABLE customers
(
name varchar(80),
streetAddr varchar(160),
"from" varchar(60),
);
Notice that to create the table I had to put the column from in quotes. Now if you wanted to insert a row into this table, your insert statement should look like the following:
INSERT INTO ShoppingFun.dbo.customers
(
name,
streetAddr,
"from"
)
VALUES
(
'MRBubbleGum',
'1061 SW BubbleGumVillage St',
'yourmom'
)

PHP mySQL INSERT syntax error?

I'm a newbie and I've been trying for over an hour to solve this simple query:
mysql_query("INSERT INTO `tracks` (artistID, albumID, format, trackID, niceTitle, title, trackNumber, description, pictureURL, playCount) VALUES('$artistID', '$albumID[$i]', 'hq','$ID[0]', '$trackName', '$title', '$j', '$description', '$pictureURL', '$playCount'") or die(mysql_error());
I just get this error every time:
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
I've done mysql_escape_string() on all variables too. Any ideas?
You are missing the final closing ):
mysql_query("INSERT INTO `tracks` (artistID, albumID, format, trackID, niceTitle, title, trackNumber, description, pictureURL, playCount) VALUES('$artistID', '$albumID[$i]', 'hq','$ID[0]', '$trackName', '$title', '$j', '$description', '$pictureURL', '$playCount')") or die(mysql_error());
You have no ending parenthesis ")" in your query

what causes the error with this mysql query?

mysql_query ("
INSERT INTO items
(index, name, description, given_by,
cost_to_tcs, starting_bid, auction_type)
VALUES
('{$index_number}','{$name}','{$description}','{$donated_by}',
NULL,'{$auction_type}','{$starting_bid}')
")
or die("3: " . mysql_error());
Errors with:
3: 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 ''index', 'name', 'description', 'given_by', 'cost_to_tcs', 'starting_bid', 'auct' at line 1
Thanks for any help.
index is mysql Reserved keyword, wrap index with (back tick) `` `
INSERT INTO items
(`index`, `name`, `description`, `given_by`,
`cost_to_tcs`, `starting_bid`, `auction_type`)
Reserve key words
try like that:
mysql_query ("
INSERT INTO items (
`index`,
`name`,
`description`,
`given_by`,
`cost_to_tcs`,
`starting_bid`,
`auction_type`)
VALUES(
'$index_number',
'$name',
'$description',
'$donated_by',
NULL,
'$auction_type',
'$starting_bid')
")
or die("3: " . mysql_error());
also make sure to safe the data with mysql_real_escape_string();

PHP Insert not Working Properly

I have the following lines of PHP code in my file along with some other code:
$command = "INSERT INTO inventory_items (Index, Name, Price) VALUES (NULL, 'Diamond', '3.99')";
$insertion = mysql_query($command) or die(mysql_error());
if ($insertion == FALSE)
{
echo "Error: Insert failed.";
}
else
{
echo "Insert successful.";
}
It keeps returning this 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 'Index, Name, Price) VALUES (NULL, 'Diamond', '3.99')' at line 1
myAdmin says I am using MySQL client version 5.0.91. What am I doing wrong? I just can't figure it out! I tried searching a lot...
Index is a reserved word in MySQL and as such, you need to either change the name of the column, or escape it with backticks. Try this $command:
$command = "INSERT INTO inventory_items (`Index`, Name, Price) VALUES (NULL, 'Diamond', '3.99')";
Read more about reserved words here: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
Try this:
$command = "INSERT INTO inventory_items (`Index`, Name, Price) VALUES (NULL, 'Diamond', '3.99');";
MySQL reserved words and how to treat them.
Can you verify that the columns in your inventory_items table are:
Index
Name
Price
And that you have the Index field set to AUTO_INCREMENT.
The best thing is probably to remove that field from your insert statement.
Try
$command = "INSERT INTO inventory_items (Name, Price) VALUES ('Diamond', '3.99')";
Since you're not inserting an Index anyway.
Hope that helps!

Categories