在PHP中显示SQL查询结果时出错

在PHP中显示SQL查询结果时出错,php,mysql,sql,arrays,Php,Mysql,Sql,Arrays,当我试图在“php”中检索sql查询的结果时,它没有正确显示 我的结果是: Array ( [0] => 0533 [SUBSTRING(cardnumber, 5, 4)] => 0533 ) 而我只是想得到这样的结果 0533 待展示 我的php文件: <?php $con=mysqli_connect("localhost","root","wickedphat", "bluecard"); // Check connection if (m



当我试图在“php”中检索sql查询的结果时,它没有正确显示

我的结果是:

Array ( [0] => 0533 [SUBSTRING(cardnumber, 5, 4)] => 0533 )
而我只是想得到这样的结果

0533 
待展示

我的php文件:

<?php
    $con=mysqli_connect("localhost","root","wickedphat", "bluecard");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $result = mysqli_query($con,"SELECT SUBSTRING(cardnumber, 5, 4) FROM users WHERE username='".($_SESSION['username'])."'");

    while($row = mysqli_fetch_array($result))
      {
      print_r($row) . " " ;
      }

    mysqli_close($con);
    ?>

这些结果是正确的,并且与您提供的代码相符。有两点需要注意:

  • 您应该为MySQL函数调用的结果提供一个别名,以便通过PHP更轻松地访问它
  • 您需要在PHP中引用每个结果的标识符,而不是整个结果行
  • 这应表明:

    // Gave the result of SUBSTRING(cardnumber, 5, 4) the alias
    // of "cardnum"
    $result = mysqli_query($con,"SELECT SUBSTRING(cardnumber, 5, 4) as cardnum FROM users WHERE username='".($_SESSION['username'])."'");
    
    while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
    {
        // accessing the value of cardnum by refering to its key in the
        // the array returned by mysqli_fetch_array()
        echo $row['cardnum'] . ' ';
    }
    

    我相信,如果需要(奇怪的)关联数组键,您需要mysqli\u fetch\u assoc()

    // Gave the result of SUBSTRING(cardnumber, 5, 4) the alias
    // of "cardnum"
    $result = mysqli_query($con,"SELECT SUBSTRING(cardnumber, 5, 4) as cardnum FROM users WHERE username='".($_SESSION['username'])."'");
    
    while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
    {
        // accessing the value of cardnum by refering to its key in the
        // the array returned by mysqli_fetch_array()
        echo $row['cardnum'] . ' ';
    }