Inline Values: The Ternary Operator

So, you have a text field, and you’re using an associative array to fill the values based on table data from your RDBMS, right?

You’re filling the values inline, something like:

value=”<?=$row['name']?>”

Which is great, so long as you’re sure the row will exist. If the row doesn’t, you get an E_NOTICE telling you there’s an undefined index. You could turn off error reporting, and poof, it works, or you could do it right.

Turning off error reporting to mask sloppy coding practices is like stopping doctor visits once you’ve been diagnosed with cancer. You’re still sick, you’re just not hearing about it any more. And just like a disease will continue to have adverse affects whether you admit it or not, your server’s error log will fill up with undefined index and undeclared variable warnings and notices. Will this cause a long term server problem? Maybe, but I doubt it.

More important, filling up the server log with garbage makes you less able to diagnose real problems and fix them, because you have to sift through millions of lines of stupid notices and warnings to get to find a “real” error.

Let’s say you’re pulling the row like this, and assigning the array:

$result = mysql_query(”select * from users where id=1″);
$user = mysql_fetch_assoc($result);

If there is no record, you have a problem. Granted, most programmers I’ve seen are too sloppy and lazy to care about such a problem, but the problem still exists regardless of how you feel about it.

In a situation like the above (which is not the best way to access a DB, IMHO, use classes and good architecture), you can short circuit the issue by declaring the empty array first and then using a decision block to init the data if there is something to init.

$row = array();
$result = mysql_query(”select * from users where id = 1″);
if (mysql_num_rows($result)):
  $row = mysql_fetch_assoc($result);
endif;

This step alone does not solve your problem, it lays the foundation by which your problem can be solved. Now, when you do an inline value (interpolated into the HTML), do it with the ternary operator:

value=”<?=$row ? $row['name'] : “”?>”

The ternary operator is a standard construct in most programming languages (VB6 had IIF, but it’s the same thing). The Syntax of the ternary operator is:

condition ? truepart : falsepart

Where condition is any valid statement that translates into a boolean, truepart is what to do when it’s true, and falsepart is what to do when it’s false.

Let’s take something a teensy bit more complicated. If you have a date in the database (let’s say a DateTime type), and you want to initialize to the current date if the date in the table is empty, otherwise print the date as m/d/Y, the ternary operators can be nested like so:

value=”<?=$row ? $row['date'] ? date(’m/d/Y’, strtotime($row['date'])) : date(’m/d/Y’) : date(’m/d/Y’)?>”

Confusing? Not so much. If we use some parentheses to section it off, it looks like:

value=”<?=”$row ? ($row['date'] ? date(’m/d/Y’, strtotime($row['date'])) : date(’m/d/Y’) ) : date(’m/d/Y’)?>”

Which is the same thing as doing this (in blocks):

if ($row):
   if ($row['date']):
     print date(’m/d/Y’, strtotime($row['date']));
   else:
     print date(’m/d/Y’);
   endif;
else:
   print date(’m/d/Y’);
endif;

Interpolation of PHP into HTML gets a bad rap either way, because it makes code harder to maintain, and a little ugly. But if you’re going to do it, and many of us still do (I don’t want to have the overhead and code size of something like Smarty all the time), then do it well and correctly.

And correctly includes the use ofthe htmlspecialchars() function, but that’s a topic for another day.

~A!

Mama Says $_REQUEST is the Devil

And unlike her embarrassing mistake with the alligators, this time Mama is right.

To those unfamiliar, PHP makes available something called super global arrays that allow you to access various things, server properties ($_SERVER), cookies ($_COOKIE), post and get values ($_POST, $_GET), etc.

When you submit a page that looks like this:

http://localhost/foo.php?key=value

Your variable is available in the $_GET superglobal array. You can access it with $_GET['key']

Likewise, when you submit a form via post, you can get the form values from $_POST the same way.

$_REQUEST, however, is the grandaddy of them all, allowing you to access all of the POST, GET, and COOKIE values from one array. How convenient, right? How very courteous, to make an array I can grab anything from at any time I want. Lovely, right?

Wrong. Really wrong. Really, really, really wrong. $_REQUEST is the same thing as using register_globals to handle GET and POST. It allows anything and everything you have to be hacked given very little knowledge of your actual application internals.

For example: Let’s say you have a web application with a front-end and an administration panel. You only want people with admin rights to be able to access the admin panel, most likely, so you build yourself a little login panel, and a form, which posts to a script the variables username and password. Those are then checked against the database, and boom, you’re in business, knowing who to authorize and who not to.

That code would look something like this:

$username = $_POST['username'];
$password = $_POST['password'];

$result = mysql_query(”select id from admin where username=’$username’ and password=’$password’”);

if (mysql_num_rows($result))
{
$_SESSION['admin_access'] = TRUE;
$_SESSION['admin_id'] = mysql_result($result, 0, “id”);

}

(The code above is far over-simplified and only used as an example. I recommend error checking, good connection management, and database framework classes. Don’t code like this.)

Now then, the problem with using $_REQUEST['username'] instead of $_POST['username'] in the example above is this: I can hack you in 2/10s of a heartbeat. Literally. Let’s call this script “login_check.php” for giggles. Hitting the following URL would compromise access to your administration panel:

logincheck.php?username=foo’%20or%20true%20–

Because you’re using $_REQUEST instead of the right array, username is going to be populated with the value I entered in the url, not what you thought it was going to be populated with. So, the query you thought you were executing now looks like this:

mysql_query(”select id from admin where username= ‘foo’ or true –’ …);

And since MySQL sees everything after the two dashes as a comment, guess what? That query will ALWAYS return records, meaning that hitting it with that url will always log someone in as an administrator.

It’s called SQL injection, and if you’re using $_REQUEST or register_globals=On, you’re asking for it to happen. Begging for it, even.

I could go on and on, but if you read this far into the piece, you care enough about your code and your professional reputation not to use $_REQUEST or register globals. And if you don’t, you may never regret it, and someone will come hire me to clean up your mess later. Fine by me.

~A!

Sopranos: Road to Respect (PS2)

I was a late comer to the whole Sopranos obsession. I have always enjoyed movies like Goodfellas, the Godfather series, Scarface, all of those. The best mob/gangland movie I’ve seen lately was The Departed, with Jack Nicholson, DiCaprio, and the rest.

I got my first taste of the Sopranos from a friend in Vegas when I lived there, and fell right in love with the show, albeit at the very end of the fifth season. I watched the sixth season of the Sopranos in its entirety.
So, when I heard there was a video game coming out for the PS2 entitled “The Sopranos: Road to Respect” I was psyched. So, as soon as there was a copy available over at Blockbuster Video, I snapped it up, brought it home, and started fantasizing about all the cool and nifty things they would do with a game based on an award winning HBO series.

I really should have known better. TV Series games, most movie games, they just kind of.. well… they suck. Sopranos was an exception to the rule because it sucked more. I’ll explain.

In Sopranos: RTR, you play Joey LaRocca, son of the notorious rat “Big Pussy” LaRocca (the guy they shot and threw off the back of a boat a season or two ago, I never saw that episode.) In the opening scene, we see Joey smash a car window and steal an old woman’s purse, and Tony Soprano knocks him over and drags him into the pork store to give him a good talking to, then offers him some work.

From there, you go on missions to do various things, one of the first of which is to dump a body in the harbor (after slamming his head into a urinal and accidentally killing him, of course.). The plot lines are egregious and over the top, but that’s a mob movie/show/game all over, so that’s not only acceptable, but a good thing.

The dialog interface allows you to choose three different versions of saying the same thing in a conversation. You can select “Tough”, “Neutral”, and “Smooth”. This could have been a very cool feature, except for the fact that you have until the other person in the conversation is done speaking to choose your response type, or Neutral is automatically selected. This is prohibitively annoying, because as any RPG player knows, sometimes you need to think about your actions in a game to get the most out of them, and this game forces you to rush through the process and really detracts from the experience.

The actual game play when you’re not watching cut-scenes (which are the best part of this travesty of a game) is composed mostly of punching people in various ways to intimidate them or knock them cold. There are no puzzles, your role-playing in your responses doesn’t seem to affect much, and all you do is beat people up through various stages that are so linear you absolutely can not go the wrong way, ever.

And for a game entirely composed of third-person combat, the combat system sucks like a hoover with a hyperdrive. The controls are awkward, and more often than not the opponents just grab you and force you to the ground. I found the best way to win a fight with more than one opponent was to let them get me down on the ground, push the square button until I rolled them over and punch them into unconsciousness. If more than one opponent is on you at a time standing up, they just pummel you into oblivion. You’re dazed after taking a hit, and the other guys beats you up, dazing you some more, then the first guy goes at it again…. and so on.

You can pick up various weapons and use the environment to your advantage, which was the only cool thing about the combat system. Everything from a filing cabinet (slamming their head in it repeatedly), to a table saw is hanging around in various stages, just waiting to be used to disable or kill your opponents.

When you’re not fighting, you’re wandering around looking for loot to pick up off desks, tables, magazine stands, and the like. Each piece of loot you pick up adds some money to your character’s balance, but the only thing you can buy in the game is tributes for Paulie, your captain in the game. You can pay a tribute to Paulie to refill your respect meter, which appears to go down for no reason whatsoever.

The respect system. Ah, how I expected something more. I expected something a little more akin to BioWare’s Knights of the Old Republic series, where you can affect your destiny and character by the choices you make in the game. Not a chance in this one, you’re responses aren’t really yours to choose, and they don’t affect the outcome of the game unless you lose enough respect to get whacked.

I got whacked once in the game, when I shot someone at a bachelor party because I was tired of the combat system and just wanted to end the fight. Immediately, without warning, a cut scene started with my character begging not to get it in the eyes and being blown off the back of a boat by Tony and Paulie a la Big Pussy’s fate. No warning, no anything except an immediate cut scene and game over.
I stuck with it, hoping against hope it would get better, and then about four hours into the game play, it was over. I had beaten the game after a long mission on the docks to kill a rival gang. Suddenly your character is a made man, the game is over, and you’re left with this sinking feeling that there are still six days left to the rental, and the game has all the replay value of pong.

There were some good things, too. They used the cast from the Sopranos for the voices, and they did a great job of making the dialog you hear fun and profane as all get-out. I haven’t heard the F-word that much in anything except the original series, ever. Definitely, definitely definitely not a game to have anyone under 18 in the room with you while you’re playing.

With the short playing time, the absolutely horrible combat system, and the half-assed attempt at RPG elements, this game is really one of the worst I have played since Star Wars: Revenge of the Sith for the PS2.

Rent it if you must indulge your obsession with the Sopranos, but don’t expect much, and definitely do not buy it.

If I was giving out stars, this game would get a 1 star rating, and even then only because the plot was fun to listen to, and I love hearing James Gandolfini talk.
~A!

WordPress Themes