Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Hammerite posted:

What does what we were talking about have to do with PDO versus proprietary database classes or functions? You would still have to work with resultset objects, or whatever the equivalent is when using PDO.

By the way - if your response to that is "PDO is so wonderful that you'll never need to use anything else, just explicitly use PDO instead of any kind of wrapper functions" then

a) I don't buy it,

b) I've seen example PDO code that you and others have posted and in my opinion it looks pretty ugly, and harder to understand than the code I make use of for performing queries.

Because it's a data-access abstraction layer and was created to solve this exact problem.

You don't buy it because you have obviously never had to deal with code from somebody who thought it would be a good idea to write their own custom undocumented code to solve a problem that has been solved. Not only that, but accessing various databases in other languages even use very similar syntax. It's very familiar for most developers.

Hammerite posted:

I find OO programming ideas difficult to understand (partly because of unfamiliarity but partly because they seem to add complexity that I don't see the need for), so I dislike and avoid them.

Clearly the problem isn't with PDO.

Adbot
ADBOT LOVES YOU

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Tiny Bug Child posted:

PDO is nice and all, but you still need to write a half-dozen lines of code to do anything useful. I use a set of sprintf-like wrapper functions that automatically escape arguments, run the query, and return the first field of the first result, or the first result row as an array, or the result set, etc.

I do something similar.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Tiny Bug Child posted:

PDO is nice and all, but you still need to write a half-dozen lines of code to do anything useful. I use a set of sprintf-like wrapper functions that automatically escape arguments, run the query, and return the first field of the first result, or the first result row as an array, or the result set, etc.

While those 6 lines are such a huge burden to type out (are you kidding me?) they are waaaaaay easier to read and debug.

Tiny Bug Child
Sep 11, 2004

Avoid Symmetry, Allow Complexity, Introduce Terror

fletcher posted:

While those 6 lines are such a huge burden to type out (are you kidding me?) they are waaaaaay easier to read and debug.

There's no way that
code:
$name = DB::get("SELECT `name` FROM affiliates WHERE affiliate_id=%d", $id);
is harder to read or debug than the equivalent PDO. Typing out a bunch of unnecessary and redundant code is actually a pretty big burden if you have to do it every single time you need to run some SQL. Plus, it makes your functions huge and messy if you need to hit the database a few times in one function.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

fletcher posted:

Because it's a data-access abstraction layer and was created to solve this exact problem.

You don't buy it because you have obviously never had to deal with code from somebody who thought it would be a good idea to write their own custom undocumented code to solve a problem that has been solved.

I am happy to accept that PDO is a high-quality toolset, but there is no objective reason why I ought to favour working with PDO directly in my code. Can you give a good reason why I ought not to wrap the functionality of PDO, or my chosen database access method, in functions that allow my code to be the neater to my eyes? (Besides "PDO will be familiar to other developers", I mean.)

Because that's what we're arguing about here. This isn't an argument about the merits of PDO, great though they might be, it's purely about the acceptability of exposing one's chosen database access method in suitable wrapper functions. My function that I call to make a query could internally be making use of PDO. In fact it isn't, it's using mysqli, but the point is it could be. I don't have to worry about it.

I have actually written some documentation for it, though I flatter myself it's self explanatory to the point that said documentation is mostly unnecessary.

fletcher posted:

Not only that, but accessing various databases in other languages even use very similar syntax. It's very familiar for most developers.

I take your point on board, but I do not consider this to be terribly important at this time. And if my code is well written, then its meaning will in any case be clear.

fletcher posted:

Clearly the problem isn't with PDO.

I've made peace with OO ideas a little more since I typed that. My code is still very definitely procedural from start to finish, but I would now say that I am happy to use objects when they are the best tool for the job. It's only sensible to use the right tool at the right time. (Of course, whether objects are "the best tool for the job" is to be judged by me rather than by anyone else.)

You complimented me on the tidy-html-formatting class I posted in this thread some pages back, so you are aware of this to at least some extent.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Tiny Bug Child posted:

There's no way that
code:
$name = DB::get("SELECT `name` FROM affiliates WHERE affiliate_id=%d", $id);
is harder to read or debug than the equivalent PDO. Typing out a bunch of unnecessary and redundant code is actually a pretty big burden if you have to do it every single time you need to run some SQL. Plus, it makes your functions huge and messy if you need to hit the database a few times in one function.

If all you ever have to write are the simplest queries conceivable, that may be sufficient. Unfortunately the real world does not work this way. Utility functions like that do have their place once in awhile, but in my experience it's fairly limited.

MrMoo
Sep 14, 2000

Tiny Bug Child posted:

I use a set of sprintf-like wrapper functions that automatically escape arguments

You should be using prepared statements, even better use stored procedures.

Tiny Bug Child
Sep 11, 2004

Avoid Symmetry, Allow Complexity, Introduce Terror

fletcher posted:

If all you ever have to write are the simplest queries conceivable, that may be sufficient. Unfortunately the real world does not work this way. Utility functions like that do have their place once in awhile, but in my experience it's fairly limited.
That was an example, not an upper bound on what a wrapper function can do. You can use as complex a query as you'd like; for my big ones I use a heredoc to write them out readably before the method call. The point is to hide the calls that you would otherwise have to make every time you want to do a certain kind of lookup. To get one field in one row of a mysqli result set, with no outside assistance, you call mysqli_query, mysqli_fetch_assoc, and then separately get the index in the array that you want.

Those are things that have to be done every time you want one field. It doesn't help anyone to see them done yet again; why not made your code more concise without sacrificing readability by hiding them in a method that does it for you? Just because the query gets more complex doesn't mean the scaffolding you have to put around it to get useful data back does- most of the time you want a field, or a row, or a result set back, and helper functions make it easy on you.

MrMoo posted:

You should be using prepared statements, even better use stored procedures.
There's nothing wrong with prepared statements, but people go around treating them like a silver bullet and they aren't. As far as I'm concerned they don't offer any tangible benefits over using a sprintf-lite helper function, they certainly aren't more concise, and if we really needed the middling boost in performance from them I would probably just rewrite my helper functions to use them instead.

Stored procedures are nice for when you have one query you use in a lot of different places, but at my job that's the case for exactly one query that I can think of, and I can't even imagine what a royal pain it would be to store several thousand queries and update our codebase accordingly.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Tiny Bug Child posted:

Stored procedures are nice for when you have one query you use in a lot of different places, but at my job that's the case for exactly one query that I can think of, and I can't even imagine what a royal pain it would be to store several thousand queries and update our codebase accordingly.

I make use of quite a lot of stored procedures (and I'd use a lot more of them if MySQL 5 supported variables in LIMIT clauses). It's great to be able to just issue

code:
$resultset = dbquery( DBQUERY_READ_RESULTSET,
                      'CALL "DescriptivelyNamedRoutine"(:variable1:, :variable2:)',
                      'variable1' , $variable1 ,
                      'variable2' , $variable2
                      );
and have it come back with the desired resultset from just one (very easy to read) function call.

The only annoying bit is when you want to update a stored procedure. To make that process smoother, I wrote a script that looks in a predefined directory for files containing stored procedure code (the files follow a naming convention), queries INFORMATION_SCHEMA to find out what procedures are present in the database, and presents options for refreshing or adding procedures.

Flamadiddle
May 9, 2004

I'm building a PHP site at the moment and I have a plethora of error messages that can be generated at various points of authentication, verification etc. What I have so far is a text file in the format:
code:
$ERROR_CODE ::$ERROR_DEFINITION
which I'm loading using file_get_contents and splitting into an associative array so that you can call getError($ERROR_CODE) throughout the code to get the corresponding text.

This sounds sensible and works fine, and I like the fact that I can just give this txt file to operators to maintain error messages as they want them, but this is causing the text file to be loaded on every request, which seems unnecessary. Is there a way to call a function or load a file into memory when I start PHP? (I'm using PHP-CGI on IIS 6.0).

Also, if this doesn't sound like a sensible way to hold error messages or there's a better way, I'm all ears.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Flamadiddle posted:

Also, if this doesn't sound like a sensible way to hold error messages or there's a better way, I'm all ears.

Why are you manually parsing a file into a hash every time instead of just storing it as a hash to begin with and using include?

Alternatives include gettext or storing the text strings in a database of some sort for the ultimate in overkill.

Flamadiddle
May 9, 2004

McGlockenshire posted:

Why are you manually parsing a file into a hash every time instead of just storing it as a hash to begin with and using include?

Well I won't be administering the system forever, and nobody I work with is confident in PHP. I figured they'd be more able to cope with changing a text file and restarting IIS.

Yay
Aug 4, 2007

MrMoo posted:

You should be using prepared statements.
There's no reason that a printf wrapper can't make use of prepared statements and bound parameters.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Flamadiddle posted:

Well I won't be administering the system forever, and nobody I work with is confident in PHP. I figured they'd be more able to cope with changing a text file and restarting IIS.

If they can change the file you are using now, they can change a file like this:

php:
<?
$error_codes = array( // DON'T TOUCH THIS LINE

 "ERROR_CODE" => "Some definition",
 "ANOTHER_ONE" => "Whee, this is fun",


); // DON'T TOUCH THIS LINE EITHER
?>

Flamadiddle
May 9, 2004

Lumpy posted:

If they can change the file you are using now, they can change a file like this:

php:
<?
$error_codes = array( // DON'T TOUCH THIS LINE

 "ERROR_CODE" => "Some definition",
 "ANOTHER_ONE" => "Whee, this is fun",


); // DON'T TOUCH THIS LINE EITHER
?>

Haha. Yeah, thanks, I'm sure I could do that. Was just curious.

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

Lumpy posted:

If they can change the file you are using now, they can change a file like this:

php:
<?
$error_codes = array( // DON'T TOUCH THIS LINE

 "ERROR_CODE" => "Some definition",
 "ANOTHER_ONE" => "Whee, this is fun",


); // DON'T TOUCH THIS LINE EITHER
?>

My concern about letting them update a PHP script is that typos could cause fatal errors. If a non-technical user sees a web page that looks like this:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')' in /var/www/html/errors.php on line 384


...it might as well be an air horn commanding them to have a panic attack.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Would you guys store a bunch of hashed values that expire onto MySQL, onto ram (xcache), or something else?

I'm generating a bunch of expiring links for a game every time a player moves and don't know where I should be storing them.

dark_panda
Oct 25, 2004

DaTroof posted:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')' in /var/www/html/errors.php on line 384


...it might as well be an air horn commanding them to have a panic attack.

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM :psyboom:

Maybe YAML or even CSV would be more suitable formats. At least with CSV one could use Excel or whatever, which presumably would be outputting correct syntax.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
So not being a Twitterer it escaped me that they've stopped allowing basic auth for API updates, they're making everyone use this "OAuth" thing now. I'm in charge of a stupid little PHP app that tweets every fifteen minutes (via cron) by making a cURL request directly to Twitter, but it stopped working about 11 hours ago. Anyone know of any *very simple* PHP->Twitter library that will essentially let me do

code:
$success=tweet($username, $password, $tweet_data);
?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

FeloniousDrunk posted:

So not being a Twitterer it escaped me that they've stopped allowing basic auth for API updates, they're making everyone use this "OAuth" thing now. I'm in charge of a stupid little PHP app that tweets every fifteen minutes (via cron) by making a cURL request directly to Twitter, but it stopped working about 11 hours ago. Anyone know of any *very simple* PHP->Twitter library that will essentially let me do

code:
$success=tweet($username, $password, $tweet_data);
?

This looks like it might work for you.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

fletcher posted:

This looks like it might work for you.

Thanks, I always forget about Pear. Now what is this 'auth_token' and 'token_secret' crap... don't answer that, it'll be a fun puzzle for this afternoon.

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

FeloniousDrunk posted:

Thanks, I always forget about Pear. Now what is this 'auth_token' and 'token_secret' crap... don't answer that, it'll be a fun puzzle for this afternoon.

It's those things you get at the arcade :q:

I won't tell you but it sounds like something you'd get from Twitter.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

FeloniousDrunk posted:

Thanks, I always forget about Pear. Now what is this 'auth_token' and 'token_secret' crap... don't answer that, it'll be a fun puzzle for this afternoon.

OAuth is a world of pain and horrors unless you've worked with something that works similarly. I would not describe it as a fun puzzle, especially when all the major libraries have little stupid idiosyncrasies as I recently discovered.

Apparently OAuth 2 (currently a draft) lightens up on the signing bullshit in favor of just requiring the use of SSL. I'm not sure if it still requires four tokens in total.

McGlockenshire fucked around with this message at 23:31 on Sep 2, 2010

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

McGlockenshire posted:

OAuth is a world of pain and horrors unless you've worked with something that works similarly. I would not describe it as a fun puzzle, especially when all the major libraries have little stupid idiosyncrasies as I recently discovered.

Apparently OAuth 2 (currently a draft) lightens up on the signing bullshit in favor of just requiring the use of SSL. I'm not sure if it still requires four tokens in total.

Well, this dude ended up helping me a lot, except that at the very end of his post he says that Twitter gives you the secret codes if you click around enough. I ended up using the PECL OAuth thing, and sidestepped Pear Twitter_Services since I'm just jamming things into Twitter without regard for friends or lists or anything fancy like that.

Fake edit: Well poo poo, I was going to be all self-congratulatory but now Twitter is sending me 403s.

As for "pain and horrors unless you've worked with something that works similarly", I've worked with Shibboleth.

epswing
Nov 4, 2003

Soiled Meat

FeloniousDrunk posted:

I've worked with Shibboleth.

Condolences :unsmith:

McGlockenshire
Dec 16, 2005

GOLLOCKS!

FeloniousDrunk posted:

As for "pain and horrors unless you've worked with something that works similarly", I've worked with Shibboleth.

This one? Well, all the keywords are there, let's see how it --

Shibboleth posted:

Shibboleth generates a SAML 1.1 authentication assertion with a temporary "handle" contained within it.

SAML. I'm sorry, man.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

McGlockenshire posted:

This one? Well, all the keywords are there, let's see how it --


SAML. I'm sorry, man.

[insert Chewbacca noise]

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
This is partly a MySQL question too, but... is there any reason to escape each parameter of a query individually, as I've been doing?
code:
$sQuery = 'SELECT * FROM table WHERE foo = "'.mysql_esc($foo).'"';
Can't I just do...
code:
$sQuery = mysql_esc('SELECT * FROM table WHERE foo = "whatev"');
?

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

Golbez posted:

This is partly a MySQL question too, but... is there any reason to escape each parameter of a query individually, as I've been doing?
code:
$sQuery = 'SELECT * FROM table WHERE foo = "'.mysql_esc($foo).'"';
Can't I just do...
code:
$sQuery = mysql_esc('SELECT * FROM table WHERE foo = "whatev"');
?

Everyone here will tell you to use PDO, but if you want to do what you are doing your best bet is to do this:

php:
<?
$value = mysql_real_escape_string($value);
$sQuery = "SELECT * FROM table WHERE foo = '{$value}'";
?>

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

DarkLotus posted:

Everyone here will tell you to use PDO, but if you want to do what you are doing your best bet is to do this:
I'm well aware of mysqli and PDO, and

quote:

php:
<?
$value = mysql_real_escape_string($value);
$sQuery = "SELECT * FROM table WHERE foo = '{$value}'";
?>

is exactly the scenario I put in my first option, so are you saying it's not kosher to simply escape the whole string?

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

Golbez posted:

is exactly the scenario I put in my first option, so are you saying it's not kosher to simply escape the whole string?

It's different, but yes, same concept. I'm not sure what will happen if you escape the whole query, probably best not to.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Golbez posted:

This is partly a MySQL question too, but... is there any reason to escape each parameter of a query individually, as I've been doing?
code:
$sQuery = 'SELECT * FROM table WHERE foo = "'.mysql_esc($foo).'"';
Can't I just do...
code:
$sQuery = mysql_esc('SELECT * FROM table WHERE foo = "whatev"');
?

What is mysql_esc?

(and yes, as said above, USE PDO)

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

fletcher posted:

What is mysql_esc?

(and yes, as said above, USE PDO)

Our shorthand for mysql_real_escape_string.

And nope, can't, I'd love to, but that would involve going through over 50,000 lines of code, so I need to work with what we have at the moment. I could spend some time adding it on to the current framework, but til I have that time, I was simply curious about if it was kosher to escape the whole string, and if so, why don't more people do it.

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players
If you escape the entire query, it will break, because all of the control characters (quotes) will be escaped, so quotes you manually put in there will be escaped.

edit:

Example

php:
<?
$query = "SELECT * FROM users WHERE name = 'bob'";
echo "Unescaped query: $query<br />\n";
$query = mysql_real_escape_string($query, $conn);
echo "Escaped query: $query<br />\n";
?>
outputs
Unescaped query: SELECT * FROM users WHERE name = 'bob'
Escaped query: SELECT * FROM users WHERE name = \'bob\'

butt dickus fucked around with this message at 22:00 on Sep 3, 2010

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
Aha, thanks, I knew there had to be some reason. :)

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players
This might be of use if you're going to be using everything that gets POSTed (you could do GET or PUT or whatever, too) in a query:

php:
<?
foreach($_POST as $key => $value)
  $$key = mysql_real_escape_string($value);?>
It's just like having register_globals on, but safer, and you can pick which ones to register.

edit: I am retarded. Don't do this.

butt dickus fucked around with this message at 15:25 on Sep 7, 2010

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Doctor rear end in a top hat posted:

This might be of use if you're going to be using everything that gets POSTed (you could do GET or PUT or whatever, too) in a query:

php:
<?
foreach($_POST as $key => $value)
  $$key = mysql_real_escape_string($value);?>
It's just like having register_globals on, but safer, and you can pick which ones to register.

I've been using array_map for this latest project (importing a CSV exported from AccesS), seems to be doing well so far. That one's not a bad idea, though.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Doctor rear end in a top hat posted:

This might be of use if you're going to be using everything that gets POSTed (you could do GET or PUT or whatever, too) in a query:

php:
<?
foreach($_POST as $key => $value)
  $$key = mysql_real_escape_string($value);?>
It's just like having register_globals on, but safer, and you can pick which ones to register.

I don't think this looks like a good idea.

I was under the impression that the security problems posed by register_globals weren't really related specifically to database injection.

What do you mean by "you can pick which ones to register"? That code surely just "registers" all $_POST entries as global variables.

I could see the following being acceptable:

code:
$my_accepted_post_vars = array('sausage', 'bacon', 'egg', 'beans');
foreach ( $_POST as $key => $value ) {
    if ( in_array($key, $my_accepted_post_vars) ) {
        $$key = mysql_real_escape_string($value);
    }
}
but not the indiscriminate version you posted.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

Doctor rear end in a top hat posted:

This might be of use if you're going to be using everything that gets POSTed (you could do GET or PUT or whatever, too) in a query:

php:
<?
foreach($_POST as $key => $value)
  $$key = mysql_real_escape_string($value);?>
It's just like having register_globals on, but safer, and you can pick which ones to register.

This isn't much safer, you are now letting anyone using your site to create any variable they want with any name/value within your code.

Adbot
ADBOT LOVES YOU

epswing
Nov 4, 2003

Soiled Meat

Doctor rear end in a top hat posted:

php:
<?
foreach($_POST as $key => $value)
  $$key = mysql_real_escape_string($value);?>

Dude! No!

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply