1

I am trying to enter 5 variables into a MySQL database. Here is the code:

    foreach ($avail_t as $row) {
    $ava = explode("+",$row);
    $day = $ava[0];
    $from = $ava[1];
    $to = $ava[2];
    //echo $day." ".$from." ".$to;
    $query = "INSERT INTO availability (username, login_value, day, from, to) VALUES ('{$_SESSION['username']}', '{$_SESSION['login_value']}', '{$day}', '{$from}', '{$to}')";
    mysql_query($query);
}

When I uncomment that echo statement all variables print out just fine, but when I process the query it doesn't enter into the database. Weirdly, if I cut out $from and $to and just enter $day it will enter the day. When I put back the $from and $to nothing gets entered.

Do you see any problems with this code? Data type is integer in military time format 2100, 1300 etc. for $from and $to.

4

2 Answers 2

7

You are using from and to as a column name which are reserved keywords, escape them using backticks ` in your query

$query = "INSERT INTO availability (username, login_value, day, `from`, `to`) VALUES ('".$_SESSION['username']."', '".$_SESSION['login_value']."', '$day', '$from', '$to')";
Sign up to request clarification or add additional context in comments.

5 Comments

Need backticks for to as well
It's considered good practice to blindly surround all table/database names with backticks, be it a reserved word or not.
@MadaraUchiha I have never heard that before. I have heard it's better practice to not used reserved words.
Perfect! I actually just changed the names altogether to prevent any issues later down the line. Thank you!
@Arun that's what you should do, be sure you ignore reserved words henceforth
0

You can't use from or to, those are reserved words.

2 Comments

looks like he can just need to surrounded with `
This is frowned upon since it can lead to confusions like this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.