What is the syntax error in this SQL/PHP Code? - php

Dreamweaver is reporting an error in the 3rd line of the following code:
if (isset($_POST['sitename']))
{
$query = "INSERT INTO dllist (name, url, pr) VALUES ( "$_REQUEST['sitename'], $_REQUEST['siteurl'], $_REQUEST['pagerank']" )";
$result = mysql_query($query)
or die("Query Failed".mysql_error());
echo "<br />Website Has been added<br />";
}
Also, when running the code in my browser the following error is reported
Parse error: syntax error, unexpected '$_REQUEST' (T_VARIABLE)
Can anybody tell me where the mistake is? I shall really be grateful.

The commas (and the fact your missing the containers around your values (e.g. single quotes)), it should be:
$query = "INSERT INTO dllist (name, url, pr) VALUES ('".$_REQUEST['sitename']."', '".$_REQUEST['siteurl']."', '".$_REQUEST['pagerank']."')";
Although this is still bad practice, and it has no SQL Injection protection.

You need to concatenate the string. Change VALUES (" to VALUES (" .

the values you put in insert query need to be single quoted individually like this:
$query = "INSERT INTO dllist (name, url, pr) VALUES ( '$_REQUEST['sitename']', '$_REQUEST['siteurl']', '$_REQUEST['pagerank']' )";

Related

What's wrong with the PHP syntax here?

I'm having hard time to figure out whats wrong in this code. I tried many variations but still getting error in this line:
$query= "INSERT INTO publish (name, email, title, content)" .
"VALUES ('$row['Name']','$row['Email']',$row['title'],$row['content'])";
What could be wrong?
here's the rest of the code:
<?php
// connect to the database
include('config2.php');
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = $_GET['id'];
$dbc = mysqli_connect('localhost', 'x', 'x', 'x')
or die('Error');
$name = $row['Name'];
$email = $row['Email'];
$title = $row['title'];
$content = $row['content'];
$result = mysql_query("select *stories WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$query= "INSERT INTO publish (name, email, title, content)" .
"VALUES ('$row['Name']','$row['Email']',$row['title'],$row['content'])";
or die('Error querying database.');
mysqli_close($dbc);
}
?>
Error message: "parse error expecting identifier (t_string) ' or variable (t_variable) ' or number (t_num_string) '"
You probably want to use complex string syntax to properly interpolate those variables. For example:
$query= "INSERT INTO publish (name, email, title, content)" .
"VALUES ('{$row['Name']}','{$row['Email']}',{$row['title']},{$row['content']})";
Though that will only fix one of the issues with the code.
Do note there are plenty of other ways to resolve this one too, such as concatenation instead of interpolation, or string replacements, etc etc.
It might also be worth reading the documentation on strings at some point.
You forgot the "." between your variables and your strings. Like so:
$query= "INSERT INTO publish (name, email, title, content)" .
"VALUES (".$row['Name'].','.$row['Email'].','.$row['title'].','.$row['content'].")";
However, it looks like you may have some additional issues going on there with the actual SQL query.
The best practice in PHP is to use single quote ' for strings. Cos PHP looks for variables inside double quoted strings and keeps on sniffing whether there is a variable (or multiple variables) inside the string.
So for example: "A very very long string... $var1 .. long string .. $var2 string" this will run slower compared to 'A very very long string... ' . $var1 . ' .. long string .. ' . $var2 . ' string'; cos when PHP sees single quote it won't sniff for variables inside it thus it's faster.
From my experience, in my early age I worked on a very large php script and used double quotes everywhere. After the above explanation from an expert I converted the whole script to single quote and the performance was much better.
So for your situation I'd suggest and request to use single quotes and it'll avoid confusions as well. Also using mysql_real_escape_string() is a good practice to avoid SQL Injection.
$query= 'INSERT INTO publish (name, email, title, content)
VALUES (
\'' . mysql_real_escape_string ($row['Name']) . '\',
\'' . mysql_real_escape_string ($row['Email']) . '\',
\'' . mysql_real_escape_string ($row['title']) . '\',
\'' . mysql_real_escape_string ($row['content']) . '\')';

debug mysqli query with or die mysqli_error

I don't know what is wrong.
$result = $db->query("INSERT INTO post_items(`post_id`,`content`,`date`,`user_id`,`category_id`)
VALUES ('".$postid.", '".$content."', '".$date."', '".$user_id."', '".$category_id."')");
if($result) {
echo "hey";
}
How can I use mysqli_error function to check the cause of error? The syntax of PHP is just fine I think. I guess it has problem with my database.
You have a problem with single quotes. You have a ' just before your $postid, but not one after. This means that the SQL query will be seeing '$postid, ' as your first variable and then being confused about the remained.
Try changing your SQL to read:
$result = $db->query("INSERT INTO post_items(`post_id`,`content`,`date`,`user_id`,`category_id`)
VALUES ('".$postid."', '".$content."', '".$date."', '".$user_id."', '".$category_id."')");
Hope that helps.

MySQL query issue with Flex, php

I'm trying to pass a MySQL query with variables from flex to MySQL using php.
This is the Query in Flex. Everything appears to be correct.
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
When the query is passed to my server via http to be processed by PHP it returns the following 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 'Test_Value )' at line 1
From what I can see it is trying to include the final ")" as part of the value. I for the life of me cannot see how to stop this from happening.
Here is the php that is being used to process the query where it errors out.
$sql = $_REQUEST['sql'];
$result = mysql_query($sql);
$err = mysql_error();
$cols_count = mysql_num_fields($result) or error_log('Invalid query: ' .mysql_error());
Any help will be much appreciated
This is the function passing the query. Maybe the issue is here?
public function mysqlQuery(sql:String,fid:String):void {
var http:HTTPService = new HTTPService;
var parm:Object = new Object;
parm.sql = sql;
parm.private_key = private_key;
parm.fas_db = mysql_db;
http.url = mysql_url+"?irand="+Math.random();
http.showBusyCursor = true;
http.request = sql;
http.addEventListener(ResultEvent.RESULT, mysqlResult);
http.addEventListener(FaultEvent.FAULT, mysqlFault);
http.method = "POST";
sqlToken = http.send(parm);
sqlToken.param = fid;
}
Change this
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
to
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ('"+firstName+"','" +lastName+"')");
put ' around values
For removing \
$result = mysql_query(stripslashes($sql));
Changed into
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
to
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ('"+firstName+"','" +lastName+"')");
IN sql , the string character are quoted in single quotes/double quotes.

Preparing SQLite SQL statements in PHP

I'm trying how best to prepare my SQLite SQL strings in PHP. The SQLite3 class comes with an escapeString() function, but here are my issues:
Try 1)
$sql = "INSERT INTO items ('id','content','title','created') VALUES ('4e7ce7c18aac8', 'Does this work', NULL, '2011-09-23T16:10:41-04:00');";
$sql = SQLite3::escapeString( $sql );
echo ($sql);
This results in a string that's all jacked up:
INSERT INTO items (''id'',''content'',''title'',''created'') VALUES
(''4e7ce7c18aac8'', ''Does this work'', NULL,
''2011-09-23T16:10:41-04:00'');
Those aren't double quotes, rather doubled-up single quotes. Obviously won't work.
Try 2)
$sql = 'INSERT INTO items ("id","content","title","created") VALUES ("4e7ce7c18aac8", "Does this work", NULL, "2011-09-23T16:10:41-04:00");';
$sql = SQLite3::escapeString( $sql );
echo ($sql);
This results in:
INSERT INTO items ("id","content","title","created") VALUES
("4e7ce7c18aac8", "Does this work", NULL,
"2011-09-23T16:10:41-04:00");
This query works fine, but the escapeString function hasn't modified anything as there's nothing to escape...
Try 3)
$sql = 'INSERT INTO items ("id","content","title","created") VALUES ("4e7ce7c18aac8", "Doesn't this work", NULL, "2011-09-23T16:10:41-04:00");'; $sql = SQLite3::escapeString( $sql ); echo ($sql);
Here's the big problem- Now I have an apostrophe in one of my values. It won't even make it to escapeString() because PHP will throw an error on the invalid string:
PHP Parse error: syntax error, unexpected T_VARIABLE, expecting ','
or ';'
How am I supposed to be approaching this? Keep in mind that in the actual code my parameter values will be variables, so am I supposed to escape each variable before I pass it into the string? If so, what function do I use?
Finally, what's the point of escapeString()?? I can't figure out how it's supposed to be used correctly.
You don't escape the entire query. You escape unsafe data you're inserting into the query, e.g.
$unsafe = $_GET['nastyvar'];
$safe = SQLite3::escapeString($unsafe);
$sql = "INSERT INTO table (field) VALUES ($safe);";
echo ($sql);

trouble with quotes and mysql insert into

I'm having problems inserting a form $_POST variable to MySQL!
I know it's a single quote problem but simply cannot resolve it.
Code is:
$naziv_db = $_POST["naziv"];
$naziv_db = mysql_real_escape_string($naziv_db);
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
$stmt = mysql_query($query) or die("MySQL error: " . mysql_error());
If I enter a value containing " it inserts correctly, but if it contains ' then the error appears!
For example if my input is Milky's
error is: MySQL 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 's
If my input is "Milkys" everything goes well...
I'm new here, so can't post an answer to my own question so i have to edit!
Christian's solution was the right one!
I have changed the code:
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
to:
$query = 'INSERT INTO `items` (`title`) VALUES ("'.$naziv_db.'")';
and now it accepts both " and ' without error!
Thank you guys, you're the best :D
To avoid this entirely, you'd be best using a prepared statement.
There's a good example in the answer to this question.
Converted for your case, you get:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO items (title) VALUES (?)");
$stmt->bind_param('s', $_POST["naziv"]);
$stmt->execute();
$stmt->close();
It's quite impossible to get such an error from your code.
Most likely there is a typo somewhere in it.
May be you're escaping wrong variable or it's another query producing this error
Are you sure you posted the code you actually running? is it exact code or some sketch?
change your mysql_query string to this one
mysql_query($query) or trigger_error(mysql_error()." ".$sql);
and paste it's output please.
or, even change whole code:
ini_set('display_errors',1);
error_reporting(E_ALL);
$naziv_db = $_POST["naziv"];
$naziv_db = mysql_real_escape_string($naziv_db);
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
var_dump($_POST["naziv"]);
echo "<br>\n";
var_dump($naziv_db);
echo "<br>\n";
var_dump($query);
echo "<br>\n";
mysql_query($query) or trigger_error(mysql_error()." ".$sql);
this is called "debugging" and usually helps.
Try addslashes - it's made for parsing strings into database-friendly content.

Categories