I am a newbie to prepared statements and trying to get something simple to work.
This is my DB table:
`unblocker_users` (
`uno` bigint(20) NOT NULL AUTO_INCREMENT,
`user_email` varchar(210) DEFAULT NULL,
`pw_hash` varchar(30) DEFAULT NULL,
`email_confirmed` tinyint(4) DEFAULT NULL,
`total_requests` bigint(20) DEFAULT NULL,
`today_date` date DEFAULT NULL,
`accessed_today` tinyint(4) DEFAULT NULL,)
and this is my function to insert some test data
function add_new_user($e_mail1)
{
require_once "db.php";
// ####### Below line is giving an error ########
$stmt = $mysqli->prepare("INSERT INTO unblocker_users VALUES ("",?, ?,0,0,?,0)");
$stmt->bind_param('sss', $e_mail1, $this->genRandomString(1),$this->today_date());
$stmt->execute();
$stmt->close();
$done = $stmt->affected_rows;
return $done;
}
As you can see above, i have marked the line that is giving me an error.
The error is" Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in..."
Where did I go wrong?
This line might be causing a problem
$stmt = $mysqli->prepare("INSERT INTO unblocker_users VALUES ("",?, ?,0,0,?,0)");
See you close and open the string again in the values, change "" to '' Thats all I could see from a quick glance.
You have " with a double quoted string. PHP thinks
"INSERT INTO unblocker_users VALUES ("",?, ?,0,0,?,0)"
is 2 strings:
"INSERT INTO unblocker_users VALUES ("
",?, ?,0,0,?,0)"
but doesn't what you want to do with them.
change the outside quotes to single quotes and it should work:
'INSERT INTO unblocker_users VALUES ("",?, ?,0,0,?,0)'
"INSERT INTO unblocker_users VALUES ("",?, ?,0,0,?,0)"
In php if you want to use double quotes within double quotes, you must escape the inner ones
"INSERT INTO unblocker_users VALUES (\"\",?, ?,0,0,?,0)"
Or use single quotes as outer ...
'INSERT INTO unblocker_users VALUES ("",?, ?,0,0,?,0)'
... or inner quotes
"INSERT INTO unblocker_users VALUES ('',?, ?,0,0,?,0)"
As far as I know mySQL use single quotes anyway
Related
This question already has answers here:
MySQL, safely using reserved word in query [duplicate]
(2 answers)
Closed 9 years ago.
I am building a small Twitter clone for personal use, and I have so trouble with it.
Fist, I want to show you my SQL structure of the table "poke_history":
http://puu.sh/3Sci0.png
This is the command I use to insert the values into a table (in PHP):
$insert = "INSERT INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
This is the annoying error that I am getting:
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 'from, time, reason) VALUES ( '1'' at line 3.
Let me clarify some things.
$to_id is a number.
$from_id is a number.
$time is a number (coming from PHP's time()).
$reason is a text string.
I am using MySQL and PHP5.
Try to quote your column identifiers like
INSERT INTO poke_history (`id`, `from`, `time`, `reason`) ...
Everything inside `` is considered to be a "identifier" not a language keyword. From the SQL-syntax it should be clear that after INSERT INTO tablename cannot come a FROM, but the MySQL sometimes needs this kind of guidance (and other sql parsers, too).
credit to mario as well:
from is a reserved keyword. Use backticks to escape them.
for example
`from`
INSERT INTO table (`from`) ....
So your code would like this:
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES (".$to_id.", ".$from_id.", ".$time.", '".$reason."')";
mysql_query($insert) or die(mysql_error());
Numbers don't need to be quoted. Only strings.
Also don't use mysql, it's deprecated. Better use PDO, with prepared statements, to avoid issues like this.
You should try to use prepared statements to prevent SQL injection.
$query = "
INSERT INTO
poke_history (`id`, `from`, `time`, `reason`)
VALUES
(:id, :from, :time, :reason)";
$db = new PDO("mssql:host=sqlserver;dbname=database", "username", "password");
$statement = $db->prepare($query);
$parameters = array(
":id" => $name,
":from" => $from,
":time" => $time,
":reason" => $reason
);
$statement->execute($parameters);
I think that you forgot to add * in between INSERT and INTO, here is the fixed script:
$insert = "INSERT * INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
The reason why you are getting the error is because you are trying to use a built in function name for one of your columns. Say you have the following CREATE TABLE...
CREATE TABLE customers
(
name varchar(80),
streetAddr varchar(160),
"from" varchar(60),
);
Notice that to create the table I had to put the column from in quotes. Now if you wanted to insert a row into this table, your insert statement should look like the following:
INSERT INTO ShoppingFun.dbo.customers
(
name,
streetAddr,
"from"
)
VALUES
(
'MRBubbleGum',
'1061 SW BubbleGumVillage St',
'yourmom'
)
I'm kind of a newbie in PHP but even I think this is not normal.
My code blocks in the followoing line all the time:
$insert = 'INSERT INTO boleia VALUES ('.$nick.', '.$data_format.', '.$custo.', '.$dest_origem.', '.$dest_destino.', NULL, '.$matricula.');';
I tried with double quotes and with the variables inside those double quotes and nothing.
Any idea?
Your PHP code is syntactically correct but the generated SQL is not because you are not using quotes to delimit the values.
You can do this:
$insert = 'INSERT INTO boleia VALUES ("'.$nick.'", "'.$data_format.'", "'.$custo.'", "'.$dest_origem.'", "'.$dest_destino.'", NULL, "'.$matricula.'");';
or this:
$insert = "INSERT INTO boleia VALUES ('".$nick."', '".$data_format."', '".$custo."', '".$dest_origem."', '".$dest_destino."', NULL, '".$matricula."');';
you can also do this:
$insert = "INSERT INTO boleia VALUES ('$nick', '$data_format', '$custo', '$dest_origem', '$dest_destino', NULL, '$matricula');";
but none of that ways are recommended because you are vulnerable to SQL Injections!
How to prevent SQL Injections?
To prevent that you must escape the values using the appropriate function for your DB, for example, since you are using PostgreSQL you must use pg_escape_string() for every value:
$insert = 'INSERT INTO boleia VALUES ("'.pg_escape_string($nick).'", "'.pg_escape_string($data_format).'", "'.pg_escape_string($custo).'", "'.pg_escape_string($dest_origem).'", "'.pg_escape_string($dest_destino).'", NULL, "'.pg_escape_string($matricula).'");';
An other way would be using pg_prepare() with pg_execute()
pg_prepare($dbconn, "my_insert", 'INSERT INTO boleia VALUES ($1, $2, $3, $4, $5, NULL, $6);');
pg_execute($dbconn, "my_insert", array($nick, $data_format, $custo, $dest_origem, $dest_destino, $matricula));
Or even using pg_query_params()
pg_query_params($dbconn, 'INSERT INTO boleia VALUES ($1, $2, $3, $4, $5, NULL, $6);',
array($nick, $data_format, $custo, $dest_origem, $dest_destino, $matricula));
Each value in an insert query requires quotes around it unless it's a number or NULL.
$insert = "INSERT INTO boleia VALUES ('$nick', '$data_format', '$custo', '$dest_origem', '$dest_destino', NULL, '$matricula');";
If you use PDO you don't have to worry about quoting or escaping anything.
Example from this PDO Tutorial:
$stmt = $db->prepare("INSERT INTO table(field1,field2,field3) VALUES(:field1,:field2,:field3)");
$stmt->execute(array(':field1' => $field1, ':field2' => $field2, ':field3' => $field3));
$affected_rows = $stmt->rowCount();
You need to encapsulate the string values going in to the query.
E.g.
$insert = 'INSERT INTO boleia VALUES ("'.$nick.'", "'.$data_format.'", "'.$custo.'", etc.
You better use double quotes for the SQL strings as it will be easier for you later on to sport where you didn't encapsulate by the quotes your strings
$insert = "INSERT INTO boleia VALUES ('$nick', '$data_format', '$custo', '$dest_origem', '$dest_destino', NULL, '$matricula')";
People, common. The original question is only 1 (ONE) line long! It is exactly this:
$insert = 'INSERT INTO boleia VALUES ('.$nick.', '.$data_format.', '.$custo.', '.$dest_origem.', '.$dest_destino.', NULL, '.$matricula.');';
we don't have to fix here any non-escaped strings presuming he hasn't done it before, neither we should presume that he is using PostgreSQL just because we see it in the tags. He had a simple error - missing encapsulation of strings in the query. It is fixed, in it's simplest form, as this:
$insert = 'INSERT INTO boleia VALUES (\''.$nick.'\', \''.$data_format.'\', \''.$custo.'\', \''.$dest_origem.'\', \''.$dest_destino.'\', NULL, \''.$matricula.'\');';
And that's it!
If, and only if, we like to add some extra info, as of how to escape the strings in case this hasn't been done, or if we are better using double quotes since it is less human-error-prone in such case, or if there is a good PDO Tutorial to read.... it's all either an additional info after the exact answer to his problem, or a chatty-off-topic.
Cheers.
$db = new mysqli( some db data );
$nick = $db->real_escape_string( $nick );
$data_format = $db->real_escape_string( $data_format ); // this is probably not needed
$dest_origem = $db->real_escape_string( $dest_origem );
$dest_destino = $db->real_escape_string( $dest_destino );
$matricula = $db->real_escape_string( $matricula );
$insert = "INSERT INTO boleia VALUES ('$nick', '$data_format', '$custo', '$dest_origem', '$dest_destino', NULL, '$matricula')";
and you should be OK
I need a little help with this, I am trying to insert some data into a MYSQL table which includes the now values for date & time for orders.
Code:
$query= "INSERT INTO ordertable
VALUES ('".$listauthor."','".$ordernumber.",'"NOW()"','"NOW()"')";
Error:
Parse error: syntax error, unexpected T_STRING in C:\xampp\htdocs\createbasket.php on line 15
How can I fix this?
Remove the quotes from around NOW() ... it's a MySQL function ... not a string.
You don't want to encapsulate NOW() with quotes. You'd need to do:
$query= "INSERT INTO ordertable
VALUES ('".$listauthor."','".$ordernumber."',NOW(),NOW())";
$query= "INSERT INTO ordertable VALUES ('".$listauthor."','".$ordernumber.",'"NOW()"','"NOW()"')";
Shouldn't be quotes around NOW
$query = "INSERT INTO ordertable VALUES ('".$listauthur."','".$ordernumber."', NOW(), NOW())";
Now() is a mysql function so don't need to put it inside single/double quotes.When you put inside quotes then it will treat it as variable.Just write as follows :
$query= "INSERT INTO ordertable VALUES ('".$listauthor."','".$ordernumber.",NOW(),NOW())";
I try to execute insert statement with "on duplicate" part. As I know Zend doesn`t support this, so I use simple statement:
$sql = "INSERT INTO agent(`inn`, `name`, `created`) VALUES(:inn, :name, :created) ON
DUPLICATE KEY UPDATE `inn` = :inn, `name` = :name, `created` = :created";
$stmt = $this->db->prepare($sql);
$stmt->execute($bind);
Where $bind - is array:
array(
'inn'=>1234567890,
'name'=>'test user',
'created' = new Zend_Db_Expr('NOW()')
);
If I try this query through phpMyAdmin - all works fine,
but after script execution the "created" column value is '0000-00-00 00:00:00'.
WTF?
You can't use an expression as an argument to a placeholder in a prepared statement. It will be interpreted as a string. This has nothing to do with zend framework.
You can either created a formatted date string in php and use that, or use now() in the prepared statement like
VALUES(:inn, :name, NOW())
Another solution, if you need to sometimes supply a datetime, and sometimes use NOW(), is using conditionals to check for that specific case
VALUES(:inn, :name, IF(:created = 'NOW()', NOW(), :created))
I want to insert a few certain values from a php file, to my MySQL database, using a query.
I use the following code snippet:
mysql_query("INSERT INTO `text` VALUES ('', '$user_id', '$text', '"$categories"')");
but I get an error saying the following:
Parse error: syntax error, unexpected T_VARIABLE in
C:\xampp\htdocs\Project\Func\idea.func.php on line 10
Does anyone know what I'm doing wrong?
I have stated both variables, earlier, by making them into real escape strings. My MySQL table structure is as follows:
idea_id (auto)
user_id
text
categories
timestamp
You need to use string concatenation:
mysql_query("INSERT INTO `text` VALUES ('', '$user_id', '$text', '" . $categories . "')");
or get rid of the double quotes surrounding $categories:
mysql_query("INSERT INTO `text` VALUES ('', '$user_id', '$text', '$categories')");
I would prefer
mysql_query(sprintf(
"INSERT INTO `text` VALUES ('', '%s', '%s', '%s')",
mysql_real_escape_string($user_id),
mysql_real_escape_string($text),
mysql_real_escape_string($categories))
);
Change '"$categories"')") to '" . $categories . "')".
You need to put fullstops between the variables to tell PHP that you want to concatenate (join) all of it together as a string.
Point is very important in this case it serves to separate the two variables in this case. If there is no point return error