Forum Moderators: open

Message Too Old, No Replies

Why am I create a PHP variable for the query string again?

         

csdude55

9:03 pm on Jan 15, 2024 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Back in the day, somewhere along the line I picked up the belief that I needed to write queries in PHP like this:

$query = sprintf("SELECT * FROM table WHERE id = %d",
$id);

$results = mysqli_query($dbh, $query);

or something like that; I just typed this for the post, so please forgive any typos.

What I can't figure is, why am I creating that $query variable at all? Isn't that just an unnecessary use of memory?

How is it different from:

$results = mysqli_query($dbh,
sprintf("SELECT * FROM table WHERE id = %d",
$id)
);

phranque

1:19 am on Jan 16, 2024 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



the difference in memory usage is negligible.
if you are reusing or further manipulating the query string, it makes sense to use a variable.
more importantly it's a matter of readability and maintainability so i would use what works best for you in that sense.

csdude55

4:51 am on Jan 16, 2024 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



For some reason I had it in my head that there's a security purpose, but I can't imagine what it was. Using sprintf() makes sense, of course, so maybe that's what I was remembering?

I think it's one of those things where I learned a technique that I didn't fully understand, and then it just got stuck in my head as "the right way". So 20 years later, I'm doing that same technique out of habit! LOL

I've been accused of micro-optimizing, and that's true! But all of my little trims and tweaks have added up, and that results in more pages per session, so in the end it's worth my time to focus on little things like this. Not using the unnecessary variable takes slightly less code, and slightly less memory usage, so if I can speed up every page by a few microseconds then why not? :-)