0

I've tried the following code for inserting data into the database. The database is getting connected. But the data is not getting added to the database. I dont know where i have gone wrong. Can anyone help me with this?

    <html>
    <head>

    <title>registration</title>
    <meta charset="UTF-8">
    <link href="site.css" rel="stylesheet">
    <div align="center">
    <link rel="stylesheet" href="mine.css"/>
   
  <table border="0" align="center" style="border-spacing: 40px 20px;">
        
          <align="center">  <td>
 </head>  
 
    <body bgcolor=" #b3ffe0">

    <style>

    html {
    font-family: "Lucida Sans", sans-serif;
    }
    ul li {display: block;position: relative;float: left;border:1px } 
    ul li a {display: block;text-decoration: none; white-space: nowrap;color:#fff;}
     ul {
    list-style-type: none;
    padding: 2px ;
 margin-left: auto;
    background-color: #666;
    }
    li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 10px 20px;
    text-decoration: none;
 
    }
    li a:hover, .dropdown:hover .dropbtn {
    background-color: #111;
    }
    </style>
    </head>
    <body>
    <form action="df1.php" method="post">
    <ul>
      <li><a class="active" href="df.html">Disease</a></li>
      <li><a href="drug.html" align="_self">Drug</a></li>
      <li><a href="#about">Interaction</a></li>
   <a href="#" class="dropbtn">Alternate Drug</a>
       </ul>
  

     <div>


    <table border="2" align="center" style="border-spacing: 40px 30px;">
        <caption><strong>DISEASE DETAILS:</br></br></strong></caption></br></br>
        <tr>   
        <td><center>  Disease_ID
                <select name="Day">
                    <option value="1">1</option>
                    <option value="2">2</option>
                   </select></center>   
            </td>
       <td>Disease
                <select name="DisType">
                    <option value="Select">Select</option>
                    <option value="Acute">Acute</option>
                    <option value="Chronic">Chronic</option>
                    <option value="Acquired">Acquired</option>
                    </select>
            </td>
           
     <td>SubDisease
                <select name="DisType">
                    <option value="Select">Select</option>
                    <option value="Acute">Acute</option>
                    <option value="Chronic">Chronic</option>

                </select>
            </td>
           
     
            <td>Associated_Disease<input type="text" name="DisDu"></td>
        </tr>

           <td>Ethinicity<select name="DisType">
                    <option value="Select">Indian</option>
                    <option value="Acute">European</option>
                    <option value="Chronic">oman</option>
                    <option value="Acquired">German</option>
                    
                   
                </select>
            </td>
           
           <td>Source<textarea name="comments" cols="30" rows="4"></textarea><br></td>
        </tr>
    </table>
   
      </div>
</br>
   <div><center>
  <input type="submit" name="submit">
 </center></div></div>
    </form>
       <?php
      if(isset($_POST['submit'])){
      $conn = mysqli_connect('localhost','root','');
     if (!$conn) {
    die("Connection failed: " . mysqli_error());
    } 
    echo "DB Connected successfully";
      mysqli_select_db("tool",$conn);    
    $sql="INSERT INTO  disease (Disease_id, Disease,SubDisease, Associated_Disease, Ethinicity,Source) 
VALUES           ('$_POST[Disease_ID]', '$_POST[Disease]','$_POST[SubDisease]', '$_POST[Associated_Disease]','$_POST[Ethinicity]', '$_POST[Source]')";
    mysqli_query($sql,$conn);
    mysqli_close($conn);
    }
    ?>
   </body>
    </html>
Martin
  • 22,212
  • 11
  • 70
  • 132
Steffi Ma
  • 70
  • 9
  • Hav you tried to read up [on similar](http://stackoverflow.com/questions/27487201/inserting-data-into-database-not-working?s=4|0.7157) [questions on](http://stackoverflow.com/questions/34019017/php-wont-insert-data-into-database?s=9|0.5349) [StackOverflow and](http://stackoverflow.com/questions/18554828/inserting-data-into-mysql-from-php?s=19|0.3918) [tried their](http://stackoverflow.com/questions/15728873/insert-data-into-mysql-database-from-android-app-changes-not-reflected-in-datab?s=25|0.3623) [**results**](http://php.net/manual/en/mysqli.query.php)? – Martin May 09 '16 at 13:31
  • That's an awesome way to literally insert `'$_POST[Disease_ID]','$_POST[Disease]','$_POST[SubDisease]','$_POST[Associated_Disease]','$_POST[Ethinicity]','$_POST[Source]'` into your databse – Alon Eitan May 09 '16 at 13:32
  • You are receiving error because of miss-use of variables in string. Use `{$_POST['Disease_ID']}` (also you are missing `'` for array keys – Justinas May 09 '16 at 13:33
  • Use isset() to check post value exist. Use $_POST['Disease_ID'] quotes in array. – RJParikh May 09 '16 at 13:37
  • @Justinas arrays keys do still work if strings are not in quotes. But it is not best practise by a long chalk... – Martin May 09 '16 at 13:38
  • @Martin Since when does it work? How than you get array key by constant? – Justinas May 09 '16 at 13:46
  • [read this qustion and answer](http://stackoverflow.com/questions/8276784/using-no-quotes-vs-single-quotes-vs-double-quotes-in-post-value), @Justinas . PHP assumes unfound constants are infact strings. – Martin May 09 '16 at 13:48
  • @Martin PHP will often just convert it to the string **and log a warning message**. So if you write dirty code with turned off errors, than yes, you can do it. But god save who will fix your code... – Justinas May 09 '16 at 13:51
  • @Justinas oh it's absolutely not the best way of writing code, but the point is that the unquoted `$_POST[array]` values inside the MySQL string are *not* a breaking error causing the failure of the code. They will throw up warning notices but still execute correctly. – Martin May 09 '16 at 13:53

3 Answers3

2

If you're ok with leaving yourself open to SQL injection and getting hacked, go ahead and follow this advice. If not, you better read up on prepared statements instead..

1) Unless your config file lists the database, you need to specify it in your constructor:

$conn = mysqli_connect('localhost','root','', 'myDatabaseName');

2) When using arrray indexes in a string you should wrap them in curlies:

$sql="INSERT INTO  disease(Disease_id,Disease,SubDisease,Associated_Disease,Ethinicity,Source) VALUES           ('{$_POST[Disease_ID]}','{$_POST[Disease]}','{$_POST[SubDisease]]','{$_POST[Associated_Disease]}','{$_POST[Ethinicity]}','{$_POST[Source]}')";
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • You are correct but your wording makes it sound like your answer encourages SQL injection, which is not so. Regardless of OPs approach to coding security, your answer stands for their *current* (albeit insecure) approach. – Martin May 09 '16 at 13:41
1

your post indexes are wrong you can not use your drop down title in that, you need to use value of your name attribute of input field so $_POST['Day'] instead of $_POST['Disease_ID'], use $_POST['DisDu'] instead of $_POST[Associated_Disease] and so on for other inputs.

DD77
  • 776
  • 2
  • 8
  • 25
1

1) Disease_ID should be an auto-incremental primary index column in your MySQL so should not be referenced directly by the HTML output. When inserting a row in the database this value will be self-generating and unique.

2) Check your syntax. Your error log should be mysqli_error($conn) <== you need to specify the connection variable. This goes for most actions using MySQLi procedural. Ask yourself how does the command know which database to apply the action to?

3) mysqli_query($sql,$conn); This is the primary cause of your issue.

The correct syntax is:

mysqli_query($conn,$sql);

Read the manual.

4) $conn = mysqli_connect('localhost','root',''); should also reference the correct database, again, simple stuff - read the manual!

So:

mysqli_connect('localhost','root','', 'tool');

And delete your mysqli_select_db reference in the code.

5) Add mysqli_error to your query insert so:

mysqli_query($conn,$sql) or die("error: ".mysqli_error($conn));

6) Secondary Cause - Your form submits data with the name attribute, buy all your form data seems to be subitted with the same name, so the data is not being received by the PHP code:

Example:

<form method="post">
<input value="whatever" name="myName">
</form>

And PHP recieves:

$_POST['myName'] = "whatever"; 

You need to update your whole HTML form with this in mind as currently your PHP is referencing value which do not exis and your HTML form is only posting a few unique values.

Martin
  • 22,212
  • 11
  • 70
  • 132