2016-12-03 153 views
0

*如果(!空)檢索第一個條目的陣列,不應該使用*mysqli_fetch_assoc while循環不工作

這個腳本搜索數據庫進行匹配在用戶提交了一個網址形成。目前由echo語句打印的$查詢在mysql中正常工作並返回一個條目。該腳本執行並打印表頭,但不輸入while($ row = ..)循環。

任何想法或建議將非常感激。我以前使用過這種方法沒有麻煩,所以我現在很困難。

//1. Query DB for results 

    $query = "SELECT * FROM projects WHERE projectsurl='".$url."';"; 
    echo "<br>".$query; 
    $projects = mysqli_query($conn, $query); 

// 2. Print Project Results 

if(!empty(mysqli_fetch_assoc($projects))){ 
    //Print Project Results 
    echo "Is this your project?<br>"; 
    echo "<table style=width:'100%'>"; 
    while ($row = mysqli_fetch_assoc($projects)){ 

    echo $tabler . $thh . "Title: <br>" .$row['title'] . $thsp . "No. Rewards: <br>" . $row['rewards'] . $thf . $xtabler; 
    echo $tabler . $thh . "ID: " .$row['id'] . $thf . $xtabler; 
    // Echo two rows for the URL Strings because they are longer. 
    echo $tabler . $thh . "<a href='" . $row['projectsurl'] . "'>Projects</a>" . $thsp . "<a href='" . $row['rewardsurl'] . "'> Rewards " . $thf . $xtabler; 
    echo "<form id='confirmation' action='../index.php' method='POST'> 
      <input type='hidden' value='2' name = 'stage'> 
      <input type='hidden' value='".$row['id']."' name='id'> 
      <input type='hidden' value='".$row['title']."' name='title'> 
      <input type='submit' value='Confirm'></form>"; 
    } 

    echo "</table>"; 


    }else{ 
      //trigger ruby script to search for lost file 
      echo "Project Not Found. <br>"; 




    } 

哦,隨機表的東西是其他地方定義爲

$tabler = "<tr>"; 
$xtabler = "</tr>"; 

$thh = "<th><b>"; 
$thsp = "</th><th>"; 
$thf = "</b></th>"; 

$csp = "</td><td>"; 
$ch = "<td>"; 
$cf = "</td>"; 
+0

你已經在你的'if(!empty('語句中獲取了一行,如果你只有一行,那麼while循環永遠不會輸入。 –

+0

使用https://secure.php.net/manual/ en/mysqli-stmt.num-rows.php而不是 –

+0

哈!猜猜這就是我試圖變得聰明時會發生什麼,謝謝! – itchyspacesuit

回答

1

如果只有一排,然後if(!empty(mysqli_fetch_assoc($projects))){將獲取它和你while循環將不進入。相反,要檢查一行是否存在,請使用mysqli_num_rows($projects)

另外,提醒,如果您尚未使用它,請在MySQL查詢中使用它之前轉義您的用戶提交的數據。這可以通過以下方式完成:$query = "SELECT * FROM projects WHERE projectsurl='".mysqli_real_escape_string($conn, $url)."';";

編輯:或者,準備MySQL語句,然後再執行它們。這是首選的方法,雖然兩者都可以保護您免受注射。

+1

轉義是一種古老的技術,不應該再使用,而應該使用Prepared Statements。 –