php and mysql optimization

And again questions about working with mysql and php:

1) There are two requests:

mysql_query('select * from `table` where `id`='.$id.' and `user_id`='.$_SESSION['id']);
mysql_query('select * from `table` where `id`='.$id.' and `user_id`='.$_SESSION['id'].'limit 0, 1');

Primary key – id. Does it make sense to write limit 0, 1 at the end of the query or will it not speed up the query?

2) In case of already received data:

$ar = array();
$res = mysql_query('select * from `table` where `id`<30');
while($ar = mysql_fetch_assoc($res)){}

Which is better to use: mysql_num_rows($res)or sizeof($ar)?

3) Why is mysql_fetch_arrayneeded when there are mysql_fetch_assocand mysql_fetch_row? In theory, these two functions separately work faster?

4) When organizing, for example, blogs, is it reasonable to move blog posts into separate files, and leave comments in the database? Just then it turns out that when displaying the latest blogs, work will be carried out simultaneously with both the database and files, which I don’t like. Moreover, the announcement will still have to be written to the database.

5) Defining global variables in a function is a rather slow thing. Is it possible to speed up the work of the function by driving references to the necessary variables into an array and defining only the new array as global in the function? That is, it was:

function f() {
    global $ar1, $ar2, $ar3;
}

New:

$all = array('ar1' => &$ar1, 'ar2' => &$ar2, 'ar3' => &$ar3);
function f() {
    global $all;
    $ar1 = $all['ar1'];
}

If you are puzzled by the appropriateness of some questions, consider that I am a fan of saving on matches.


Answer 1, authority 100%

1) It makes sense to do this:

mysql_query('select * from `table` where `id`='.$_SESSION['id'].' limit 0,1');

Just exclude * in requests, then there will be savings no longer on matches 🙂

2) Agree with @mozzart

3) mysql_fetch_array is faster than assoc because adds only indices to the array.

4) Agree with @mozzart

5) Rather, it’s faster like this:

function (&$ar1, &$ar2, &$ar3) {
...
}

Example:

class Api {
    private $db;
    public function test() { //      get  post
        $this->db; //  
    }
}

or like this:

class Api extends DB {
    public function test() {
        $this->query();
    }
}
class DB {
    public function query() {
        ...
    }
}

Answer 2, authority 50%

1) There is a meaning

2) If you just need to get the number of records, then it is more logical and more optimized to use mysql_num_rows, if all records are received in an array, then of course – sizeof

3) Didn’t check…

4) If file storage implies caching, then yes. Roughly speaking, working with files is much faster than working with a database

5) The first option is faster