-1

Hello I am trying to use phpmyadmin and connect to my database. I did once before but I have never applied styles to the text boxes so I don't know if its right. For some reason I get an error message I told it to say if it fails to connect. I can't figure out why its not connecting. I'm using MAMP server Port: PHP 5.6.21

Here is my PHP code:

<?php
if($_POST['formSubmit'] == "Submit") {
    $errorMessage = "";

    if(empty($_POST['formName'])) {
        $errorMessage .= "<li>You need to enter your name</li>";
    }
    if(empty($_POST['formEmail'])) {
        $errorMessage .= "<li>You need to enter your email</li>";
    }
    if(empty($_POST['formSubject'])) {
        $errorMessage .= "<li>Please enter a subject.</li>";
    }
    if(empty($_POST['formComment'])) {
        $errorMessage .= "<li>Please enter your question.</li>";
    }

    $varname = $_POST['formName'];
    $varemail = $_POST['formEmail'];
    $varsubject = $_POST['formSubject'];
    $varcomment = $_POST['formComment'];

    if(empty($errorMessage)) {
        $db = mysql_connect("localhost","root","root");
        if(!$db) die("Error connecting to MySQL database.");
        mysql_select_db("three_cats_database" ,$db);

        $sql = "INSERT INTO contact_form (name, email, subject, comment) VALUES (".
        PrepSQL($varname) . ", " .
        PrepSQL($varemail) . ", " .
        PrepSQL($varsubject) . "," .
        PrepSQL($varcomment) . ") ";
        mysql_query($sql);

        header("Location: thankyou.php");
        exit();
    }
}

// function: PrepSQL()
// use stripslashes and mysql_real_escape_string PHP functions
// to sanitize a string for use in an SQL query
//
// also puts single quotes around the string
//
function PrepSQL($value)
{
    // Stripslashes
    if(get_magic_quotes_gpc()) {
        $value = stripslashes($value);
    }

    // Quote
    $value = "'" . mysql_real_escape_string($value) . "'";

    return($value);
}
?>

Here is my HTML:

<p>Please fill out this form completely to contact us with any concerns or suggestions.</p><br>
    <div class="imgbg"><div class="img">
    <!-- FORM IS HERE -->
      <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
      <div class="contact-form margin-top">

        <label for='formName'><span>Name:</span>
        <input type="text" class="input_text" name="formName" id="name" maxlength="50" value="<?=$varname;?>"/>
        </label>

        <label for='formEmail'><span>Email:</span>
        <input type="text" class="input_text" name="formEmail" id="email" maxlength="50" value="<?=$varemail;?>"/>
        </label>

        <label for='formSubject'><span>Subject:</span>
        <input type="text" class="input_text" name="formSubject" id="subject" maxlength="50" value="<?=$varsubject;?>"/>
        </label>

        <label><span>Comment</span>
        <textarea class="message" name="formComment" id="feedback"><?php echo htmlspecialchars($varcomment);?></textarea>
        </label>

        <input type="submit" class="button" name="formSubmit" value="Submit" />
        </label>
      </div>
    </form>

And last a picture of my database setup for proof of names enter image description here

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Brittney
  • 31
  • 2
  • 1
    Some sensible code indentation would be a good idea. It help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](http://www.php-fig.org/psr/psr-2/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Aug 02 '16 at 23:14
  • Please dont use [the `mysql_` database extension](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), it is deprecated (gone for ever in PHP7) Specially if you are just learning PHP, spend your energies learning the `PDO` database extensions. [Start here](http://php.net/manual/en/book.pdo.php) its really pretty easy – RiggsFolly Aug 02 '16 at 23:16
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared statement and parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Aug 02 '16 at 23:17
  • 2
    99% of that code has noting to do with a connection error, nor does phpmyadmin, you need the actual error, not yours –  Aug 02 '16 at 23:17
  • CSS / stylesheets also have nothing at all to do with making database connections. – Stephen P Aug 02 '16 at 23:18
  • 1
    As was sugested in your last question **You are wasting your time** with this tutorial. Throw it away and find one that uses the `PDO` or `mysqli_` database connection API's – RiggsFolly Aug 02 '16 at 23:22
  • after each of the following steps -- connecting, selecting a db, running a query -- do `if(mysql_errno()) die(mysql_error())` so we can see your error details. – BeetleJuice Aug 02 '16 at 23:23
  • Hiya! As a few others have mentioned, the mysql_* functions are deprecated. You can, as @RiggsFolly said, use PDO, but if you don't want to learn something completely different, mysqli is very similar to mysql_* in terms of function names and parameters, so it may be easier to learn mysqli. (They both have some advantages and disadvantages; read here:http://code.tutsplus.com/tutorials/pdo-vs-mysqli-which-should-you-use--net-24059 (It's worth teading the comments too)) Good Luck! – M. Salman Khan Aug 02 '16 at 23:25
  • Brittney, if the MySQL_ API isn't available for you to use, then error reporting may shed some light on this http://php.net/manual/en/function.error-reporting.php - You may need to resort to using either the MySQLi_ or PDO API. Also make sure that the credentials are correct and (the user is) granted the right privileges. – Funk Forty Niner Aug 02 '16 at 23:26
  • Also, just to make sure, is your password for root actually root, or is that a typo? (Most people will replace their actual password with the string "password" when posting on SO) – M. Salman Khan Aug 02 '16 at 23:33

2 Answers2

-1

Here is the code that you are having a problem with. Hope this helps. I made comments explaining what was happening throughout the code so if you want to go ahead and read them, that would make you understand a tad bit better. Hope this helps.

if($_POST['formSubmit'] == "Submit") {
    $errorMessage = "";
    if(empty($_POST['formName'])) {
        $errorMessage .= "<li>You need to enter your name</li>";
    }
    if(empty($_POST['formEmail'])) {
        $errorMessage .= "<li>You need to enter your email</li>";
    } 
    if(empty($_POST['formSubject'])) {
        $errorMessage .= "<li>Please enter a subject.</li>";
    } 
    if(empty($_POST['formComment'])) {
        $errorMessage .= "<li>Please enter your question.</li>";
    }

    $varname = $_POST['formName'];
    $varemail = $_POST['formEmail'];
    $varsubject = $_POST['formSubject'];
    $varcomment = $_POST['formComment'];

    if(empty($errorMessage)) {
        try 
        { 
           // I used PDO because I prefer it over mysqli
            $db = new PDO('mysql:host=localhost:3306;dbname=three_cats_database, root, root');
        }
        catch(PDOException $e)
        {
            die('Unable to connect to database');
        }
        // Here is the sql statement that you provided.
        $sql = "INSERT INTO contact_form (name, email, subject, comment) 
            VALUES (?,?,?,?)";
        // Prepare helps with sql injections ect. It is still not completely hacker proof.
        $stmt = $db->prepare($sql);
        // Each question mark (?) means they increment from 1-4 in this case.
        $stmt->bindValue(1, $varname, PDO::PARAM_STR);
        $stmt->bindValue(2, $varemail, PDO::PARAM_STR);
        $stmt->bindValue(3, $varsubject, PDO::PARAM_STR);
        $stmt->bindValue(4, $varcomment, PDO::PARAM_STR);
        //If statement to check if the sql command went through.This is also good for error checking.  
        if($stmt->execute())
        {
            header("Location: thankyou.php");
        }
        else 
        {
            // There was an error in the statement
        }
    }
}
Teddy Codes
  • 489
  • 4
  • 14
-2

Edit this line to get more informations on your error :

if(!$db) die("Error connecting to MySQL database.");

can become :

if(!$db) die("Error connecting to MySQL database : ".mysql_error($db));

You will see more information when crashing :)

Note : create a user for your table, it's better to never write root password in your php files

technico
  • 1,192
  • 1
  • 12
  • 22
  • 2
    this is a comment, not an answer –  Aug 02 '16 at 23:18
  • *"You will see more information when crashing :)"* - @Dagon seems like crashing is a fun thing there. – Funk Forty Niner Aug 02 '16 at 23:24
  • I think it is actually the better answer to give, and should be posted as an answer. As mysql_connect errors are simple, the complete error message is the only help that the OP need, as other readers in the future. How to know comment / answer ? – technico Aug 02 '16 at 23:33
  • I got an error saying "Can't connect to MySQL server on 'localhost' (10061)" – Brittney Aug 02 '16 at 23:44
  • The number shown is enough to find more info : http://stackoverflow.com/questions/119008/cant-connect-to-mysql-server-on-localhost-10061 @Fred : Errors are fun in test environnement :) – technico Aug 02 '16 at 23:50
  • *That's the spirit!* - Not my downvote btw. ;-) Just so you know; I'm the "nicer guy" here hehe. – Funk Forty Niner Aug 02 '16 at 23:54
  • Ok good as new! I went through MAMP and changed my ports and now it works. This is not a major site project or anything, I'm just trying to teach myself. I know I got a lot to learn so thanks for being patient with me. I can make some awesome web graphics but coding is a new ball game to me. I will eventually change it to PHP 7 but this is just where I landed on when trying to learn PHP. – Brittney Aug 03 '16 at 00:04
  • 1
    Nice, you were quick :) About the mysqli stuff, you should really go there, there is no need to change your PHP version or whatever. Just add a "i" after your mysql functions. Only a few mysqli functions need to change the order of the parameters, nothing big. Please accept answer so i will be happy (and Dagon not :p) – technico Aug 03 '16 at 00:05