简体   繁体   中英

Trying to add values from HTML form into mySQL database using PHP

I am unable to add values from input boxes to a database I created manually. My index form is below.

  <!DOCTYPE html>
     <Header>
     </header>
     <body>
     <form action="includes/signup.inc.php" method="POST">
         <input type="text" name="inputName" placeholder="First Name">
         <br>
         <input type="text" name="inputLastname" placeholder="Last Name">
         <br>
         <input type="text" name="inputGender" placeholder="Gender">
         <br>
         <button type="submit" name="submit"> Sign up </button>
     </form> 
     </body>

I have a signup.inc.php file inside an "includes" folder where the heavy lifting is supposed to occur. See below

<?php
    require_once 'dbh.inc.php';

    /* Variables from input form for SQL */
    $inputName = $_POST['inputName'];
    $inputLastname = $_POST['inputLastname'];
    $inputGender = $_POST['inputGender'];

    /* Using said variables from form to insert into SQL database */
    $sql = "INSERT INTO tbl_users (first_name, last_name, gender) 
            VALUES ('$inputName,' '$inputLastname', '$inputGender');";
    mysqli_query($conn, $sql);

    /* If this page runs successfully, URL bar should have success */
    header("location: ../index.php?signup=success");
?>

From what I understand, I created the variables and slotted them into my SQL statement, pulling values from the form, as seen below. $conn is a variable from dbh.inc.php that is the connection between my PHP project and the database.

The error below is what I get:

Fatal error: Uncaught mysqli_sql_exception: Column count doesn't match value count at row 1 in G:\xampp\htdocs\phptutorial\includes\signup.inc.php:10 Stack trace: #0 G:\xampp\htdocs\phptutorial\includes\signup.inc.php(10): mysqli_query(Object(mysqli), 'INSERT INTO tbl...') #1 {main} thrown in G:\xampp\htdocs\phptutorial\includes\signup.inc.php on line 10

I tried removing altering where DBH was being pulled from and the error changes so I know I'm pulling information from the right file. My database only has users_id which is Auto Increment so I doubt that could be an issue.

You have an error with your SQL Query. Always use "." when you are adding custom PHP values. try use

    $sql = "INSERT INTO tbl_users (first_name, last_name, gender) 
            VALUES('" . $inputName. "','" . $inputLastname. "','" . $inputGender. "');"

Instead Of

$sql = "INSERT INTO tbl_users (first_name, last_name, gender) 
        VALUES ('$inputName,' '$inputLastname', '$inputGender');";

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