简体   繁体   中英

Comparing user input data to mysql db

so i've recently got a job at a market, and they got a lot of PLU's that i need to know. So for helping me, i'm trying to do something to help me.

I've created a database with some of the items that look like this:

id art img plu_code

and in my index.php, after connecting to database and selecting a random id to show

$query = "SELECT * FROM produto ORDER BY RAND() LIMIT 1";

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $imagem_produto = $row["imagem"];
        $nome_produto = $row["artigo"];
        $plu_produto = $row["plu"];

        echo '<center><tr>
                  <td><img height="150" width="150" src="'.$imagem_produto.'"></td><br> 
                  <td>'.$nome_produto.'</td><br>
                  <td>'.$plu_produto.'</td>  
              </tr></center>';
    }
    $result->free();

    if ($plu_produto === $_GET['U']) {
        echo "Correct. Please wait!";
        header("Refresh:3");
    }else{
        echo 'Wrong.';
    }
}

?>

<html>
<body>
<form method="post">
<input type="text" name="U"/>
<input type="submit" />
 </form>
</body>

</html>

How do i compare the user input to the db and then show if it's correct or wrong? Thank you!

It is not like comparing the user input to the db.

Your code

if ($_POST['U'] === $plu_produto) {

compares with the last row read by the while loop which is not as expected.

After connecting to the database, have code to show all data which will show up in the first run. And after the user input you should select the relevant rows from the database itself which matches with "U" where there should not be any while loop but the sql select itself should return only one row.

You should just query for the specific PLU, not the entire table.

You also need to use $_POST , not $_GET , since the form has method="POST" .

if (isset($_POST['U'])) {
    $plu_produto = $_POST['U'];
    $stmt = $mysql->prepare("SELECT 1 FROM produto WHERE plu = ?");
    $stmt->bind_param("s", $plu_produto);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        echo "Correct. Please wait!";
        header("Refresh:3");
    }else{
        echo 'Wrong.';
    }
    exit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM