basic query statement fails to execute - php

$query="INSERT INTO ".$table_name." VALUES ('$rowNum','$something',$_SERVER['REQUEST_TIME'], $_SERVER['REQUEST_TIME'], '$somethingelse')";
The error produced is
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in line 15
I have a problem with that query but I don't know where the mistakes are. Anyone sees the light please shed it on me. Thank you for your spot.
EDIT:
The query to create my table is
$query="CREATE TABLE ".$table_name." (id int not null auto_increment, something varchar(128), post_date varchar(32), edit_date varchar(32), somethingelse text)";

I find this syntax easier to manage and debug for anything but the most basic of parameter replacement into strings:
$query = sprintf("INSERT INTO %s VALUES ('%s', '%s', '%s', '%s', '%s');", $table_name,
$rowNum, $something, $_SERVER['REQUEST_TIME'], $_SERVER['REQUEST_TIME'],
$somethingelse)
N.B. You can also use printf in place of sprintf with the same structure to output the same string just like a print or echo statement.
A couple of other suggestions too:
Use PDO to simplify and abstract the database operations as well as making it easier to secure all of the statements with bound parameters in prepared statements.
Instead of using $_SERVER['REQUEST_TIME'] perhaps some default 'now()' date fields and triggers for mod_dates on the database would be more reliable and maintainable. (although I don't have full context to know whether you are explicitly inserting the server time for another reason which can't be handled by timestamping handled by the DB)

Have you tried
$query="INSERT INTO ".$table_name." VALUES ('$rowNum','$something',".$_SERVER['REQUEST_TIME'].",". $_SERVER['REQUEST_TIME']", '$somethingelse')";
EDIT - the problem was with $_SERVER['REQUEST_TIME'] which doesn't get interpreted by php as $sometext and so you have to concatenate it

Try:
$query="INSERT INTO ".$table_name." VALUES ('$rowNum','$something','".$_SERVER['REQUEST_TIME']."','". $_SERVER['REQUEST_TIME']."', '$somethingelse')";
Array values are should not be in single or double quotes.

Related

The formatting of the string appears to be incorrect, as 1 should be a value, and not a number

the title is a response i got working with hostgator about a php file I'm using to connect with my web mysql. Here's the suggestion from Hostgator:
"The error here is in the formatting of the string, There's a similar string higher in the file, that functions properly:
$query = sprintf("insert into `tinywebdb` (`tag`, `value`) values ('%s', '%s')",
This one shows values ('%s', '%s') and functions properly.
THE STRING WITH THE ERROR IS:
$query = sprintf("select `tag`, `value` from `tinywebdb` where `tag` = '%s' limit 1", mysql_real_escape_string($tag));
In short, the formatting of the string appears to be incorrect, as 1 should be a value, and not a number.
I need help fixing the 2nd query.
mysql_real_escape_string() is deprecated. You should read the mysql_real_escape_string doc for info on how to replace it.

MySQL PHP: Geting 0000-00-00 00:00:00 when using NOW() in a datetime column

Using the SQL in the below code:
public function saveOrder() {
$id = $this->getUserId();
$this->db->query("INSERT INTO orders VALUES (null, '$id', '$this->basket_lines', '$this->total', NOW() )");
return $this->db->id();
}
Where the last column in the above is a DATETIME field, the result in the database keeps defaulting to 0000-00-00 00:00:00.
I have tried the column format as timestamp too and used:
ALTER TABLE `content ` CHANGE `date` `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
from another post but to no avail.
Can anyone spot whats wrong?
Thanks
Edit: BTW I am escaping my SQL statement from within the DB class using
$this->SQL = $this->mysqli->real_escape_string($SQL);
$this->result = $this->mysqli->query($SQL);
Edit 2: I am now escaping pre query with
$i=mysql_real_escape_string($id);
$b=mysql_real_escape_string($this->basket_lines);
$t=mysql_real_escape_string($this->total);
$this->db->query("INSERT INTO orders VALUES (null, '$i', '$b', '$t', NOW() )");
Still not working, this all all rather odd?
You aren't escaping any data. In all likelihood, your data is messing up the rest of your query. It's also very likely that you are wide open to SQL injection. At a minimum, you should be using mysql_real_escape_string(), but it would be better to use prepared queries with PDO.
You got the escaping concept wrong, you need to escape the data you will insert in DB, to prevent SQL injection, not the whole query!
So you should do something like:
$id=$this->mysqli->real_escape_string($id);
$basketlines=$this->mysqli->real_escape_string($this->basket_lines);
$total=$this->mysqli->real_escape_string($this->total);
$SQL="INSERT INTO orders VALUES (null, '$id', '$basketlines', '$total', NOW() )");
$this->result = $this->mysqli->query($SQL);
I am pretty sure that all your problem is because when escaping the whole query, then query becomes malformed and not a valid SQL query anymore.
If the field is of type TIMESTAMP
try
$this->db->query("INSERT INTO orders VALUES (null, '$id', '$this->basket_lines', '$this->total', CURRENT_TIMESTAMP() )");
I don't see anything wrong with the query itself.
However I would like to advise you to read these 2 links.
http://nl.php.net/manual/en/book.pdo.php
http://nl3.php.net/manual/en/function.mysql-real-escape-string.php
The way you're using mysql is a HUGE security risk.

MySQL query broken

Ok its late and I am not catching why this is broken. So here goes.. the error is as follows
syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING
or T_VARIABLE or T_NUM_STRING
typically I would assume its a mising ; ' " or similar, I've checked I have found nothing missing from the surrounding code.
Now despite the possible "injection" factors which I don't care about currently someone please tell me whats wrong with this one line.
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, $when, $email, $fakeHash, '0', mysql_real_escape_string($_POST['fileID']))") or die(mysql_error());
Besides using a quoted subscript on an embedded (interpolated) variable, you are likely missing some quotes (around values) in the query.
Try this:
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, '".mysql_real_escape_string($when)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($fakeHash)."', '0', '".mysql_real_escape_string($_POST['fileID'])."')") or die(mysql_error());
If the $_POST['fileID'] is always expected to be an integer, then it does not need to be wrapped in a mysql_real_escape_string call and it would actually be safer (against SQL injection) and possibly more efficient to just cast it to an int:
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, '".mysql_real_escape_string($when)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($fakeHash)."', '0', ".((int)$_POST['fileID']).')') or die(mysql_error());
One of your variables contains an apostrophe:
$when, $email, $fakeHash
That's my guess. You should use mysql_real_escape_string() for all of those.
Make sure you enclose all text field values in (single or double) quotes (and make sure they are escaped). The quotes are required to make sure MySQL treats the text as strings and not as something else.
Alternatively, use PDO, and you don't have to worry about that.

Can't figure out what's wrong with my php/sql statement

So this is probably a dumb beginner question, but I've been looking at it and can't figure it out. A bit of background: just practicing making a web app, a form on page 1 takes in some values from the user, posts them to the next page which contains the code to connect to the DB and populate the relevant tables.
I establish the DB connection successfully, here's the code that contains the query:
$conn->query("SET NAMES 'utf9'");
$query_str = "INSERT INTO 'qa'.'users' ('id', 'user_name','password' ,'email' ,'dob' ,'sx') VALUES (NULL, $username, $password, $email, $dob, $sx);";
$result = #$conn->query($query_str);
Here's the error that is returned:Insert query failed: 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 ''qa'.'users' ('id', 'user_name' ,'password' ,'email' ,'dob' ,'s' at line 1
Thanks in advance!
Unless it's changed since I did MySQL in PHP, escape your db/column/table names with backticks (`), not apostrophes (').
A good general trouble-shooting technique is to make the query work via another interface to the database. For example, phpMyAdmin. If it works there, you have some confidence going forward. or you may find how to fix your SQL. (phpMyAdmin is handy because it will convert your SQL into a ready-made string for PHP.)
You need to escape your column names with a backtick (`) instead of (')
You also need to properly escape the actual values you are inserting as well (use a single quote)
OMG not a single right answer
$query_str = "
INSERT INTO `qa`.`users` (`id`, `user_name`,`password` ,`email` ,`dob` ,`sx`)
VALUES (NULL, '$username', '$password', '$email', '$dob', '$sx')";
identifiers being quoted with backticks, while strings being quoted with apostrophes!
and I hope you have passed all your variables through mysql_real_escape string BEFORE putting it into query, i.e.:
$username = mysql_real_escape string($username);
and so on

mystery mysql error

I'm by no means experienced in mysql and keep getting an error in this lines of code:
$sql= "INSERT INTO songs (unique_show_id, artist, date, year, city, state, venue, taper, transfered_by, source, mic_loc, lineage, uploaded_by, uploaded_on, show_notes, show_xml)
VALUES('$showId', '$artist', '$showDate', '$year, '$city', '$state', '$venue', '$taper', '$transferer', '$source', '$mic_loc', '$lineage', '$uploader', NOW(), '$show_notes', '$show_xml')";
//check to see if the query went through
if (!mysql_query($sql,$con)){
echo "query fail";
die('Error: ' . mysql_error());
}
I'm sure it's something simplistic, but I can't see where the error is. The error message I get is:
query failError: 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 'ipuhgbi', 'CA', '', '', '', '', '', '', 'danwoods', NOW(), '', '<show id=\'gm198' at line 2
Some of the values I'm inserting are NULL, but from what I've read I don't think that should be a problem. Any ideas?
Missing quote after $year.
When MySQL issues such an error (near bla di bla), the error is usually immediately before the string it mentions. In this case 'ipuhgbi' maps to $city, so you know it's right before '$city', and what do we see there? Voila, a missing quote.
You need to use mysql_real_escape_string() in each and every single one of your $variables.
Also, read this StackOverflow question carefully regarding SQL Injections.
It looks like the last single quote on the error line is not escaped.
you need to remember to sanitize all of the strings going into the query.
There are quite few things you need to be sure about:
You don't insert primary keys through queries (eg unique_show_id in your code)
For numbers you don't use single quotes.
It is better to use the set variant of inserting records which avoids count problems eg:
Use intval for numbers and mysql_real_escaps_string for strings to avoid injections issues as well as single quotes query erros.
insert into table set field='field_value', field2='field_value' // and so on

Categories