2

I am trying to send data from form but its sending the name in stead of value of the input box. File is uploading properly and the input box name is uploading too but I need to put the values.

<form action="intern.php" enctype="multipart/form-data" method="post" autocomplete="off">
     <h3  class="register-heading">Want to be a <strong>learner Bee</strong>?</h3>
       <div class="row register-form">
          <div class="col-md-6">
            <div class="form-group">
              <input type="text" class="form-control" name="iname" placeholder="Your Certificates name" value="" required />
      </div>
      <div class="form-group">
                <input type="text" class="form-control" maxlength="14" minlength="10" name="icon" placeholder="Your 24/7 opened Phone Number" value="" required />
      </div>
     <div class="form-group">
           <input type="text" class="form-control" name="ildegree" placeholder="University you are graduating from" value="" required />
         </div>
      <div class="form-group">
           <textarea type="text" class="form-control" name="iaboutus"  placeholder="What you know about us!" value="" required ></textarea>
           </div>
       <div class="form-group">
            <textarea type="text" class="form-control" name="iaddress" placeholder="Your present address " value="" required ></textarea>
       </div>
       <div class="form-group" >
           <label class="form-control" for="iapply"><input name="icvfile" style="  border: 0; clip: rect(1px, 1px, 1px, 1px); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;" type="file" name="" id="iapply" accept=".doc, .docx, .pdf, .png, .jpg, . ppt, .pptx" required>Click here to upload your CV</label>
            </div>
      </div>
      <div class="col-md-6">
           <div class="form-group">
               <input class="form-control" name="inname" placeholder="Nick Name you like to called by" value="" required />
                </div>
         <div class="form-group">
         <input type="email" name="iemail" class="form-control" placeholder="Your own mostly used Electronic mail" value="" required />
          </div>                              
      <div class="form-group">
       <select class="form-control" name="icontrib" required>
               <option class="hidden"  selected disabled>How you can contribute us?</option>
                <option>Graphic Design</option>
                <option>Sales</option>
                <option>Creative Idea Generation</option>
        </select>
        </div>
        <div class="form-group">
          <textarea  type="text" class="form-control" name="ixp" placeholder="Your past working experience in short" value="" required ></textarea>
      </div>
      <div class="form-group">
          <textarea  type="text" class="form-control" name="ifgoal" placeholder="Where you want to see yourself after 10 years!" value="" required ></textarea>
           </div>
      <input type="submit" class="btnRegister" name="isubmit" value="Submit"/>
      </div>
      </div>
   </form>

Upper one is the form that I need to filled. Just stuck somewhere, cannot find out.

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("Location: https://teambbc.asia/error.html");
        } 
        $sql = "INSERT INTO Intern (Name, Contact, University, AboutUs, Address, NickName, Email, Contribution, Experience, FutureGoal) VALUES ('iname', 'icon', 'ildegree', 'iaboutus', 'iaddress', 'inname', 'iemail', 'icontrib', 'ixp', 'ifgoal')";
        //Filename upload
        $user=$_POST['inname'];
        $cont=$_POST['icon'];
        //$filename=basename($_FILES["file"]["name"]);

        $tmp=$_FILES["icvfile"]["tmp_name"];
        $extension = explode("/", $_FILES["icvfile"]["type"]);
        $name=$user.".".$extension[1];

         move_uploaded_file($tmp, "recruitment_cv/" . $user. "-" .$cont .".".$extension[1]);


        if (mysqli_query($conn, $sql)) {
           header("Location: https://teambbc.asia/congratulations.html");
        } else {
           echo "Error: " . $sql . "" . mysqli_error($conn);
           header("Location: https://teambbc.asia/error.html");
        }
        $conn->close();
     }

My connnection with database is okey, I am not thinking about that one.

Martin
  • 22,212
  • 11
  • 70
  • 132
  • Does it generate any errors – Nipun Tharuksha Jul 22 '19 at 19:24
  • No, it is just transferring the name only what ever I provide through the input box. – Md. Shohanur Reza Badhon Jul 22 '19 at 19:25
  • What do you mean by name????? please add your form code too – Nipun Tharuksha Jul 22 '19 at 19:26
  • There is no form in your question. Please [edit] your question and add more details including the complete form. – Dave Jul 22 '19 at 19:28
  • 2
    You are not using the `$_POST` variables in your `insert` command, only hard coded string. Is this the desired behavior? – Felippe Duarte Jul 22 '19 at 19:28
  • 2
    Well, of course it is. `VALUES ('iname', 'icon', 'ildegree', 'iaboutus', 'iaddress', 'inname', 'iemail', 'icontrib', 'ixp', 'ifgoal')` passes in those exact strings to your database, and you never replace them. You'd be better off using [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [bind_param](http://php.net/manual/en/mysqli-stmt.bind-param.php) to prevent SQL injection and quoting issues, and so that you can better see how you're passing in the form variables. – aynber Jul 22 '19 at 19:28

2 Answers2

6

Your Problem:

You are inserting Strings [ref] rather than Variables [ref] in to your SQL.

See:

$sql = "INSERT INTO Intern (Name, Contact, University, .... )
        VALUES ('iname', 'icon', 'ildegree', .... )";

The values in 'quotes' are MySQL string literals. These values are NOT PHP variables. So they will be the same, no matter what variable data you give to PHP.

Solution Basics:

To fix this, you need to understand that when you submit a form the superglobals $_POST/$_GET and $_REQUEST are populated with the form data.

Example:

HTML:

<form action="intern.php" enctype="multipart/form-data" method="post" autocomplete="off">
 <input type="text" class="form-control" name="iname" placeholder="Your Certificates name" value="" required />
<input type='submit' value='Button to submit the form'>
</form>

PHP:

if(!empty($_POST['iname'])){
    print_r($_POST['iname']); // This will output the value entered into the form for the iname form element. 
}

So Applying This To Your SQL:

You need to at a very basic level turn your strings into variables:

$sql = "INSERT INTO Intern (Name, Contact, University, .... )
        VALUES ('".$_POST['iname']."', '".$_POST['icon']."', '".$_POST['ildegree']."', .... )";

BUT:

THIS IS DEEPLY INSECURE.

YOU MUST NEVER, EVER TRUST USER SUBMITTED DATA. EVER.

Reference and Reference

So how should you save this data safely, to your SQL table?

By using Prepared Statements; either PDO or MySQLi.

My example here will use Object Orientated MySQLi Prepared Statements:

    $sql = "INSERT INTO Intern (Name, Contact, University) VALUES (?,?,?)";

    $insert = $conn->prepare($sql);
    /***
     * See https://www.php.net/manual/en/mysqli-stmt.bind-param.php
     * You can add multiple values at once: 
     ***/
    $insert->bind_param("sss", $_POST['iname'],$_POST['icon'],$_POST['ildegree']);
    $insert->execute();

This will insert the data (example only three bits of data but you should get the idea), safely and easily into your database.

There is a lot I have missed out for simplicity and verboseness, so you should read up on how to use PDO/MySQLi proficiently.

NOTES:

  • One ? in the SQL string for each placeholder.
  • One value letter in the bind_param for each placeholder value. The value, and the corresponding value letter (i,s,d,b) MUST match the SQL column type (you can't insert string-type (s) values into integer-type columns (INT, TINYINT, etc.).
  • In MySQLi order is important, the first ? will relate to the first bind_param value (in the example codeblock above, $_POST['iname']).

Qualifier:

Some of your MySQL PHP code uses procedural interactions, and functions - and some of your MySQL PHP code uses Object Orientated interactions and functions. These CAN NOT BE MIXED and will result in errors and inconsistencies for you.

ALWAYS USE OBJECT ORIENTATED PHP/MYSQL INTERACTIONS Reference and Reference

Objct orientated interactions use the -> syntax.

You have:

if ($conn->connect_error) {
    error_log("Connection failed: " . $conn->connect_error);
    header("Location: https://teambbc.asia/error.html");
    }  

This is Object Orientated. This is best.

But:

mysqli_query($conn, $sql);

This is Procedural. This is not best. The OO version of this line would be $var = $conn->query($sql).

Bonus advice:

  • Do not use die to output error messages to the screen, error messages should always be output to the error log file.

  • When using header("Location: ... "); you must always put die() or exit afterwards:

    Example:

    if ($conn->connect_error) {
        error_log("Connection failed: " . $conn->connect_error);
        header("Location: https://teambbc.asia/error.html");
        exit;
        } 
    

Good luck!

Martin
  • 22,212
  • 11
  • 70
  • 132
  • @FelippeDuarte hah, I missed out a lot of details, but thanks. `:-D` – Martin Jul 22 '19 at 20:35
  • @Martin this is amazing. Best answer and well explained . Great job – Nipun Tharuksha Jul 22 '19 at 20:39
  • @NipunTharuksha Thank you `:-)` – Martin Jul 22 '19 at 20:40
  • @Martin in OOP should we have to pass data directly to the VALUES or can we declare the variable and fetch data and then assing it to the VALUE. Which one is recmended – Nipun Tharuksha Jul 22 '19 at 20:42
  • @NipunTharuksha please can you clarify what you mean by `fetch data`? You can set any `$data` you like to save to MySQL via Parameterised queries (illustrated above); – Martin Jul 22 '19 at 20:45
  • @Martin usually what I do is `$name = $_POST['name'];` and then insert `$name` as value. In your answer I can see that you have directly inserted the `$_POST['name']`What I wants to know is which one is the best method. – Nipun Tharuksha Jul 22 '19 at 20:50
  • 1
    @NipunTharuksha in OOP SQL you should add the variables to the `bind_param` function. It doesn't matter from a security point of view what value you use. I would recommend forcing type casting so for numeric (integer) columns you'd set `bind_param('i',(int)$idValue);` , etc. Does that make sense? – Martin Jul 22 '19 at 20:52
  • @NipunTharuksha because if the value does not fit the `type` (Set by the [first string in`bind_param`](https://www.php.net/manual/en/mysqli-stmt.bind-param.php#types)) then it is not inserted and the execution is aborted. – Martin Jul 22 '19 at 20:53
-4

You should assign data to variables firstly. After that, you can insert to db.

function make_secured($x) 
{
   $variable = strip_tags(mysql_real_escape_string(trim($x)));
   return $x; 
}

    $_POST = make_secured($_POST);

    $name = $_POST['iname'];
    $contact = $_POST['icon'];

    $sql = "INSERT INTO Intern (Name, Contact) VALUES ('$name', '$contact')";

make_secured() function does checking all sql injection attacks in the POST.

ariferol01
  • 221
  • 4
  • 13
  • @FelippeDuarte He does'nt ask like this: "how can i solve this problem as safely". If he was ask about prepared statements, yes exactly we should write answer security focused. – ariferol01 Jul 23 '19 at 00:04
  • 1
    arif's answer is correct but he must add more detailed info. – kodmanyagha Jul 24 '19 at 12:59