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
Related
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!
This sql query is not working:
$sql = "INSERT INTO top(topic_subject,topic_date, topic_cat, topic_by)
VALUES(" . mysql_real_escape_string($_POST['topic_subject']) . " , NOW()," . mysql_real_escape_string($_POST['topic_cat']) . " , " . isset ($_SESSION['user_id']) . ")";
how can I fix it?. I am getting this error message.
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 2`
It's likely that topic_subject is character data. To include literal strings in SQL text, it should be enclosed in single quotes.
... VALUES ('abc', ...
If you used prepared statements, this wouldn't be an issue, and for the love of all things that are beautiful and good in this world, don't use the deprecated PHP mysql_ interface for new development. It's been superseded by the mysqli_ and PDO interfaces.
You forgot the quotes.
$sql = "INSERT INTO top(topic_subject,topic_date, topic_cat, topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "' , NOW(),'" . mysql_real_escape_string($_POST['topic_cat']) . "' , '" . isset ($_SESSION['user_id']) . "')";
And be aware that mysql_* is deprecated. Use PDO or mysqli instead.
There are couple problems here.
Quote your strings
Make sure your data is of the correct type
$topic_subject = mysql_real_escape_string($_POST['topic_subject']);
$topic_date = NOW();
$topic_cat = mysql_real_escape_string($_POST['topic_cat']);
$topic_by = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : ""; // always returns a string value.
$sql = "INSERT INTO top(topic_subject,topic_date, topic_cat, topic_by)
VALUES('{$topic_subject}' , {$right_now}, '{$topic_cat}' , '{$topic_by}')";
It may help you to use more variables in your code (shown) so that you can use a debugger to verify that the strings and variables you create have the values you intend them to have.
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 trying to inserts some values to the database in my php program but I am getting the error
Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in C:\wamp\www\php\books.php on line 9
mysql_query..
mysql_query("insert into books values('$_GET["title"]','$_GET["author"]','$_GET["edition"]','$_GET["publish"]','$_GET["isbn"]',)") or die(mysql_error());
get your values in variables like
$title = $_GET["title"];
$author = $_GET["author"];
then use query like this
mysql_query("insert into books values('$title','$author','$edition','$publish','$isbn',)") or die(mysql_error());
you are using nested double quotes
mysql_query("insert into books values('{$_GET["title"]}','{$_GET["author"]}','{$_GET["edition"]}','{$_GET["publish"]}','{$_GET["isbn"]}',)") or die(mysql_error());
or
mysql_query("insert into books values('$_GET[title]','$_GET[author]','$_GET[edition]','$_GET[publish]','$_GET[isbn]',)") or die(mysql_error());
The good query is :
mysql_query("insert into books values('" . $_GET["title"] . "','" . $_GET["author"] . "','" . $_GET["edition"] . "','" . $_GET["publish"] . "','" . $_GET["isbn"] . "')") or die(mysql_error());
There are non escaped quotes but also a comma which has nothing to do here, at the end of the query.
Maybe you should learn PHP and its syntax first.
Can anyone show me a query in MySQL that would delete rows from all available columns.
I use this to insert rows:
$sql = "INSERT INTO " . KEYS . " // KEYS is a constant
(key, user_id, time, approved)
VALUES ('" . $randkey . "', '" . $user_id . "', '" . $time . "', '0')";
I need the opposite of this now, delete created rows.
delete from <table> where ....
Keep in mind that the delete statement is always for an entire row.
Using similar syntax sql = "DELETE FROM " . KEYS . " WHERE 1=1";
Replace 1=1 with the conditions for the row you want to delete or it will delete all rows.
Also, it's good to get out of the habit of just dropping variables into SQL as soon as possible, because it will open your code up to SQL Injection attacks. Look into using parameterized queries.