2016-12-03 110 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。 –