-2

I have created php submit button using form action with the intention of just storing a username and school name to be stored in a database using xampp by clicking okay button. I have set the database table to have flds for ID as primary key and AI, username and school set to varchar with max length of 50. The code i have used shown does $con to the DB but only the ID is being send to the DB?? (what have i missed or need to do so that the data inputted can be stored like the ID)?.

<?php

require 'config.php';

$username = " "; //$username
$school = " ";//what school they attend

if(isset($_POST['register_button'])){
  $_SESSION['reg_username'] = $username; //Stores first name into session variable

  $_SESSION['reg_school'] = $school; //Stores first name into session variable

  $query = mysqli_query($con, "INSERT INTO users VALUES ('', '$username', '$school')");

 }
?>

<html>
 <head>
  <title> School </title>
</head>
<body>
    <h1> Welcome! </h1>

  <form action="index.php" method="POST">
    <input type="text" name="reg_username" placeholder="Name" value="<?php
        if(isset($_SESSION['reg_username'])) {
            echo $_SESSION['reg_username'];
        }
        ?>" required>

    <br>

        <input type="text" name="reg_school" placeholder="School" value="<?php
        if(isset($_SESSION['reg_school'])) {
            echo $_SESSION['reg_school'];
        }
        ?>" required>

    <br>

        <input type="submit" name="register_button" value="Okay">
</body>
</html>
P_Lee
  • 65
  • 7
  • Are `$username` and `$school` empty in the DB or are the ` `? – Christian Baumann Sep 26 '20 at 11:14
  • yes, it was because i was not loading the variables into the post data they were blank..Thanks – P_Lee Sep 26 '20 at 11:24
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 26 '20 at 13:00

1 Answers1

2

You need to load the post data into your variables before you insert them. The only assignement you did was $username = '';

$username = $_POST['reg_username'];
$school = $_POST['reg_school'];
Sélim Achour
  • 718
  • 4
  • 7
  • thanks i knew it was something obvious but could not see the trees for the woods. Much appreciated – P_Lee Sep 26 '20 at 11:22