O'Reilly logo

PHP & MySQL: The Missing Manual by Brett McLaughlin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Better Searching with Regular Expressions

In the last chapter, you did one of the most common things programmers do: Write code that solves a problem, but is ugly, messy, and a little hard to understand. Unfortunately, most programmers leave code in that state because…well, it works.

Bad code is like sloppy plumbing or a poorly constructed house framing. At some point, things are going to go bad, and someone is going to have to fix problems. And, if you’ve ever had an electrician tell you what they’ve got to charge you because of the guy who did it wrong before him, then you know how expensive it is to fix someone else’s mistakes.

But here’s the thing: even good code is going to fail at some point. Anytime you’ve got a system where humans are involved, someone will eventually do something unexpected, or maybe just something you never thought about dealing with when you wrote your code. And that’s when you’re the electrician, trying to fix things when the customer’s unhappy—but there’s nobody else to blame.

So writing ugly code that works really isn’t an option. And the code in run_query.php right now is very ugly. It’s all those if statements, trying to figure out whether the user entered a CREATE or an UPDATE or an INSERT, or maybe a SELECT…or who knows what else? What you really need is a way to search the incoming query for all those keywords at one time. And then there’s converting things to uppercase, and dealing with whitespace, and making sure the SQL keyword you ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required