Bc1151 Bc1151 - 6 months ago 14
PHP Question

PHP/SQL, Reduce number of queries

I am querying a large db in php, and I am not doing it near well enough.
I have the code I need, I simple cannot find a good way to compact these statements.

$q = $_GET['q'];
(dbinit)
$query = "SELECT post_id FROM wp_postmeta WHERE meta_key = '_billing_email' AND meta_value = '$q'";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result))
{
$thing = $row['post_id'];
$querys = "SELECT 'meta_value' FROM wp_postmeta WHERE post_id = '$thing' AND meta_key = '_order_number'";
$results = mysql_query($querys);
$rows = mysql_fetch_array($results);
$postid = $rows['meta_value'];
$queryss = "SELECT post_id FROM $table WHERE meta_value = $postid AND meta_key = '_order_number'";
$resultss = mysql_query($query);
$rowss = mysql_fetch_array($result);
$order_id = $rowss['post_id'];
(handling)
}


I am wondering if there is a more efficient way to do these queries, or perhaps have them in one query?

Answer

Not sure where $table comes from.

But this JOIN attempt should work:

$q = $_GET['q'];
// ... dbinit ...

$query = "SELECT wpp.post_id,
       wpp1.meta_value as orderNumber,
       wpp2.post_id as orderId

    FROM wp_postmeta wpp
    LEFT JOIN wp_postmeta wpp1 
    ON wpp1.post_id = wpp.post_id 
      AND wpp1.meta_key = '_order_number'
    LEFT JOIN $table wpp2
    ON  wpp2.meta_value = wpp1.meta_value 
      AND wpp2.meta_key = '_order_number'
    WHERE wpp.meta_key = '_billing_email' 
      AND meta_value = '$q'";

$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    (handling)
}

As you can see you can get

$thing = $row['post_id'];
$order_id = $row['orderId'];

inside the loop if needed.

Comments