简体   繁体   中英

Outputting a sub-query

<!DOCTYPE html>
<html>
<?php
// Connecting to SQL server
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "super_athletics";

// Creates connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
} else {
    echo "Connected!";
}
echo "<br>";

// Sums upp all the points recieved by each student for specific school
$myQuery = "SELECT SUM(result_studpoints) AS total FROM result WHERE stud_id IN (SELECT stud_id FROM students WHERE stud_school = 'CCA')";
$result = mysqli_query($myQuery);

mysqli_close($conn);
?>
</html>

The problem I am having with the code above is the fact that I cannot output $myQuery. This is a sub-query that works out the sum of points for a specific school. The sub-query selects all the student id's who go to a specific school from the student table, in this case 'CCA', and uses the id's to sum up the points (which is gained from result table) received, which should give the total of points for the specific school (CCA).

The subquery works well on sql alone but I cannot get it to output with php. I have tried echoing but nothing comes up. This may seem simple but I have not found a solution, please help!

Either the tutorial you followed is woefully incomplete. Or you skipped over a bunch of stuff because you thought it wasn't necessary.

One problem in the code is the call to the mysqli_query function. The first argument to that function should be the connection: $conn .

$result = mysqli_query($conn,"SELECT ... ");
                       ^^^^^^

mysqli_query should evaluate to FALSE when an error has occurred. Otherwise, it will evaluate to TRUE. The code should perform some kind of check, and handle an error. This isn't necessarily the best way to code this:

  if(!$result) {
    die("query execution failed");
  }

Once the code has determined that $result is a handle to a valid resultset, the code can then "fetch" the results. You might want to revisit the tutorial, focusing on the part about retrieving the rows from the resultset. Processing of the rows is usually performed in a loop.

You were missing the connection in mysqli_query and you didn't fetch the data

// Sums upp all the points recieved by each student for specific school
$myQuery = "SELECT SUM(result_studpoints) AS total FROM result WHERE stud_id IN (SELECT stud_id FROM students WHERE stud_school = 'CCA')";
$result = mysqli_query( $conn, $myQuery);
$data = mysqli_fetch_assoc( $result );
echo $data[ 'total' ];
mysqli_close($conn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM