只有一个数据从数据库中获取如何显示所有数据特定的一个id

时间:2017-01-30 08:50:38

标签: php mysqli

只从数据库中提取一个数据行。如何显示从SELECT返回的所有数据。 SELECT应该返回多行,因为查询中的id是外键,可以返回一个或多个结果

<?php
   session_start();
    $r  = $_SESSION["v_id"];
    $p = implode($r);

   $servername = "localhost";
   $username = "root";
   $password = "";
   $dbname = "student";

    $db = new mysqli($servername, $username, $password, $dbname);

    $query = "SELECT s_name, code FROM sponser where v_id = '$p'";
    $result = mysqli_query($db,$query);
    $row = mysqli_fetch_array($result);

    $count = mysqli_num_rows($result);

   // fetch the all data to the database where id is v_id
   if($count > 0 ) {
       while ($row) {
           printf ("s_name: %s  code: %s", $row["s_name"], $row["code"]);
           break;
       }
  }
  ?>

2 个答案:

答案 0 :(得分:0)

$query = "SELECT * FROM sponser where v_id = '$p'";
$result = mysqli_query($db,$query);
while($row = mysqli_fetch_assoc($result)) {
       //do code
}

答案 1 :(得分:0)

通过在进入while循环之前调用fetch,你丢弃了结果集的第一行。

一次一个地从结果集中提取行,在这样的while循环中。

<?php
session_start();
$r  = $_SESSION["v_id"];
$p = implode($r);

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student";

$db = new mysqli($servername, $username, $password, $dbname);

$query = "SELECT s_name, code FROM sponser where v_id = '$p'";
$result = mysqli_query($db,$query);

// this call was getting the first row of the result set
// and then ignoring it as yo do nothing with it
//$row = mysqli_fetch_array($result);

// now you fetch one row at a time
// each time round the while loop
while ($row = $result->fetch_assoc()) {
    printf ("s_name: %s  code: %s", $row["s_name"], $row["code"]);
    // the break is not required, and in fact stops
    // the while loop after its has fetched only the first row
    //break;
}
  

在您的查询被写入时,它有SQL Injection Attack的风险   看看Little Bobby Tables偶然发生了什么   if you are escaping inputs, its not safe!   使用prepared parameterized statements

<?php
session_start();
$r  = $_SESSION["v_id"];
$p = implode($r);

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student";

$db = new mysqli($servername, $username, $password, $dbname);

$query = "SELECT s_name, code FROM sponser where v_id = ?";
$stmt = $db->prepare($query);
if ( !$stmt ) {
    echo $db->error();
    exit;
}
$stmt->bind_param('i', $_SESSION["v_id"]);

$result = $db->execute();
if ( !$stmt ) {
    echo $db->error();
    exit;
}

// Gets a result set from a prepared statement
$result = $stmt->get_result();

// this fetches the result
while ($row = $result->fetch_assoc()) {
    printf ("s_name: %s  code: %s", $row["s_name"], $row["code"]);
}
?>