I am having trouble inserting my data into a MySQL database via PHP

I am currently tackling a school project and struggling to complete the registration page accurately. The data does not seem to be getting inserted into the table as intended.

Please take a look at this screenshot of the database and table

After reviewing all the provided answers, I have come to realize that my learning materials for PHP, HTML, CSS, and Website Security might be outdated.

 <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Register</title>
  </head>
  <body>
    <div class="form">
      <h2>Registration</h2>
      <form action="" method="post">
              Name<input type="text" name="name" placeholder="First & Last name" required><br><br>
              Username<input type="text" name="username" placeholder="Username"required><br><br>
              Password<input type="password" name="password" placeholder="Create a Strong Password"required><br><br>
              Confirm Password<input type="password" name="confirm-pass" placeholder="Re-enter Password"required><br><br>
              Email<input type="email" name="email" placeholder="Email"required><br><br>
              Phone No.<input type="text" name="phone-no" placeholder="Phone Number"required><br><br>
              Gender<input type="text" name="gender" placeholder="Male or Female"required><br><br>
              State<input type="text" name="state" placeholder="State"required><br><br>
              <button type="submit" name="home">Home</button>
              <button type="submit" name="sub">Submit</button>
              <button type="submit" name="reset">Reset</button>
            </form>
    </div>
  </body>
</html>
<?php
$con=mysqli_connect('localhost','root','123456789','eedb');
if ($con)
{
    if (isset($_POST['sub']))
    {
        $n= $_POST['name'];
        $un=$_POST['username'];
        $p=$_POST['password'];
        $cp=$_POST['confirm-pass'];
        $e=$_POST['email'];
        $pn=$_POST['phone-no'];
        $g=$_POST['gender'];
        $s=$_POST['state'];
        mysqli_query($con,"SELECT * FROM `register`");
        $insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`) VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
        if ($insert)
        {
            echo "<center>Data Successfully Submitted</center>";
        }
        else
        {
            echo "<center>Data Not Submitted</center>";
        }
    }
}
else
{
    echo "<center>Oh no! An error has occurred.<br><br>But fret not, we have a team of trained chimpanzees ready to tackle it.<br><br> <image src='images/chimps.jpg'><br><br>Come Back Soon</center>";
}
if (isset($_POST['home']))
{
    header("location:index.php");
}
if (isset($_POST['reset']))
{
    header("location:register.php");
}
?>

Answer №1

If your HTML form is missing, I have provided an example of what it should look like below. This snippet includes just one element as an illustration.

Remember to complete the form with the necessary information and follow the same format throughout.

<form method="post" action="handler.php">

First name:
<input type="text" name="name">
<br>
<input type="submit" name="sub" value="Submit">

</form>

It's essential to escape any values that might cause issues with MySQL, particularly special characters like apostrophes.

For instance: Doug's Bar & Grill.

Then execute:

$n= mysqli_real_escape_string($con, $_POST['name']);

To prevent SQL injection, consider using prepared statements since your current code is vulnerable.

  • Ref: How can I prevent SQL injection in PHP?

Apply the same process to all other POST arrays in your code.

When working with pure PHP and a post method in an HTML form, the name attribute must be included for POST arrays to function correctly.

Note: Your entire script depends on the condition
if (isset($_POST['sub'])){...}. Ensure that the form element shares the same name attribute.

  • Don't forget to check for errors.

If you encounter issues, display a message like this:

echo "<center>Data Not Submitted</center>";

References:

This line may not serve its intended purpose:

mysqli_query($con,"SELECT * FROM `register` ");

If you're trying to validate row existence, refer to my Stack Overflow answer:

  • check if row exists with mysql

Password Security

I observed that passwords might be stored in plain text in your application. It's strongly advised against doing so.

Consider implementing one of these methods:

Note on column length:

When adopting password_hash() or the compatibility pack, ensure that your password column has a length of at least 60 characters (255 recommended). Update the column and generate new hashes for the changes to take effect; otherwise, MySQL will fail silently.

Additional Resources:

  • CRYPT_BLOWFISH

HTML Specification Tip:

The <center> tag is deprecated according to Web standards and should not be used moving forward.

Learn more about this change here:

Answer №2

give this a shot

$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`)VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");

consider using notepad++ or another editor like netbeans to help with identifying open and closed brackets more easily.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving dates from a database and populating them into a jQuery UI Picker using PHP

I need to retrieve dates from the database using PHP and highlight them in a datepicker. Here is how I am attempting to accomplish this: HTML Date: <input type="text" id="datepicker"> // Static dates // An array of dates var eve ...

We're experiencing server sluggishness due to excessive MySQL usage

Welcome to my website: This platform functions as an advertisement network, similar to BuySellAds. Publishers have the ability to register and create ad spaces for their websites, while advertisers can select the specific ad space they wish to utilize for ...

Load classes in subdirectories of the application core in CodeIgniter 2

Within my application/core directory, I initially had a class named MY_Controller. Now, I am looking to create two separate classes in the following paths: application/core/Frontent/Frontend_Controller.php and application/core/Backend/Backend_Controller.ph ...

Data not successfully added to the table due to an error in the batch

I have the two tables designed to store information about the purchase and issuance of items. store_update_stock Table +-----------------+----------+-------------------+-----------------+--------+ | update_stock_id | supplier | user order_status | transf ...

Is there a method to prompt the browser to retain form data when using the back button?

Having a puzzling problem. I've developed a sophisticated quote form for our company that utilizes ajax to display prices for products based on user input. There are 6 hidden fields set up as follows: productname1 productname2 productname3 and the ...

Improving performance of Laravel Eloquent whereHas() query - facing significant delays

In my Laravel 5.4 project, I have three models: Order, OrderLine, and Product. The relationship between these models is as follows: - Order has many OrderLines - OrderLine has one Product associated with it via the product_id field in the OrderLine model ...

When retrieving keys and values from an associative array in PHP, it will not return all keys and values if they have the same key name

Currently, I am analyzing a file with the following data: Vélez Sarsfield|Zárate, Mauro|8|0|0|1|9 Estudiantes|Carrillo, Guido|5|1|0|2|8 Boca Juniors|Gigliotti, Emanuel|3|2|0|2|7 River Plate|Carbonero, Carlos Mario|4|2|0|0|6 Arsenal|Echeverría, Mariano|6 ...

Does the Wikipedia API provide limited data?

Hello there, I'm currently struggling with extracting data from Wikipedia articles by using its API (http://en.wikipedia.org/w/api.php) through a PHP script. However, I am only able to retrieve a small portion of the actual content. For instance, when ...

What is the process for transforming the outcome of a Javascript function into a webpage containing solely a JSON string?

I have a specific requirement where I need to fetch a URL and ensure that the only content displayed on the page is a JSON string. For instance, let's say I created a basic function called getDayOfWeek() to determine the current day of the week. The ...

What is the best way to turn a calendar table's <td> elements into interactive form elements?

I am currently working on developing an events booking form, but I am facing a challenge. I want users to be able to click on a specific date in a table cell representing a calendar to select their start date. However, my expertise lies more in PHP progra ...

Google Maps fails to load when triggered by the jQuery show() function

One issue I'm facing is that the Google Map is not loading after the show() function is called in jQuery. Initially, I use display:none to close a division on page load. After some research, I found out that it can be resolved by using google.maps.eve ...

Using the requests library to pass arguments to a JSON function

I've been attempting to utilize the guerrillamail API found at , but I'm facing some difficulties with the "set_email_user" function, as it requires me to send arguments along with the function call. Since I have no previous experience working w ...

recurring issues with time outs when making ajax requests

During the development of my website, I tested it as localhost. Now that it's nearly complete, I switched to using my local IP address and noticed that about 30% of my ajax calls result in time out errors or 'failed to load resource errors'. ...

Database numbers list with conditionals

I currently have a database structured in the following way: table: users column: day1, day2, day3, day4, day5 row: null, 1, 1, 1, null My goal is to achieve the following: if($row['day1'] == null) { $totalNullDays = '1' // &ap ...

Access a designated tab within a CSS-designed tab system

Can anyone offer some assistance? I currently have a tab structure created using CSS. The first tab is set as the default when the page loads. I am looking to create a link from another page that will take users directly to the page with the tabs and ope ...

Revise Stripe Pricing (payment_intent)

I'm in the process of building a website that allows users to select their subscription length (1/3/6/12 months) from a dropdown menu. When a user makes a selection, a modal window pops up displaying the Stripe payment forms. However, I've run i ...

Trouble arises when accessing GET form in php/Ajax

I am in the process of creating a dynamic website. At the top, I have an input form that, when submitted, should display the output from an asynchronous request to a PHP page using echo to show what was submitted. Unfortunately, it's not functioning ...

Modify a filter within a SQL query's selection code

Can someone assist me in updating the filter in my code below? I am unsure how to proceed. Here is the current code snippet: $query = "SELECT P.`Building_info` as `name`,P.`Area` as `area`, avg( CASE WHEN ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

Issue with $_SERVER['PHP_SELF'] not functioning properly

Apologies if this question has been asked before, but after searching extensively I couldn't find a solution. Therefore, I am posting here... The issue is that I'm trying to submit values on the same page (using jQuery Mobile UI) and I have used ...