2017-01-30 57 views
-1

只有一个数据行从数据库中获取。如何显示从SELECT返回的所有数据。该SELECT应,通过调用之前抓取返回多行,查询中的ID是外键的可以返回一个或多个结果从数据库只有一个数据块如何显示所有数据特定的一个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; 
     } 
    } 
    ?> 
+0

然后使用select *(或)从数据库中提取时,在选择查询中写入所有列.. – Sona

+0

您还需要绑定参数!留下自己打开SQL注入在这里.. – Option

回答

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

你被扔掉你的结果集的第一行进入while循环。

行从结果集中一次一个地取出,像这样在一个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"]); 
} 
?> 
相关问题