What's wrong with the PHP syntax here? - php

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']) . '\')';

Related

MySQLi queries with php - query strings contain single quotes and curly braces

I am writing a php script to put a dictionary file into a Mysql database. It works fine, except in certain cases when the definition strings contain both single quotes and multiple sets of curly braces. This is one of the definition strings that fails.
(n) (1) {sports} carry-back/bringing the ball back to one's own
position (in rugby)/(2) {econ} carryback/carrying over a deduction or
credit from a prior year to the current year (to reduce income tax)
This is the **MySQLi ** 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 's own position (in rugby)/(2) econ', {'(n) (1) {sports}
carry-back/bringing the ' at line 1
Heres the section of the script regarding the definition string:
$definition = substr($definition_string, 0, $pos);
$definition = substr($definition, 1);
// Escape single quote
$definition = str_replace(["'"], "''" , $definition);
$mysqli->set_charset("utf8");
$result = $mysqli->query("INSERT INTO dict (entry, reading, category, definition, entry_number) VALUES ('$entry', '$reading', '$category', '$definition', '$entry_number')");
I can't figure out why its failing and the error message isn't helping much. Any ideas?
I recommend you read about this here. They give several different methods on how to protect the data going into the database.
Here is one of the many ways:
$result = $mysqli->query("INSERT INTO dict (entry, reading, category, definition, entry_number) VALUES (
'" . $mysqli->escape_string($entry) . "',
'" . $mysqli->escape_string($reading) . "',
'" . $mysqli->escape_string($category) . "',
'" . $mysqli->escape_string($definition) . "',
'" . $mysqli->escape_string($entry_number) . "')");
Another more eloquent solution:
$stmt = $mysqli->prepare("INSERT INTO dict (entry, reading, category, definition, entry_number) VALUES (
?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $entry, $reading, $category, $definition, $entry_number);
$stmt->execute();
$result = $stmt->get_result();

PHP: Error when inserting quotation marks in mySQL

I insert a text variable in a mySQL table. Everything works fine except in the text is a quotation mark. I thought that I can prevent an error by using "mysql_real_escape_string". But there is an error anyway.
My insert statement:
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
mysql_real_escape_string($insertimage);
The error message:
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 '1413885955514','10')' at line 1
You need to escape data that you are putting into the SQL so that any special characters in it don't break the SQL.
You are escaping all the special characters in the final string of SQL; even those that you want to have special meaning.
If you want to use your current approach, you would do something like this:
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
… but the PHP mysql_ extension is obsolete and you shouldn't use it.
Modern APIs, such as mysqli_ and PDO support prepared statements, which are a better way to handle user input. This answer covers that in more detail.
The problem with your current code is that you have not correctly escaped the values you're trying to enter into the table.
Better still is to avoid the mysql_* function family entirely. Those functions are now deprecated and bring security risks to the table (along with other concerns).
You'd be better to use PDO and Prepared Statements, for example:
$db = new PDO('param1', 'param2', 'param3');
$sql = $db->prepare( 'INSERT INTO `image` (`filename`, `text`, `timestamp`, `countdown`)
VALUES (:filename, :text, :timestamp, :countdown)' );
$sql->execute( array(':filename' => $filename,
':text' => $text,
':timestamp' => $timestamp,
':countdown' => $countdown )
);
mysql_real_escape_string($insertimage);
You will have to use this function to each variables before writing the query.
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
Try this ,
$insertimage = sprintf("INSERT INTO image(filename,text,timestamp,countdown) VALUES ('%s','%s','%s','%s')", mysql_real_escape_string($filename), mysql_real_escape_string($text), $timestamp, $countdown);
Why, because your inputs vars must be escaped before using them in sql
then execute your sql.
Escaping the entire query is not useful. In fact, right now, you are causing syntax errors by doing so.
You should be escaping the individual variables that you inject into it.
Try this:
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage = "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
mysql_query($insertimage);
Concat the php variables like this:
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES (" . $filenamec . "," . $text . ", " . $timestamp . ", " . $countdown . ")";
with the respective single quotes in those that are text fields i.e: "... '" . $text . "' ..."

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

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']' )";

MySQLi query to MySQL query

I am trying do multi-driver support for my Framework, which basically means I can use MySQL, MySQLi or PDO(MySQL) with ease.
So, let's say I have an array of values I want to insert.
array('Manuel', 'StackOverflow');
and I have this query..
mysql_query("INSERT INTO users(name, fav_site) VALUES(?, ?)");
So, I'd like to replace the question marks with those values in order, so Manuel goes first and then goes StackOverflow. Remembering that I need to add -> ' <- at the sides of these values so MySQL doesn't throw an error.
I have tried searching if someone has asked this and had no luck.
Any help is appreciated!
NOTE: I know I shouldn't even bother with MySQL, but hey! A feature is a feature.
<?php
$query = "INSERT INTO users(name, fav_site) VALUES(?, ?)";
$args = array('joe', 'google goggles');
while(strpos($query, '?') !== FALSE)
{
$query = preg_replace('/\?/', your_quoting_func(array_shift($args)), $query, 1);
}
echo $query;
Basically, this says...while there is still a ? remaining in the string, delete the first question mark and replace it with a quoted (use your own function or mysql_real_escape_string and surround with single quotes) string, and shift that item off the array. You should probably substr_count the ? marks versus the number of arguments for error checking.
I used preg_replace because it accepts an argument specifying how many values to replace, whereas str_replace does not.
I would do it this way (with one exeption: I wouldn't use mysql_):
<?php
$values = array('foo', 'bar');
$query_start = "INSERT INTO `users` (`name`, `fav_site`) VALUES ('";
$query_end = "')";
$query = $query_start . implode("', '", $values) . $query_end;
$result = mysql_query($query);
?>
$query_start contains the start of the MySQL query (notice the ' at the end), and $query_end goes at the end.
Then $values is imploded, with ', ' as the 'glue', and $result is set as:
$query_start (impoded $result) $query_end.
See implode - PHP Manual.

PHP/MySQL Query and String Concatenation of row from mysql_fetch_array()

This works:
$row = mysql_fetch_array($result);
$accountID = $row['accountID'];
queryMysql('INSERT INTO accounts (accountID, password) VALUES (' .
"'$accountID'" . ', \'a\')');
But this doesn't:
$row = mysql_fetch_array($result);
queryMysql('INSERT INTO accounts (accountID, password) VALUES (' .
$row['accountID'] . ', \'a\')');
Why?
Because you're missing another ' right before and after $row['accountId']
$row = mysql_fetch_array($result);
queryMysql('INSERT INTO accounts (accountID, password) VALUES (\'' .
$row['accountID'] . '\', \'a\')');
If you are beginning PHP and have the required version of PHP (5.1.0) I strongly suggest you start using PDO
http://php.net/pdo
instead of the standard mysql_*
First, you should always tell us why it doesn't work. Only saying "it doesn't work" is really begging for getting your post ignored.
Second, the cause of the error is most likely the lack of quote, but that would only be necessary if there's another underlying problem. The type of the column accountID seems to be varchar or text. An ID should be an integer.
You have to wrap your value with quotes if it's a string, you don't if it's an integer.

Categories