Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Fatal error: Uncaught mysqli_sql_exception: Unknown column 'gender' in 'field list' in C:\Users\sumer\PhpstormProjects\untitled\php.php:39 Stack trace: #0 C:\Users\sumer\PhpstormProjects\untitled\php.php(39): mysqli->query('INSERT INTO stu...') #1 {main} thrown in C:\Users\sumer\PhpstormProjects\untitled\php.php on line 39
This is the error.
Iam tried to write this question:
1. Design a web page using HTML5 that includes the following form fields:
a. Full Name (text input)
b. Email Address (email input)
c. Gender (radio buttons for Male/Female)
d. Submit button
2. Connect to a MySQL database using pure PHP. Create a table named "students" with the 
following columns:
a. id (auto-incrementing primary key)
b. full_name (VARCHAR)
c. email (VARCHAR)
d. gender (ENUM: 'Male', 'Female')
When the user clicks the Submit button, use the POST method to send the form data to a PHP 
script that performs the following actions:
a. Validates the form data once again on the server-side.
b. If the data is valid, insert the student's information into the "students" table in the database.
c. Display a success message on the web page if the data is successfully inserted into the 
database.
d. If there are any errors, display appropriate error messages on the web page.
*You do not need to use any CSS.
And finally list the information of the students registered from the database on the web 
page by performing the above requirements. (You can make the listing as you wish.


What I have tried:

<?php

// Server-side form validation
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST)) {
    // Validate Full Name
    if (empty($_POST['full_name'])) {
        $errors[] = 'Full Name is required';
    }

    // Validate Email Address
    if (empty($_POST['email'])) {
        $errors[] = 'Email Address is required';
    } elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid Email Address';
    }

    // Connect to MySQL database
    $servername = 'localhost';
    $username = 'root';
    $password = '';
    $dbname = 'ibp';

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

    if ($conn->connect_error) {
        die('Connection failed: ' . $conn->connect_error);
    }

    // Insert data into database if there are no errors
    if (empty($errors)) {
        $full_name = $_POST['full_name'];
        $email = $_POST['email'];
        $gender = $_POST['gender'];

        $sql = "INSERT INTO students (full_name, email, gender) VALUES ('$full_name', '$email', '$gender')";

        if ($conn->query($sql) === true) {
            $success_message = 'Registration successful!';
        } else {
            $errors[] = 'Error: ' . $conn->error;
        }
    }

    // Close the database connection
    $conn->close();
}

// Display the students' information from the database
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'ibp';

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

if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

$sql = "SELECT * FROM students";
$result = $conn->query($sql);

$students = [];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $students[] = $row;
    }
}

// Close the database connection
$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Student Registration Form</title>
</head>
<body>
<h1>Student Registration Form</h1>

<?php if (!empty($errors)) { ?>
    <div style="color: red;">
        <?php foreach ($errors as $error) {
            echo $error . '<br>';
        } ?>
    </div>
<?php } ?>

<?php if (isset($success_message)) { ?>
    <div style="color: green;">
        <?php echo $success_message; ?>
    </div>
<?php } ?>

<form method="post" action="">
    <label for="full_name">Full Name:</label>
    <input type="text" id="full_name" name="full_name" required><br>

    <label for="email">Email Address:</label>
    <input type="email" id="email" name="email" required><br>

    <label for="gender">Gender:</label>
    <input type="radio" id="male" name="gender" value="Male" required>
    <label for="male">Male</label>
    <input type="radio" id="female" name="gender" value="Female" required>
    <label for="female">Female</label><br>

    <input type="submit" value="Submit">
</form>
<h2>Registered Students:</h2>
<table>
    <thead>
    <tr>
        <th>ID</th>
        <th>Full Name</th>
        <th>Email</th>
        <th>Gender</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($students as $student) { ?>
        <tr>
            <td><?php echo $student['id']; ?></td>
            <td><?php echo $student['full_name']; ?></td>
            <td><?php echo $student['email']; ?></td>
            <td><?php echo $student['gender']; ?></td>
        </tr>
    <?php } ?>
    </tbody>
</table>
</body>
</html>
Posted
Updated 28-May-23 18:26pm

1 solution

Read the error message, it's pretty explicit:
-"Error"
Uncaught mysqli_sql_exception: Unknown column 'gender' in 'field list'
Then look at the code: it refers to
PHP
$sql = "INSERT INTO students (full_name, email, gender) VALUES ('$full_name', '$email', '$gender')";

if ($conn->query($sql) === true) {
It's saying "there is no field in that table called 'gender' so I don't know where to put the data"

Check your table design and find out what the fields are named.

You should expect to get syntax errors every day, probably many times a day while you are coding - we all do regardless of how much experience we have! Sometimes, we misspell a variable, or a keyword; sometimes we forget to close a string or a code block. Sometimes the cat walks over your keyboard and types something really weird. Sometimes we just forget how many parameters a method call needs.

We all make mistakes.

And because we all do it, we all have to fix syntax errors - and it's a lot quicker to learn how and fix them yourself than to wait for someone else to fix them for you! So invest a little time in learning how to read error messages, and how to interpret your code as written in the light of what the compiler is telling you is wrong - it really is trying to be helpful!

So read this: How to Write Code to Solve a Problem, A Beginner's Guide Part 2: Syntax Errors[^] - it should help you next time you get a compilation error!

And spending a little time learning to understand syntax error messages will save you a huge amount of time in future: you waited at least 7 hours for me to reply, then your email system probably added another 10 minutes or so, plus the time it took you to type up the question once you had found this site and created an account. Chances are that you could have saved a significant chunk of that time if you knew how to read them!

I'm not saying we don't want to help you fix them - sometimes I can't see my own errors because I read what I meant to write - but fixing syntax errors is part of the job, and if you can't do it for yourself people are going to look at you as a bit weird should you get a job in the industry!

Oh, and while I'm here ... Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900