tastybyte
tastybyte

Reputation: 3

"No result" when trying to retrieve names from database

Okay, so as you can see, I made a form. If I put in a name and surname and try to display it afterwards it works, but it goes wrong when I am trying to 'post' it to the database and retrieve it. It gives me a "no result". Since I'm fairly new to this, I don't know what I did wrong. Anyone seeing the problem here?

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

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


    echo "<form action='' method='post'>
    Naam: <input type='text' name='name'><br>
    Achternaam: <input type='text' name='surname'><br>
    <input type='submit'>
    </form>";

    $name = $_POST["name"];
    $surname = $_POST["surname"];

    //insert name
    $sql = "INSERT INTO Namen
    VALUES ($name, $surname)";
    $result = $conn->query($sql);


    if(!$result){
     echo "fout ".mysql_error();   

    }

    $sql = "SELECT Voornaam, Achternaam FROM Namen";
    $result = $conn->query($sql);

    echo "<table border='1px'>";
    echo "<th>Naam</th>";
    echo "<th>Achternaam</th>";
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<tr><td>" .$row["Voornaam"] . "</td>";
            echo "<td>" . $row["Achternaam"] . "</td></tr>";
        }
    } else {
        echo "0 results";
    }
    echo "</table>";
    $conn->close();
    ?>

Upvotes: 0

Views: 49

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

Your values' variables VALUES ($name, $surname) must be encapsulated inside quotes, since we are (more than likely) dealing with strings.

Change it to VALUES ('$name', '$surname')

You're also mixing (they don't mix together) MySQL APIs with echo "fout ".mysql_error(); which needs to be changed to echo "fout ".mysqli_error($conn); to give you the actual error(s) found.

Also, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.


You should also consider wrapping your code (or the one you wish to execute) inside a conditional statement based on a named submit button.

I.e.:

<input type='submit' name='submit' value='Submit'>

then doing

if(isset($_POST['submit'])){...}

the {...} being your initial query, and/or the entire (or portion of) of your PHP/SQL code.

Upvotes: 1

Related Questions