2017-01-30 32 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"]); 
} 
?> 
相關問題