查询仅返回我的PHP表中的1行数据

时间:2019-03-30 13:07:04

标签: php mysql database mysqli

我建立了一个查询,该查询在MySQL应用中运行时会显示所有预期结果。但是,当我在PHP代码中循环浏览时,结果只显示一行。

无论我如何处理SQL代码,它仍然会在我的MySQL应用程序中显示所有结果,但是由于某种原因,我的PHP代码中的某些内容导致了该问题,因此无法解决。

最后,尽管它显示了一行结果,但仍然出现错误

  

PHP警告:mysqli_fetch_assoc()期望参数1为mysqli_result,在第144行“ ..中给出的字符串。错误。

我的查询在下面,其中$tID获取URL变量ID

    SELECT *

    FROM tbl_test_results tr

    LEFT JOIN tbl_test_ordered tor
    ON tr.testorderedID = tor.testorderedID

    LEFT JOIN tbl_test t
    ON tr.testID = t.testID

    WHERE tor.testorderedID = '$tID'

    ORDER BY t.test_name ASC

我的代码:

<!DOCTYPE html>
<html dir="ltr">
<head>
<?php include($_SERVER['DOCUMENT_ROOT'].'/gezond/includes/header_2019.php'); ?>    
<title>gezond | cronkflies.com</title>

    <style>
    .tablesorter-pager .btn-group-sm .btn {
      font-size: 1.2em; /* make pager arrows more visible */
    }
    </style>

    <script type="text/javascript">
        $(function() {

          $("table").tablesorter({
            theme : "bootstrap",

            widthFixed: true,

            // widget code contained in the jquery.tablesorter.widgets.js file
            // use the zebra stripe widget if you plan on hiding any rows (filter widget)
            // the uitheme widget is NOT REQUIRED!
            widgets : [ "filter", "columns", "zebra" ],

            widgetOptions : {
              // using the default zebra striping class name, so it actually isn't included in the theme variable above
              // this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden
              zebra : ["even", "odd"],

              // class names added to columns when sorted
              columns: [ "primary", "secondary", "tertiary" ],

              // reset filters button
              filter_reset : ".reset",

              // extra css class name (string or array) added to the filter element (input or select)
              filter_cssFilter: [
                'form-control',
                'form-control',
                'form-control',  // select needs custom class names :(
                'form-control',
                'form-control',
                'form-control'
              ]

            }
          })
          .tablesorterPager({

            // target the pager markup - see the HTML block below
            container: $(".ts-pager"),

            // target the pager page select dropdown - choose a page
            cssGoto  : ".pagenum",

            // remove rows from the table to speed up the sort of large tables.
            // setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
            removeRows: false,

            // output string - default is '{page}/{totalPages}';
            // possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
            output: '{startRow} - {endRow} / {filteredRows} ({totalRows})'

          });

        });
    </script>

</head>

<body class="stretched">

<section id="content">
    <div class="content-wrap">
    <!-- <div class="section bottommargin-lg header-stick">

    </div>-->

<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div class="page-header">

            </div>


  <?php
    if (!defined('DB_SERVER')) define('DB_SERVER', 'localhost');
    if (!defined('DB_USER')) define('DB_USER', 'xxx');
    if (!defined('DB_PASSWORD')) define('DB_PASSWORD', 'xxx');
    if (!defined('DB_TABLE')) define('DB_TABLE', 'xxx');

    // The procedural way
    $mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
    $mysqli->set_charset("utf8");
    $mysqli->query("SET NAMES 'utf8'");

    if (mysqli_connect_errno($mysqli)) {
        trigger_error('Database connection failed: '  . mysqli_connect_error(), E_USER_ERROR);
    }

    if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
            die("Invalid ID specified.");} 
        else {
            $tID = mysqli_real_escape_string($mysqli, $_GET['id']); 
        }

    $query = "
        SELECT *

        FROM tbl_test_results tr

        LEFT JOIN tbl_test_ordered tor
        ON tr.testorderedID = tor.testorderedID

        LEFT JOIN tbl_test t
        ON tr.testID = t.testID

        WHERE tor.testorderedID = '$tID'

        ORDER BY t.test_name ASC    ";

    $result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

    echo "
    <table id='table_vluchten' class='table-bootstrap table-sm table-bordered table-striped' width='100%'>";
    echo "<thead class='thead-inverse'>";
    echo "<tr>";
    echo "<th class='filter-false' data-sorter='false'>&nbsp;</th>
        <th ><div align='left'>Test</div></th>
        <th ><div align='left'>Result</div></th>
        <th ><div align='left'>Units</div></th>
        <th ><div align='left'>Low</div></th>
        <th ><div align='left'>High</div></th>";
    echo "</tr>";
    echo "</thead>";

    echo "<tbody>";

    if($result) {
        while($row = mysqli_fetch_assoc($result)) {

        $test = $row['test_name'];

        if(!isset($row['test_result'])) {
                $result = $row['test_result_t'];
            } else {
                $result = $row['test_result'];
            }

        $low = $row['test_low'];
        $high = $row['test_high'];
        $units = $row['test_unit'];

    echo "<tr >";
    echo "<td style='width:50px;'><span style='font-size:14px;text-align: center;'><i class='fas fa-list-ul'></i></span></td>";
    echo "<td style='width:200px'><span style='font-size:14px'>" .$test. "</span></td>";
    echo "<td style='width:100px'><span style='font-size:14px'>" .$result. "</span></td>";
    echo "<td style='width:100px'><span style='font-size:14px'>" .$units. "</span></td>";
    echo "<td style='width:100px'><span style='font-size:14px'>" .$low. "</span></td>";
    echo "<td style='width:100px'><span style='font-size:14px'>" .$high. "</span></td>";
    echo "</tr>"; 


      }
    echo "</tbody>";
    echo "</table>";

        }

    mysqli_close($mysqli);

    ?>  


                    </div>
                </div>
            </div>

</div>
</section>


<script>
$(document).ready(function(){
  $('[data-toggle="tooltip"]').tooltip();   
});
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的代码混乱。您正在混合很多过程样式和面向对象样式:

int main()
{
int i, score = 1, n;
float sum = 0.0, average;  //<-------------changed to float

for(i=0; score>0; i++)
{
    printf("Enter score (4-10) :");
    scanf("%d", &score);
    if(score>0){ 
            sum = sum + score;
    }
    else{
       break;
    }
}



 printf("You entered %d scores.\n", i);
 average = sum / i;
 printf("The average is: %f", average); //<--- changed to %f you can use &.2f to print 2 digits after . 

 return 0;
}

我建议选择一种或另一种,但不要一直混在一起。

但是@Qirel是您所要解决的特定问题的答案,那就是在此处重命名变量:

...
$mysqli->set_charset(...     <-- object oriented style
$mysqli->query(...           <-- object oriented style
if (mysqli_connect_errno(... <-- procedural style
mysqli_connect_error(...     <-- procedural style