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

Why is this insert function not working?

Hello, I am having some issues with this function, it seems the query won't insert the data from the variables and I don't know why is this happening?

function insert(){
                $user = $_POST['user'];
                $pass = md5($_POST['pass']);
                $priv = "User";
                $mail = $_POST['mail'];
                $avatar = $_FILES['avatar']['name'];
                $date="now()";
                $submit = $_POST['submit'];


                $query = "INSERT INTO user(user,pass,priv,mail,avatar,date) VALUES(`$user`,`$pass`,`$priv`,`$mail`,`$avatar`,`$date`);";
                if($submit){
                    $res = mysqli_query($con,$query) or die(mysqli_error($con));
                }


            }

2 Answers

I notice two things. The first is that you're using backquotes ( ` ) around your values. In MySQL, you'll need to use single quotes ( ' ) for literal values and backquotes for table/field names. The other is that you're wrapping the now() function in quotes when it should be unquoted.

Try this:

$query = "INSERT INTO `user` (`user`, `pass`, `priv`, `mail`, `avatar`, `date`) VALUES ('$user', '$pass', '$priv', '$mail', '$avatar', now());";

I'm reffering in the script to the MySQL now() function which supposed to show the time and date of the user and not a function named now() from php

Correct, the MySQL NOW() function needs to appear unquoted in your query, as per my previous example.