sdfgg45
sdfgg45

Reputation: 1242

How to optimize nested query with PHP and MySqli?

I have this code, that fetches data from two tables in MySQLi. It first has to get the title, description, status and project_id from table 1, and then get the name from table 2 using the id from table 1.

Is there a better/faster way to do this? I have about 600 rows in the tables, and it takes about 5 sec to run this query. I will also add that this example is a bit simplified, so please don't comment on the db-structure.

<?php
$results = $connect()->db_connection->query(
    'SELECT title, description, status, project_id 
     FROM table 
     WHERE created_by ='.$user_id
);

if ($results) {
    while ($result = $results->fetch_object()) {
        $res = $connect()->db_connection->query(
            "SELECT name FROM projects WHERE id = ".$result->project_id
        );
        if ($res) {
             while ($r = $res->fetch_object()) { 
                echo $r->name;      
            }   
        }
     echo $result->title; 
     echo $result->status; 
    }
}     
?>

Upvotes: 0

Views: 657

Answers (3)

n-dru
n-dru

Reputation: 9420

You can use JOIN on project_id:

$results = $connect()->db_connection->query('SELECT t.title title,t.description,t.status status,t.project_id, p.name name FROM `table` t JOIN projects p ON p.id= t.project_id WHERE t.created_by ='.$user_id);
if($results){
   while($result = $results->fetch_object()){
        echo $result->name;
        echo $result->title; 
        echo $result->status; 

    }
} 

tables have aliases here - t for table and p for projects.

Also to make it faster, add index to project_id in table table, if you haven't done it yet:

$connect()->db_connection->query('ALTER TABLE `table` ADD INDEX `product_id`');

Upvotes: 0

Michal_Szulc
Michal_Szulc

Reputation: 4177

Try to use JOIN in your query.

You can find examples and description of this command here: http://www.w3schools.com/sql/sql_join.asp

Check out also this infographics: http://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_orig.jpg

Upvotes: 1

harry
harry

Reputation: 1007

Use Query:
    SELECT title,description,status,project_id 
    FROM table tb
    inner join projects pr on pr.id = tb.project_id
    WHERE created_by = $user_id

Upvotes: 1

Related Questions