vendredi 25 janvier 2019

Problems with if/else in fetch_assoc

I have this code - a simple database search with two fields. If there is a match It should echo the values that are in the database. If there is no match it schools echo a table with info that there is no record with the entered values. I’m doing something wrong :( when there is no match the code works, but when there is a match the code shows both. Can you please help me?

The code:

<?php
if( isset($_POST['user_id']) and isset($_POST['entry_no']) ) {

    // DB Connection 
    $host="localhost";
    $user="root";
    $pass="pass";
    $db="Database";

    //Connection
    $conn = new mysqli ($host, $user, $pass, $db);

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

    // set Variables
    $user_id = $_POST["user_id"];
    $entry_no = $_POST["entry_no"];

    //set Query
    $query = "SELECT * FROM demo WHERE user_id='$user_id' OR entry_no='$entry_no'";
    $result = $conn->query($query);
    if (!$result) die($conn->error);

    echo '<p style="color:red; font-family:Trebuchet ms; font-weight:bold;"> There is no Record in the Database for </p>';
    echo '<table>
           <tr>
           <td style="font-family:Trebuchet ms; font-weight:bold; ">';
    echo 'User ID: </td>
           <td style="font-family:Trebuchet ms; font-weight:bold; color:red;">' . $user_id . '</td>
           </tr>';
    echo '<tr>
           <td style="font-family:Trebuchet ms; font-weight:bold; ">';
    echo 'Entry Number: </td>
           <td style="font-family:Trebuchet ms; font-weight:bold; color:red;">' . $entry_no . '</td>
           </tr>
           </table>';

    $rows = $result->num_rows;
    for ($j = 0 ; $j < $rows ; ++$j)
    {
        $result->data_seek($j);
        $row = $result->fetch_array(MYSQLI_ASSOC);
        echo 'table_id: ' . $row['table_id'] . '<br>';
        echo 'user_id: ' . $row['user_id'] . '<br>';
        echo 'entry_no: ' . $row['entry_no'] . '<br>';
        echo 'name: ' . $row['name'] . '<br>';
        echo 'vorname: ' . $row['vorname'] . '<br>';
        echo 'female: ' . $row['female'] . '<br>';
        echo 'born: ' . $row['born'] . '<br>';
    }
}

$result->close();
$conn->close();
?>
</br></br></br>
<hr color="gray" width=33% align="center">
    </br>
    <div>
    <a href="db_view_full.php?entry_no=<?php echo $row["entry_no"]; ?>">View Full Record</a>              /
    <a href="db_input.php?entry_no=<?php echo $row["entry_no"]; ?>">Edit This Record</a>          /
    <a href="db_input.php">Insert New Record</a>            /
    <a href="db_search.php">Search again</a>                /
    <a href="db_logout.php">Logout</a>
    <p>You are currently logged in as "<strong><?php echo $_SESSION['user']; ?></strong>"</p>
    </div>

Aucun commentaire:

Enregistrer un commentaire