Php blocking on variable declaration (w/psql) - php

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

Related

Wrong SQL Syntax? [duplicate]

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'
)

Insert a PHP false into mysql

My MySQL table contains a tinyint(1) value that i use to store a true or false value.
I have the following PHP variables:
$name = '';
$description = '';
$active = true;
Now my SQL query is as follows:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', $active) ";
This will only work if my value for $active is true. As soon as the active variable is false, php will insert an empty string, instead of a 0 and thus the query will fail.
What is the best method to use false in such a query?
Should i manually convert the false to a '0' string?
Is it better use stings on the PHP side right away? in other words declare: $active = '1';
or can i somehow get PHP to always convert false to a '0' string?
Thanks
Michael
Convert your variable to int:
intval($active)
First of all your values should be escaped using mysql_real_escape_string or mysqli_real_escape_string or other method suitable for your database connection to avoid sql injection then for your specific question regarding false you may do something like that:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".($active?1:0) .")";
or casting $active to int should do the work too:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".((int) $active)).")";
use a mysql_real_escape_string function...
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($description)."', ".mysql_real_escape_string (((int) $active))).")";

Zend_Db_Statement_Pdo->execute with expression in params

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))

PHP: Prepared statements (newbie) getting this error

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

MYSQL ERROR: "You have an error in your SQL syntax"

I have this query running in my PHP script:
$insertQuery = "INSERT INTO blog_articles
VALUES '$title', $tags', '$category', '$blog', '$author', '$date'";
I then run this script:
if ($result = $connector->query($insertQuery)){
// It worked, give confirmation
echo '<center><b>Article added to the database</b></center><br>';
}else{
// It hasn't worked so stop. Better error handling code would be good here!
die (mysql_error());
}
}
I get this 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 'Title Number 1, General, Blogging, Kayaking, General, Tgis is blog number spelli' at line 2
But I cannot tell what the error is.
You have a single quote missing before $tags.
Your query should be more like this
INSERT INTO blog_articles (`title`, `tags`, `category`, `blog`, `author`, `date`)
VALUES ('$title', '$tags', '$category', '$blog', '$author', '$date')
You should also look into sanitizing your query. Perhaps this way (but i don't know your exact setup, so results might vary)
$sql = sprintf("INSERT INTO blog_articles (`title`, `tags`, `category`,
`blog`, `author`, `date`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
mysql_real_escape_string($title), mysql_real_escape_string($tags),
mysql_real_escape_string($category), mysql_real_escape_string($blog),
mysql_real_escape_string($author), mysql_real_escape_string($date));
This uses the sprintf() function, the php documentation has some great examples.
You need to add the names of the fields you are inserting to
INSERT INTO blog_articles ('title', 'tags', 'category', 'blog', 'author', 'date') VALUES ('$title', '$tags', '$category', '$blog', '$author', '$date')
Also you should add some code to escape double or single quote in your text that could break the SQL query.
use the PHP function mysql_real_escape_string()
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
For more details:
http://uk.php.net/mysql_real_escape_string
As aknock says, you are missing a ' before $tags.
However, you really need to be using mysql_escape_string to protect against SQL injection attacks. Using mysql_escape_string for your SQL query parameters is a good habit to get into.
Using a DB wrapper like PEAR can make escaping parameters much less painful. Your code above could be written like:
$insertQuery = "INSERT INTO blog_articles \
(`title`, `tags`, `category`, `blog`, `author`, `date`) \
VALUES (?, ?, ?, ?, ?, ?)";
$data = array($title, $tags, $category, $blog, $author, $date);
if ($result = $connector->query($insertQuery, $data)) {
// It worked, give confirmation
echo '<center><b>Article added to the database</b></center><br>';
}else{
// It hasn't worked so stop. Better error handling code would be good here!
die (mysql_error());
}
(assuming $connector is a PEAR DB object)
Explicitly giving the names and order of the columns that you're inserting makes your code much more maintainable and readable. If you change the database schema later, you will be protected from inserting values into the wrong column, or into columns that don't exist any more.

Categories