PHP MySQL command syntax error - php

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.

Related

Trouble specifying my tablename inside query because of dot notation

I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.
I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.

MySQL throws error but works - PhpMyAdmin without error

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!

Error while inserting into db in php

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.

SQL syntax is ok but php still throw error

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

Odd Mysql issue on insert

Hy all,
Not sure what's going on here, but if I run this:
$query = 'INSERT INTO users
(`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES
("'. $user_id . '", "' . $first_name .'", "'. $second_name . '", "' . $date . '", "' . $date . ");';
$result = mysql_query($query);
I get no return, but if I change it to this it's fine:
$query = 'INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES ("21021212", "Joe", "Bloggs", "20090202", "20090202");';
$result = mysql_query($query);
User id = bigint(20)
first name = varchar(30)
second name = varchar(30)
date = int(8)
At first I thought it was a issue with the vars but they are exactly the same and still don't work.
Any help appreciated.
Get into the habit of escaping all database inputs with mysql_real_escape_string- really, you should use some kind of wrapper like PDO or ADODb to help you do this, but here's how you might do it without:
$query = sprintf("INSERT INTO users ".
"(id, first_name, second_name, register_date, lastlogin_date)".
"VALUES('%s','%s','%s','%s','%s')",
mysql_real_escape_string($user_id),
mysql_real_escape_string($first_name),
mysql_real_escape_string($second_name),
mysql_real_escape_string($date),
mysql_real_escape_string($date));
$result = mysql_query($query);
and also check for errors with mysql_error
if (!$result)
{
echo "Error in $query: ".mysql_error();
}
What's the result from "mysql_error()"? Always check this, especially if something doesn't seem to be working.
Also, echo out $query to see what it really looks like. That could be telling.
Maybe the value of $date was "1111'); DELETE FROM users;"?
Seriously though? The problem is that isn't how you interact with your database. You shouldn't be passing in your data with your query. You need to specify the query, the parameters for the query, and pass in the actual parameter values when you execute the query. Anything else is inefficient, insecure and prone to bugs like the one you have.
By using PDO or something that supports parametrized queries, you'll find these kinds of issues go away because you are calling the database property. It is also much more secure and can speed up the database.
$sth = $dbh->prepare("INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`) VALUES (?,?,?,?,?)")
$sth->execute(array($user_id ,$first_name , $second_name , $date, $date ));
In addition to echoing the query and checking mysql_error() as #GoatRider suggests:
Are you escaping your data properly? See mysql_real_escape_string()
You shouldn't end your queries with a semicolon when using mysql_query()
in $query = 'INSERT INTO users (id, first_name, second_name, register_date, lastlogin_date) VALUES ("' . $user_id . '", "' . $first_name . '", "' . $second_name . '", "' . $date . '", "' . $date . '");
are u giving the correct date format?? it might be the issue. otherwise the syntax is all fine.

Categories