mysql_real_escape_string when echoing out? - mysql-real-escape-string

I know I have to use mysql_real_escape_string when running it in a query, for example:
$ProjectHasReservationQuery = ("
SELECT *
FROM reservelist rl
INNER JOIN project p on rl.projectid = p.projectid
WHERE rl.projectid = ". mysql_real_escape_string($record['projectid']) ."
AND restype = 'res'
");
But how about echoing it out, like:
query1 = mysql_query("SELECT * FROM users");
while ($record = mysql_fetch_array($query1 ))
{
echo "".stripslashes(mysql_real_escape_string($record['usersurname']))."";
// OR
echo "".$record['usersurname']."";
}
Which one is it? Personally I think echo "".$record['usersurname']."";, since this is coming FROM a query and not going INTO. But want to be 100% sure.
(I am aware about PDO and mysqli)

I know I have to use mysql_real_escape_string when running it in a query
Quite contrary, you should not use mysql_real_escape_string on a query like this.
It will do no good but leave you with false feeling of safety.
As you can say from the function name, it is used to escape strings, while you are adding a number. So, this function become useless, while your query still remains wide open for injection.
One have to use this function only to format quoted strings in the SQL query.
Thus you can conclude the answer from this rule: no, there is no point in using this function for output.
As for the protection, either treat your number as a string (by quoting and escaping it) or cast it using intval() function.
Or, the best choice, get rid of this manual formatting and start using placeholders to represent dynamical data in the query. it is not necessarily prepared statements - it could use the same escaping, but encapsulated in some placeholder handling function

Related

Have anyone found beautiful way to replace "smth if smth.present?"?

Often I'm facing lines like
result = 'Some text'
result += some_text_variable if some_text_variable.present?
And every time I want to replace that with something more accurate but I don't know how
Any ideas plz?
result += some_text_variable.to_s
It will work if some_text_variable is nil or empty string for example
But it always will concat empty string to original string
You can also use
result += some_text_variable.presence.to_s
It will work for all presence cases (for example for " " string)
You could "compact" and join an array, e.g.
['Some text', some_text_variable].select(&:present?).join
I realise this is a longhand form, just offering as an alternative to mutating strings.
This can look a bit nicer, if you have a large number of variables to munge together, or you want to join them in some other way e.g.
[
var_1,
var_2,
var_3,
var_4
].select(&:present?).join("\n")
Again, nothing gets mutated - which may or may not suit your coding style.

Lua heredoc with variable interpolation?

Is there a way to use a heredoc type of notation in Lua that references variables within the string?
The basic idea of what I'm trying to do would look something like follows. The heredoc piece is fine, but within Lua you can't actually reference the variable in the manner I'm showing below.
username = "bigtunacan"
sql=[=[
SELECT * FROM users WHERE username='$bigtunacan';
]=]
There's no built-in string interpolation, but it can be trivially implemented with gsub and replacement table.
sql=[=[
SELECT * FROM users WHERE username='$username';
]=]
print((sql:gsub('$(%w+)', { username = 'bigtucan' })))
-- SELECT * FROM users WHERE username='bigtucan';
Note an extra set of () - this is so only first return - the interpolated string is used from gsub and the 2nd - number of replacements made - silently discarded. This might be important if you use result of gsub as last in list of arguments to some function where adding one more argument might produce different behavior.
Also if you want to use this in SQL context, you really should use placeholders instead.
There is no Lua construct that allows variable interpolation within any string. See Literal Strings in the official reference guide.
You could of course write a function that would parse it and do the substitutions.

Rails: Given a String, check if an Array (of strings) contains a substring of String

Is there a more Railsy way to do this (without explicit regex, perhaps?):
array_o_strings = ["some strings", "I'd like", "to parse"]
string = "like to parse"
re = Regexp.union(array_o_strings.map { |i| Regexp.new(i) })
string =~ re
Just pining for magical Rails methods.
There's really nothing wrong with using a regular expression here if that's your intent. It's generally more efficient to use one of those than to go through the trouble of comparing arrays.
It's worth noting you don't have to do that much work to get this:
re = Regexp.union(array)
That should handle automatically escaping those strings and compiling them into a singular regular expression. Test with strings containing * and ? to be sure.
One note to add on style is that the =~ operator is a hold-over from Perl. It's preferable to use string.match(re) to make it clear what's going on there.
How big is the array? It may be worth comparing the speed using a regex vs checking each element. If the array is sorted shortest to longest that would help when checking one by one as you're more likely to find a match first.
In any event, this is one way:
array_o_strings.any?{|e| string.index(e) }

(F) Lex, how do I match negation?

Some language grammars use negations in their rules. For example, in the Dart specification the following rule is used:
~('\'|'"'|'$'|NEWLINE)
Which means match anything that is not one of the rules inside the parenthesis. Now, I know in flex I can negate character rules (ex: [^ab] , but some of the rules I want to negate could be more complicated than a single character so I don't think I could use character rules for that. For example I may need to negate the sequence '"""' for multiline strings but I'm not sure what the way to do it in flex would be.
(TL;DR: Skip down to the bottom for a practical answer.)
The inverse of any regular language is a regular language. So in theory it is possible to write the inverse of a regular expression as a regular expression. Unfortunately, it is not always easy.
The """ case, at least, is not too difficult.
First, let's be clear about what we are trying to match.
Strictly speaking "not """" would mean "any string other than """". But that would include, for example, x""".
So it might be tempting to say that we're looking for "any string which does not contain """". (That is, the inverse of .*""".*). But that's not quite correct either. The typical usage is to tokenise an input like:
"""This string might contain " or ""."""
If we start after the initial """ and look for the longest string which doesn't contain """, we will find:
This string might contain " or "".""
whereas what we wanted was:
This string might contain " or "".
So it turns out that we need "any string which does not end with " and which doesn't contain """", which is actually the conjunction of two inverses: (~.*" ∧ ~.*""".*)
It's (relatively) easy to produce a state diagram for that:
(Note that the only difference between the above and the state diagram for "any string which does not contain """" is that in that state diagram, all the states would be accepting, and in this one states 1 and 2 are not accepting.)
Now, the challenge is to turn that back into a regular expression. There are automated techniques for doing that, but the regular expressions they produce are often long and clumsy. This case is simple, though, because there is only one accepting state and we need only describe all the paths which can end in that state:
([^"]|\"([^"]|\"[^"]))*
This model will work for any simple string, but it's a little more complicated when the string is not just a sequence of the same character. For example, suppose we wanted to match strings terminated with END rather than """. Naively modifying the above pattern would result in:
([^E]|E([^N]|N[^D]))* <--- DON'T USE THIS
but that regular expression will match the string
ENENDstuff which shouldn't have been matched
The real state diagram we're looking for is
and one way of writing that as a regular expression is:
([^E]|E(E|NE)*([^EN]|N[^ED]))
Again, I produced that by tracing all the ways to end up in state 0:
[^E] stays in state 0
E in state 1:
(E|NE)*: stay in state 1
[^EN]: back to state 0
N[^ED]:back to state 0 via state 2
This can be a lot of work, both to produce and to read. And the results are error-prone. (Formal validation is easier with the state diagrams, which are small for this class of problems, rather than with the regular expressions which can grow to be enormous).
A practical and scalable solution
Practical Flex rulesets use start conditions to solve this kind of problem. For example, here is how you might recognize python triple-quoted strings:
%x TRIPLEQ
start \"\"\"
end \"\"\"
%%
{start} { BEGIN( TRIPLEQ ); /* Note: no return, flex continues */ }
<TRIPLEQ>.|\n { /* Append the next token to yytext instead of
* replacing yytext with the next token
*/
yymore();
/* No return yet, flex continues */
}
<TRIPLEQ>{end} { /* We've found the end of the string, but
* we need to get rid of the terminating """
*/
yylval.str = malloc(yyleng - 2);
memcpy(yylval.str, yytext, yyleng - 3);
yylval.str[yyleng - 3] = 0;
return STRING;
}
This works because the . rule in start condition TRIPLEQ will not match " if the " is part of a string matched by {end}; flex always chooses the longest match. It could be made more efficient by using [^"]+|\"|\n instead of .|\n, because that would result in longer matches and consequently fewer calls to yymore(); I didn't write it that way above simply for clarity.
This model is much easier to extend. In particular, if we wanted to use <![CDATA[ as the start and ]]> as the terminator, we'd only need to change the definitions
start "<![CDATA["
end "]]>"
(and possibly the optimized rule inside the start condition, if using the optimization suggested above.)

Lua string.gsub without printing match count

Frustratingly, any my previous Lua tries went in extensive Google searching of more/less same Lua resources, and then resulted in some multi-line code to get basic things, which i.e. I get from Python with simple command.
Same again, I want to replace substring from string, and use i.e.:
string.gsub("My string", "str", "th")
which results in:
My thing 1
I imagine replacement count can be useful, but who would expect it by default, and without option to suppress it, but maybe I miss something?
How to print just string result, without counter?
Enclose in parentheses: (string.gsub("My string", "str", "th")).
The results are only a problem because you are using print, which takes multiple parameters. Lua allows multiple assignments, so normally the code would look like
newstr, n = string.gsub("My string", "str", "th")
but the count is only provided if there is a place to put it, so
newstr = string.gsub("My string", "str", "th")
is also fine, and causes the count to be discarded. If you are using print directly (the same applies to return) then you should enclose the call in parentheses to discard all but the first result.

Resources