根据信息获取用户数据

时间:2015-11-03 16:58:16

标签: php mysql

第一个字段是网络访问者将进入' cardname'点击提交并转到另一个页面(dashboard2.php),其中只显示他或她的内容。

Enter your cardname to access your content<br>
<form action='dashboard2.php'>
<input type='text' name='cardname'/><input type='submit' value='retrieve card'/>
</form>
</body>

以下页面是用户输入&#39; cardname&#39;后定向的页面。从第一个输入字段。但是,我只希望第二页根据输入的卡名显示信息。现在,它显示了该表中的每个单一名称,问题,答案。

    <?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT cardname, questionone, answerone FROM cards";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<br> ". $row["cardname"]. "  ". $row["questionone"]. " " . $row["answerone"] . "<br>";
     }
} else {
     echo "0 results";
}

$conn->close();

?>

2 个答案:

答案 0 :(得分:2)

您必须修改查询以接受WHERE子句。例如,WHERE cardname = mysqli_real_escape_string($conn, $_GET['cardname'])除非您指定method="post",否则任何表单的默认方法都是GET。)。

您应该了解preparedMySQLi语句,并考虑使用PDO,it's really not hard

答案 1 :(得分:-1)

您似乎想要执行搜索而不是显示所有记录。 通常,搜索会返回与特定字段匹配的记录,除非在搜索中输入了特定ID或唯一值。我不确定是不是这样。

我把它放在一起有点快,但希望它有帮助...

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// escape the string to avoid SQL injections
$searchEscaped = $conn->real_escape_string($_POST['cardname']);

// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT cardname, questionone, answerone FROM cards WHERE cardname = '$searchEscaped' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    if($result->num_rows == 1){
        // only one result found, show just that
        $row = $result->fetch_assoc()
        echo "<br> ". $row["cardname"]. "  ". $row["questionone"]. " " . $row["answerone"] . "<br>"; 
    }else{
        // multiple rows found, show them all
        while($row = $result->fetch_assoc()) {
             echo "<br> ". $row["cardname"]. "  ". $row["questionone"]. " " . $row["answerone"] . "<br>";
         }
    }

} else {
     echo "0 results";
}

$conn->close();

?>