2017-04-09 26 views
0

我试图寻找解决方案,但找不到一个解决方案。在我的PHP页面上,我试图在两个条件下搜索记录,如果用户在搜索框中输入内容然后根据该内容显示,并且如果他不搜索任何内容,则从表中显示记录。试图在php下运行两个sql查询,如果其他条件?

我得到的所有记录,但无法获取记录时,我用他们的名字搜索他们。

<?php 
if(isset($_POST['search'])) 
{ 
$name=$_POST['src']; 
$qry1=mysqli_query($connection,"select * from test_history where 
username='$name'"); 
} 
else 
{ 
$qry1=mysqli_query($connection,"select * from test_history"); 
$counter=0; 
while($ftc=mysqli_fetch_array($qry1)) 
echo 
'<tr> 

<td align="center"> '.++$counter.' </td> 
<td> '.$ftc['username'].' </td>  
<td> '.$ftc['enrollment'].' </td> 
<td> '.$ftc['test_cat'].' </td> 
<td> '.$ftc['test_name'].' </td> 
<td> '.$ftc['score'].'% </td> 
<td> '.$ftc['test_date'].' </td> </tr>'; 

} 
    if(isset($_POST['submit'])) 
    { 
    $dlt=mysqli_query($connection,"delete from test_history"); 
    } 
?> 
+0

*发生了什么?这个失败具体如何?注意:你的代码对SQL注入非常开放(所以我们不知道你实际运行的是什么SQL查询)并且你没有用'mysqli_error($ connection)'检查错误(所以你不知道是否/查询失败的方式)。 – David

+0

它没有输出任何结果只是空表。错误代码被写入另一个文件,未列出。对不起,我是PHP的新手,每天都在学习。你能告诉我什么是防止SQL注入的最佳方法!顺便说一句,我的问题已解决。 –

+0

不确定您的意思是“错误代码是否写入另一个文件”。你应该看看'mysqli_error'函数来检查代码中的错误。至于SQL注入,这是一个很好的开始:https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – David

回答

2

可能是因为显示结果的表在“else”块内。试着把它弄到外面去。

 <?php 
    if(isset($_POST['search'])) 
    { 
    $name=$_POST['src']; 
    $qry1=mysqli_query($connection,"select * from test_history where 
    username='$name'"); 
    } 
    else 
    { 
    $qry1=mysqli_query($connection,"select * from test_history"); 
    $counter=0; 
    } 

// ... // 

    while($ftc=mysqli_fetch_array($qry1)) 
    echo 
    '<tr> 

    <td align="center"> '.++$counter.' </td> 
    <td> '.$ftc['username'].' </td>  
    <td> '.$ftc['enrollment'].' </td> 
    <td> '.$ftc['test_cat'].' </td> 
    <td> '.$ftc['test_name'].' </td> 
    <td> '.$ftc['score'].'% </td> 
    <td> '.$ftc['test_date'].' </td> </tr>'; 

// ... // 

     if(isset($_POST['submit'])) 
     { 
     $dlt=mysqli_query($connection,"delete from test_history"); 
     } 
    ?> 

发生了什么将代码

里面的“其他”块任何部分将会被执行时的否定“如果”条件满足,即,isset($ _ POST [”之后搜索'])是“假”。负责显示数据的代码部分位于“else”块内,这意味着只有当isset($ _ POST ['search'])返回false时才会显示数据。

显然,那不是你想要的。您总是想要显示数据,并且您想要根据$ _POST ['search']值更改查询。第二个要求是通过if语句实现的。请参阅http://php.net/manual/en/control-structures.else.php

+0

Jazakallah(谢谢)..我是新的PHP编程,所以没有尝试过。你能告诉我背后的原因吗?仍然显示没有找到“$ counter”,只是将其移出“其他”块。 (在“while”之前)。瞧! –

+0

还有一件事,如果我想根据“从这个日期”到“这个日期”获取这些记录,我应该应用什么逻辑。谢谢.. –

+0

嗨。我更详细地更新了主要答案。 –

相关问题