0

Trying to make connection between html form and sql database

I am new to coding and stuff. I have copied script and trying to figure them out.

the code works with wampp server, just doesn't work with real hostgator server. i know it could be from the hostgator's end that the script is not working. I'm just unable to to access the database, pass and username are absolutely correct.

my website: sqms.in

contact form: sqms.in/contactus.html

PHP CODE:

define('DB_NAME', 'contactus');
define('DB_USER', 'sqmsihv7_admin');
define('DB_PASSWORD', '*******');
define('DB_HOST', 'localhost:3306');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
   die('Could not connect: ' . mysql_error());
   }

  $db_selected = mysql_select_db(DB_NAME, $link);

  if (!$db_selected) {
  die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
  }

  $value = $_POST['name'];
  $value2 = $_POST['email'];
  $value3 = $_POST['gender'];
  $value4 = $_POST['message'];


  $sql = "INSERT INTO tb_cform (name, email, gender, message) VALUES  ('$value', '$value2', 
  '$value3', '$value4')";
  mysql_query($sql);

  mysql_close();

HTML CODE:

<div class="row">
                    <form action="connection2.php" method="post">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="name" class="sr-only">Email</label>
                                <input placeholder="Name" name="name" type="text" class="form-control input-lg">
                            </div>  
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="email" class="sr-only">Email</label>
                                <input placeholder="Email" name="email" type="text" class="form-control input-lg">
                            </div>  
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="gender" class="sr-only">Gender</label>
                                <select class="form-control input-lg" name="gender">
                                  <option>--Gender--</option>
                                  <option>Male</option>
                                  <option>Female</option>
                                </select>
                            </div>  
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="message" class="sr-only">Message</label>
                                <textarea placeholder="Message" name="message" class="form-control input-lg" rows="3"></textarea>
                            </div>  
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <input type="submit" class="btn btn-primary " value="Send">

                                <input type="reset" class="btn btn-outline  " value="Reset">
                            </div>  
                        </div>
                    </form> 
                </div>

strong text

KillerHawx
  • 41
  • 6
  • what is the error message and wher it come from? Web Console PHP Error Log? – Sysix Aug 12 '17 at 22:30
  • 4
    *"I have copied script and trying to figure them out."*: before copying a script, take care to the year it has been written. Coding practises are changing over the years, don't waste your time with a too old code. – Casimir et Hippolyte Aug 12 '17 at 22:31
  • 1
    May be the live server's PHP version is different than the local server, check this first. FYI, `mysql_*` functions are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. – Rajdeep Paul Aug 12 '17 at 22:31
  • Server: Localhost via UNIX socket Server type: Percona Server Server version: 5.6.34-79.1-log - Percona Server (GPL), Release 79.1, Revision 1c589f9 Protocol version: 10 User: sqmsihv7@localhost Server charset: UTF-8 Unicode (utf8) – KillerHawx Aug 12 '17 at 22:33
  • webserver: cpsrvd 11.58.0.50 Database client version: libmysql - 5.1.73 PHP extension: mysqli Documentation – KillerHawx Aug 12 '17 at 22:33
  • When your local environment isn't iso with your production one you are going into strange errors. I. advice you to use docker, it's a very simple and powerfull tool. You could check your server log and mysql configuration – Mcsky Aug 12 '17 at 22:34
  • Please refer to the above details^ and let me know if it should work. thank you – KillerHawx Aug 12 '17 at 22:34
  • 1
    *PHP extension: mysqli Documentation* indicates that your live server doesn't support `mysql_*` functions. Use [`mysqli`](http://php.net/manual/en/book.mysqli.php) or [`pdo`](http://php.net/manual/en/book.pdo.php) instead. [**And this is why you shouldn't use `mysql_*` functions**](https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). – Rajdeep Paul Aug 12 '17 at 22:37
  • so the code is correct I suppose and compatible with PHP server, could it be the host link? in my database its Server: localhost:3306 »Database: sqmsihv7_contactus »Table: tb_cform – KillerHawx Aug 12 '17 at 22:39
  • @RajdeepPaul , I literally have no knowledge of PHP, can you please provide me the exact line I should replace it with in my code? – KillerHawx Aug 12 '17 at 22:40
  • 1
    @KillerHawx I've already given you enough information in [this comment](https://stackoverflow.com/questions/45655461/html-form-to-php-server-access-denied#comment78269251_45655461). Go through the documentation, you are supposed to write the code by yourself. However, if you get stuck anywhere in between, feel free to ask your specific question on SO. – Rajdeep Paul Aug 12 '17 at 22:46
  • *"I literally have no knowledge of PHP"*: SO is for people that are able to understand the eventual answers, it isn't a code writing service. In other words, if you have no knowledge of PHP, start to learn PHP before asking. – Casimir et Hippolyte Aug 12 '17 at 22:46
  • Maybe debug the code a little bit. see first if the form works print our the $_POST["name"] and the other stuff , if they don't show up go to debuging the php itself – Frosty Aug 12 '17 at 22:49
  • You're **wide open** to SQL injection attacks. Use prepared/parameterized queries to avoid this entirely. **Do not use your script as-is.** – Brad Aug 12 '17 at 23:52

3 Answers3

0
<?php
define('DB_NAME', 'contactus');
define('DB_USER', 'sqmsihv7_admin');
define('DB_PASSWORD', '*******');
define('DB_HOST', 'localhost:3306');


// Create connection
$conn = new mysqli(DB_NAME, DB_USER, DB_PASSWORD, DB_HOST);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$value = $_POST['name'];
$value2 = $_POST['email'];
$value3 = $_POST['gender'];
$value4 = $_POST['message'];

$sql = "INSERT INTO tb_cform (name, email, gender, message) VALUES  ('$value', '$value2', 
  '$value3', '$value4')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Try this for your php file it should work just fine (If your form works correctly) and your Database exists

Dont forget to put your real DB_PASSWORD when you copy my code

Frosty
  • 299
  • 5
  • 31
  • thanks for not fixing the sql injection vulnerabilities, so i can hack him, though – hanshenrik Aug 12 '17 at 22:58
  • Oh yeah, because you are totally the hacker thats trying to get him. And you have all the banks under your control , get a life dude – Frosty Aug 12 '17 at 23:01
0

Since you are using hostgator as the hosting provider. Your MySQL database and username are always in the format : YOUR-HOSTGATOR-USERNAME_your-database, YOUR-HOSTGATOR-USERNAME_your-username

In the above code, just replace

define('DB_NAME', 'contactus');
define('DB_USER', 'sqmsihv7_admin');
define('DB_PASSWORD', '*******');
define('DB_HOST', 'localhost:3306');

with

define('DB_NAME', 'sqmsihv7_contactus');
define('DB_USER', 'sqmsihv7_admin');
define('DB_PASSWORD', '*******');
define('DB_HOST', 'localhost:3306');

as your username on hostgator is sqmsihv7

After this everything will work properly.

Ashutosh Kumar
  • 459
  • 3
  • 12
0

the code works with wampp server - this is bad, because the code should NOT work on any modern development setup, and indicates that you are still on PHP5. all new development should happen on PHP 7+ (as of writing, php 7.1.8 is optimal). so the first thing you should do, is to update your wampp server (link to wamp with php 7.1.7 is here: https://bitnami.com/redirect/to/153294/bitnami-wampstack-7.1.7-0-dev-windows-x64-installer.exe )

just doesn't work with real hostgator server - that's hopefully because the host server has been updated to php7 already. but somewhere, there is a php error log, you should find that log and check it in any case. (if phpinfo() don't say where it is, ask your hosters customer support)

you see, in PHP7, the mysql_ api is removed. (although there is a mysql_ backport for legacy code compatibility available ), and in PHP7 you must decide between the MySQLi api (which itself is very close to the mysql_ api), and PDO (my personal favorite).

your second problem, is that you don't escape your sql inputs, so you're vulnerable to hacker's SQL Injection attacks. for example, if a hacker sets the message to goodbye db'); DROP TABLE contactus; -- , the hacker will delete your entire database!

your code ported to PDO (which is both PHP5 and PHP7 compatible), and fixing the SQL injection vulnerabilities, would roughly look like this:

define('DB_NAME', 'contactus');
define('DB_USER', 'sqmsihv7_admin');
define('DB_PASSWORD', '*******');
define('DB_HOST', 'localhost');
define('DB_PORT',3306);

// $link = mysql_connect ( DB_HOST, DB_USER, DB_PASSWORD );
$db = new PDO ( 'mysql:host=' . DB_HOST . ';port='. DB_PORT .';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASSWORD, array (
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION 
) );
// if (! $link) {
// die ( 'Could not connect: ' . mysql_error () );
// }
// $db_selected = mysql_select_db ( DB_NAME, $link );
// if (! $db_selected) {
// die ( 'Can\'t use ' . DB_NAME . ': ' . mysql_error () );
// }

$value = $db->quote ( $_POST ['name'] );
$value2 = $db->quote ( $_POST ['email'] );
$value3 = $db->quote ( $_POST ['gender'] );
$value4 = $db->quote ( $_POST ['message'] );

$sql = "INSERT INTO tb_cform (name, email, gender, message) VALUES  ($value, $value2,
  $value3, $value4)";
$db->query ( $sql );
// mysql_query ( $sql );

// mysql_close ();

(note that i recommend using prepared statements instead of quoted strings, but learning that is just a google search away - an excellent tutorial explaining both prepared queries, and the difference between mysql_ and PDO, is here http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers )

edit: noticed that you specified the port in the host, that probably doesn't work with PDO, so i updated the code to use the port= parameter and a new DB_PORT define.

hanshenrik
  • 19,904
  • 4
  • 43
  • 89