Jump to content
MakeWebGames

Best way to write this?


Recommended Posts

Just wondering what would be the best way to write this? The only thing the query is calling is the (username) nothing else.

Option #1 By far the easiest so I don't think it's the best.

$chas=$db->query("SELECT * FROM `users` WHERE `userid`={$lol['userid']}");
while($bill=$db->fetch_row($chas))

 

Option #2

$chas=$db->query("SELECT `username` FROM `users` WHERE `userid`={$lol['userid']}");
while($bill=$db->fetch_row($chas))

 

Now I have been starting to use this kind of stuff alot more....Is this even right?

$do = sprintf("UPDATE `users` SET `money`='%s' WHERE `userid`='%s' ",
         mysql_real_escape_string(50000),
         mysql_real_escape_string($userid));

                  mysql_query($do);

 

I have read on this at php.net...still confussed. I thought at first that the %s made a difference that there was a different varible to use on numbers or text...but it works both ways, this is why I think I am doing it wrong....Cause if the %s lets it go though both ways.....how is it different from say

$amt=5000;
$db->query("UPDATE `users` SET `money`=($amt) WHERE `userid`=$userid");

I'm sure there is a diffence I just don't know what it is...I really appreciate any help you can give...Just to let you know I'm not really good at reading for hours on end to learn something. But if I see it then I know it..So please don't call me stupid and point me straight back to the php manual...Please give me an example. One small one. Nothing Big. I can figure out from there but with your example I can learn faster and better than reading on any site.. Also I want to learn about the GET & POST so example on that would be nice. I ahve seen some so really on that not that big of a deal But what I have see where really long Functions....Do you have to put that above EVERY (POST and GET)?

And only one more question for now :-D

Can you use the mysql_real_escape_string on say a query that you are doing a count on or say one like my Options 1 and 2 where it has to fetch_row?

For example would something like this be possible...this Don't work have tried, lol.

$cnt = sprintf("SELECT COUNT(*) as cnt FROM `users` WHERE '%s' > unix_timestamp()-200*720 ",
         mysql_real_escape_string(laston));
while($ct=db->fetch_row($cnt))
print " blah blah";

Also have tried

$cnt = sprintf("SELECT COUNT(*) as cnt FROM `users` WHERE '%s' > unix_timestamp()-200*720 ",
         mysql_real_escape_string(laston));
while($ct=mysql_fetch_row($cnt))
print " blah blah";

 

Both just give me errors...can't remeber them though...So any help would be greatly appreciated. 8-)

Link to comment
Share on other sites

Re: Best way to write this?

Kudos! You're exploring new territory. Keep it up ;)

 

 

Just wondering what would be the best way to write this? The only thing the query is calling is the (username) nothing else.

Option #1 By far the easiest so I don't think it's the best.

$chas=$db->query("SELECT * FROM `users` WHERE `userid`={$lol['userid']}");
while($bill=$db->fetch_row($chas))

Option #2

$chas=$db->query("SELECT `username` FROM `users` WHERE `userid`={$lol['userid']}");
while($bill=$db->fetch_row($chas))

 

The second one is definitely the better one. About the only thing you could do is add in a "limit 1" since you most likely only want one row there.

 

Now I have been starting to use this kind of stuff alot more....Is this even right?
$do = sprintf("UPDATE `users` SET `money`='%s' WHERE `userid`='%s' ",
         mysql_real_escape_string(50000),
         mysql_real_escape_string($userid));

                  mysql_query($do);

Yes, and no. mysql real escape will protect you from injections, but the better way here, is to use the %d (or as nyna does, %u) to format as an integer. %u does not carry over a negative sign, if there is one, %d will allow negative numbers. If you cast the variable as an integer, you are that much more precise, and you save processing power. But over all, yes you *could* do it that way.

 

And only one more question for now :-D

Can you use the mysql_real_escape_string on say a query that you are doing a count on or say one like my Options 1 and 2 where it has to fetch_row?

For example would something like this be possible...this Don't work have tried, lol.

$cnt = sprintf("SELECT COUNT(*) as cnt FROM `users` WHERE '%s' > unix_timestamp()-200*720 ",
         mysql_real_escape_string(laston));
while($ct=db->fetch_row($cnt))
print " blah blah";

 

In this situation, remember that %s does no need quotes around it. You put in the quotes earlier because of how the mysql syntax works. Here you would use the back tick. You also did not have the string that is the argument in the mysql escaping function surounded with quotes (that's a php string so it needs to be surounded by quotes). And lastly, if the string is hard coded, i.e., permanent, why not just put the string in the query? Perhaps this is simply for the sake of testing, seeing what can be done. In which case, that's cool.

 

$cnt = sprintf("SELECT COUNT(*) as cnt FROM `users` WHERE `%s` > unix_timestamp()-200*720 ",
         mysql_real_escape_string('laston'));
while($ct=db->fetch_row($cnt))
print " blah blah";
Link to comment
Share on other sites

Re: Best way to write this?

Cool see I'm learning already :-D

So %u is the best to use since no Negitive correct? So this would be better?

$do = sprintf("UPDATE `users` SET `money`='%u' WHERE `userid`='%u' ",
         mysql_real_escape_string(50000),
         mysql_real_escape_string($userid));

                  mysql_query($do);

and that will keep them from using a negative entry....well guess that don't matter though I blocked that competley from my site, lol..But I need to know..I like learning.

So is that the right way? ^^^^ If not please tell me, lol.

Now you said the the string is hard coded (not sure what that means) So does that mean that this would be ok? And safe?

$william=$db->query("SELECT COUNT(*) as cnt FROM `users` WHERE `laston` > unix_timestamp()-200*720");
while($raye=$db->fetch_row($william))
print "blah blah";

 

I think my biggest thing is knowing where to use certain things. Liek the mysql_escape..where do I need to use that and where can I use a normal entry like

$db-query("");

I guess knowing that is the trick, lol.

Oh and the Post and Gets...any tips on that?

Link to comment
Share on other sites

Re: Best way to write this?

One could right a book on the topic of passing variables in the URL in the POST header.

The first query you have there, dosn't need those escaping functions since you're casting the variable to an integer. You can't inject database code into a database if your input has been cast to an integer. so, the %u, with no escape, and escape if you are putting in a string.

On the second on, that's exactly what you should do. hard coded: it's permanent. the opposite would be user submited data since that's always changing.

Link to comment
Share on other sites

Re: Best way to write this?

 

One could right a book on the topic of passing variables in the URL in the POST header.

The first query you have there, dosn't need those escaping functions since you're casting the variable to an integer. You can't inject database code into a database if your input has been cast to an integer. so, the %u, with no escape, and escape if you are putting in a string.

Sorry that part lost me....so do i even need it like that? or are you saying the %s is all i need not the %u or are they the same difference?

or do you mean that i can use

$db->query("UPDATE `users` SET `money`=50000 WHERE `userid`=$userid"):

 

would that be the same as the

 

$do = sprintf("UPDATE `users` SET `money`='%u' WHERE `userid`='%u' ",
         mysql_real_escape_string(50000),
         mysql_real_escape_string($userid));

                  mysql_query($do);

 

Or defenty use the last one? For sakes of security I want to be secure as I can be and learn to write the cleanest and easiest to read code I can :wink:

Link to comment
Share on other sites

Re: Best way to write this?

 

$do = sprintf("UPDATE `users` SET `money`='%u' WHERE `userid`='%u' ", 50000, $userid);
mysql_query($do);

 

The sprintf function takes the "arguments", that is the stuff at the end, and formats them the way you specify in the string at the beginning.

%u and %d format the argument as an integer, and that makes escaping that argument unnescessary.

If you use %s, then that argument would likely need to be escaped.

Link to comment
Share on other sites

Re: Best way to write this?

OH I think i get it now..if I use the %u i don't need to use the mysql_real_escape_string

If I use the %s then I need to use it.....

What would you recommend to be the bettter of the 2? I have used the %s more so I am more familiar with it. Should I just stick with it?

Though the %u looks easier......and faster...so they pretty much do same? If so I will start using the %u its alot cleaner.

I guess the real question is, is there a difference in the speeds the query will run? Cause the %u looks like it will run faster....

Now would this work here since it has text and not just numbers?

 

$do = sprintf("UPDATE `users` SET `money`='%u' WHERE `username`='%u' ", 50000, {$ir['username']});

 

This is just an example of course, lol...

And when you add to the money say like would this be how its done?

 

$do = sprintf("UPDATE `users` SET `money`=`money`+'%u' WHERE `username`='%u' ", 50000, {$ir['username']});

 

Or

 

$do = sprintf("UPDATE `users` SET `money`='%u' WHERE `username`='%u' ", money+50000, {$ir['username']});

 

Sorry for the million questions but I really am learning alot right now. And your help is a lot more appreciated than you can believe

Link to comment
Share on other sites

Re: Best way to write this?

php will parse formatting a variable as a integer faster than it will parse escaping a string and then formatting it as a string.

And yup, you got it ;) I'd recommend formatting in a format that is closest to the expected format you want. If you only want a number, then format it as a number. ;)

The query itself, once php is done parsing it, it doesn't matter if you escaped a number, or if you formatted it as a number, mysql will run that query at the same speed.

Link to comment
Share on other sites

Re: Best way to write this?

What about something like this?

 

$refill = sprintf("UPDATE `users` SET `energy`='%u' WHERE `userid`='%u' ", maxenergy, $userid);
$refill2 = sprintf("UPDATE `users` SET `crystals`=`crystals`-'%u' WHERE `userid`='%u' ", $set['ct_refillprice'], $userid);
mysql_query($refill);
mysql_query($refill2);

 

No errors BUT does not update the users energy to max....does take the crystals though...

I did do this and made it work...but I know there is probalry a better way to this.

 

$maxenergy=$ir['maxenergy'];
$refill = sprintf("UPDATE `users` SET `energy`='%u' WHERE `userid`='%u' ", $maxenergy, $userid);
$refill2 = sprintf("UPDATE `users` SET `crystals`=`crystals`-'%u' WHERE `userid`='%u' ", $set['ct_refillprice'], $userid);
mysql_query($refill);
mysql_query($refill2);
Link to comment
Share on other sites

Re: Best way to write this?

I think he was thinking he could reference a table column from the sprintf argument section.

This represents a fundamental error in how you see the sprintf function working.

 

sprintf(" QUERY STRING HERE ", ARGUMENTS HERE );

The argument section, is formated, and the string portion has the arguments inserted into it. You can't reference a column directly from the arguments section, because php combines that into the string.

IN other words, the ARGUMENTS part, is not interpreted by MySQL.

That sprintf only returns the; QUERY STRING HERE part.

so

if you do

sprintf("QUERY STRING", maxenergy);

maxenergy is interepreted by php as a constant, that is undefined (or else it could be defined, but it wouldn't hold the value of maxenergy in the users table)

this constant, if it doesn't hold a value, is asigned the value: null

so

sprintf("QUERY STRING", null);

This is equivalent to the last sprintf deal.

 

sprintf("QUERY maxenergy STRING", $userid);

maxenergy MUST be inside the string, as it's intended to reference a table column directely

You could do:

sprintf("QUERY %s STRING", 'maxenergy');

as you can see maxenergy is surrounded by quotes, so now it's a string and not a constant.

Link to comment
Share on other sites

New Question

This one is a short one, lol....

Ok, on my game i have made some functions that i can call up by using

 

$h->whatever();

 

That works Great. No complaints...But I was thinking that I could just include instead since thats all that function is really doing...

Like the endpage function really is just including a table close and you could make a page called endpage and put at the bottom of each page

include "endpage.php";

Well that is kinda my question, Is there a differernce in page loading speeds? Should I use the Function or should I use the include...

$h->whatever();

Does the exact same as

include "whatever.php";

Do you think there would be a speed difference....Yes they load images..If that makes a difference.

Link to comment
Share on other sites

Re: Best way to write this?

I think any speed difference would be negligible.

Okay, I've given my answer to your question, now for unsolicited advice lol

Your assumption that calling a "method" is the essentially the same as including a file with the code in that method is in error.

Yes, it's a minor technical thing, but it's something worth thinking about as this will lead to a proper understanding of when and why to use one or the other.

First, the thing you refer to "$h" is an object. This object is defined in the header.php file. The name of the class is "Header".

When you use a class, you store it in a variable whose type is object. This is opposed to having a variable whose type is integer, float, string and so on.

So a variable can be a string, an integer, or an object amount others.

Now, within the Header class, you have "methods". This is what you refer to as "functions".

The idea behind using classes is that you can take an Object Oriented approach to Programming. OOP for short

OOP is where certain tasks are grouped into classes. A database connection is a perfect example of a class. Another typical class you will run across is a BBCode class.

Now, you wouldn't add in a method to the BBcode class for calculating the average of an array's values. Doing so has absolutely nothing to do with BBcode.

(Note: I'm not saying you are in violation of any of these concepts, but instead I'm laying them out for you so that you can see that the question of how fast something executes is not the reason why you would or wouldn't use a class. And it's not a reason for why you would or wouldn't add a method to a class either.)

Therefore, we come to the conclusion that if the task you wish to perform makes sense to be grouped with the class you are thinking of putting that bit of code into, then by all means do so. If it doesn't, then na, don't put it in there.

Now, that we've covered that, let's consider the question of variable scope. If you simply make a file, with no functions in it, and no classes, and then you include said file in another script, every variable in that script you just included is going to "exist" in the same scope as the script it is included into. However, if you put said code into a method, and then called that method, the variables in that method are NOT in the same scope as the script that method is called in. The variables will remain in that method's scope. If your class has any attributes, then those attributes would be available to all methods in the class by default. So class attributes have a scope that spans all of the methods in the class.

Okay, I've spewed enough jibber jabber. But like I said, the question of how fast using a class is, is really a minor concern when the power of a class and the useability of a class can make your code better (especially if the code is something more than one person works on because it compartmentalizes the code)

 

The last thing I'll say is, you'll get more mileage out of optimizing the code in your classes, functions, includes, and scripts rather than trying to figure out if your code runs faster in a class, function, Include or otherwise.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...