dqjl0906
2014-06-05 00:41 浏览 29
已采纳

在PHP中显示SQL查询结果出错[关闭]



When i try to retrieve the results from my sql query within' php it doesn't shows me it right.

My result:

Array ( [0] => 0533 [SUBSTRING(cardnumber, 5, 4)] => 0533 )

While i just try to get the result that is

0533 

to be shown.

My php File:

<?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);
    ?>

and in my html file ive put this, where it suppose to show the result.

<?php include_once '../../includes/number1.php' ?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答 默认 最新

  • 已采纳
    douxianglu4370 douxianglu4370 2014-06-05 00:46

    Those results are correct and expected with the code you provided. Two things to note:

    1. You should give the result of your MySQL function call an alias to make access it via PHP easier
    2. You need to refer to the identifier of each result in PHP, not the whole row of results

    This should demonstrate this:

    // 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'] . ' ';
    }
    
    点赞 评论 复制链接分享
  • dongxu6418 dongxu6418 2014-06-05 00:47

    You want, I believe, mysqli_fetch_assoc() if you want the (strange) associative array key.

    点赞 评论 复制链接分享

相关推荐