Which query would be faster and why? mysql_query("select * from mytable where id=$id"); Code (markup): OR mysql_query('select * from mytable where id='.$id); Code (markup): Thanx
The query is the same... MySQL will return the results from both at the same speed. However PHP will execute the second command faster. If you're trying to optimize you should stay away from "SELECT *" queries. Only SELECT the columns you need.
0.000021, 0.000022, 0.000019 <-- query one, repeated 3 times 0.000017, 0.000017, 0.000017 <-- query two, repeated 3 times The second one is faster by at least 0.000002 seconds (seemingly more like 0.000004 the majority of the time)! It's only a tiny bit quicker, but it's still quicker (These times don't include the time for an actual query, but they still give the same difference in speed whether they actually query or not).
^ This makes no difference. PHP will generate (parse) the string, and THEN pass it to MySQL. So the MySQL speed will be identical...
I (and several other people around the web) have written multiple articles on Optimizing PHP. Here's a link to my most up-to-date article: http://www.sacredgfx.com/show_article.php?id=9 As for why it's faster: PHP searches for Variables in the double quotes: ie: echo("blah blah $blah"); will echo out whatever $blah has in it; and echo('blah blah $blah'); will display the $blah as plain text rather than the variable data. The same applies for mysql_query() and pretty much any other function in PHP. As for how to test speed: the top of my article has a very basic, yet very effective way to benchmark your scripts. Hope this helps. Also: azizny, that's a bad attitude to have; it may not be noticeable right now, but down the line if his site becomes super popular, those loading times start multiplying themselves by the amount of users concurrently loading the page. Also, it's not like he has to jump through loops to optimize it, and proper PHP is all about properly optimizing and using the least amount of code possible.
Well what I did was this: For the first query, I wrote a file containing this, and opened it 3 times. <?php require_once '/home/*username*/php/Benchmark/Timer.php'; // Load PEAR Benchmark $timer =& new Benchmark_Timer(true); $timer->start(); $id = 1; $query = "select * from mytable where id=$id"; unset($id); $timer->stop(); echo ($timer->timeElapsed()); ?> PHP: For the second query, I wrote a file containing this, and opened it 3 times. <?php require_once '/home/*username*/php/Benchmark/Timer.php'; // Load PEAR Benchmark $timer =& new Benchmark_Timer(true); $timer->start(); $id = 1; $query = 'select * from mytable where id='.$id; unset($id); $timer->stop(); echo ($timer->timeElapsed()); ?> PHP: The $timer is done via the Benchmark module of PEAR.
Okay, ya my question should have been phrased as: "Where you testing the speed of the PHP script or the MySQL query?" It was PHP as I suspected, just wasn't sure. Thanks for the clarification.