Travis
Travis

Reputation: 253

How to execute multiple select queries in a single query and still retrieve the values

So I have a bunch of these in my php script:

//get current values to add to new ones
    $sql = "SELECT `pageViews` FROM $table WHERE `appName` = '$appName'";
    $result = mysql_query($sql);
    if (!$result) {
     die("Invalid query: " .mysql_error());
    }
    $totalPoints += mysql_result($result, 0, 0);


    //get current values to add to new ones
    $sql = "SELECT `appTime` FROM $table WHERE `appName` = '$appName'";
    $result = mysql_query($sql);
    if (!$result) {
     die("Invalid query: " .mysql_error());
    }
    $appRunTime += mysql_result($result, 0, 0);

    //get current values to add to new ones
    $sql = "SELECT `soundsPlayed` FROM $table WHERE `appName` = '$appName'";
    $result = mysql_query($sql);
    if (!$result) {
     die("Invalid query: " .mysql_error());
    }
    $lifesLost += mysql_result($result, 0, 0);

Is it possible to combine all those queries into one and still retrieve each individual information, ie setting them to a variable?

Thanks.

Upvotes: 0

Views: 139

Answers (1)

peterm
peterm

Reputation: 92785

Are you looking for something like this?

$sql = "SELECT pageViews, appTime, soundsPlayed 
          FROM $table 
         WHERE appName = '$appName'";

$result = mysql_query($sql);
if (!$result) {
 die("Invalid query: " .mysql_error());
}
if ($row = mysql_fetch_assoc($result)) {
    $totalPoints += $row['pageViews'];
    $appRunTime  += $row['appTime'];
    $lifesLost   += $row['soundsPlayed'];
}

On a side note: instead of interpolating query strings use prepared statements with either mysqli_* or PDO

Upvotes: 1

Related Questions