Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

PDO insert function error

Hello, I am having difficulties in running this code, it won't add the data from a HTML form inside a table, why is this not working?

function add(){
                    include 'con.php';
                        try{
                        $user=$_POST['user'];
                        $pass=md5($_POST['pass']);
                        $avatar=$_FILES["avatar"]["name"];
                        $mail=$_POST['mail'];
                        $priv='User';
                        $date="now()";
                            $con->query("
                                INSERT INTO users(user,pass,avatar,mail,priv,date)
                                VALUES('$user','$pass','$avatar','$mail','$priv','$date');
                            ");
                        }catch(Exception $e){
                            echo "Could not add user";
                            exit;
                        }
                    }

4 Answers

Deoward Kotze
Deoward Kotze
14,604 Points

Need to see your html for the form and your connection file since the problem might reside in one of those.

Html form:

<form method="post">
    User:<br>
    <input type="text" value="" name="user"/><br>
    Pass:<br>
    <input type="password" value="" name="pass"/><br>
    File:<br>
    <input type="file" enctype="multipart/form-data" value="" name="avatar"/><br>
    Mail:<br>
    <input type="mail" value="" name="mail"/><br>
    <input type="submit" value="Send file" name="submit"/>
</form>

Connection file:

try{
    $con = new PDO("mysql:host=localhost;dbname=mydb","myuser","mypass");
    echo "Succesfully connected to database";

}catch(Exception $e){
    echo "Could not load database";
}
Deoward Kotze
Deoward Kotze
14,604 Points

Ok first off - I would use require('con.php'); instead of include('con.php');

  1. Reason for this is that if it cannot find your connection file include will only produce a warning and continue executing the script which makes things harder to debug / require will produce a fatal error.

  2. Don't know if that's a typo but your connection file should start with <?php the sample you have starts with php only?

its a typo, it the script starts correctly