0

I have this code to send the data of 3 input fields for an id-number and 2 dates (2 selectors, one text field) to my database. All 3 columns are VARCHAR. I am using a form with method POST.

I get this error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 336

I do not have 336 lines in any of my files.

This is what PHP and SQL code I have in my file. I've been going through it for a long while now but can't seem to find where this syntax error lies. Any ideas?

<?php
//Fetches the id of the konsert selected.
$id = $_GET['id'];

//Create DB object
$db = new Database();

//Create query to fetch personel
$query = "SELECT * FROM funktionar";

//Run above query
$personel = $db->select($query);

//Fetch all from konsert matching the id
$query = "SELECT * FROM konsert WHERE konsertID=".$id;

//Run above query
$konsert = $db->select($query);

if(isset($_POST['submit'])) {
    //Assign variables
    $namn = mysqli_real_escape_string($db->link, $_POST['personalID']);
    $tidStart = mysqli_real_escape_string($db->link, $_POST['tidStart']);
    $tidSlut = mysqli_real_escape_string($db->link, $_POST['tidSlut']);

    //Simple validation
    if($namn == '' || $tidStart == '' || $tidSlut == ''){
        //Set error if any field is left empty
        $error = 'V&auml;nligen fyll i alla f&auml;lt.';
        } else {
        $query = "INSERT INTO sakerhet
            (personalID, tidStart, tidSlut)
            VALUES ('$namn', '$tidStart', '$tidSlut')";

        $insert_row = $db->insert($query);
    }
}
?>

EDIT: Have added the insert function:

public function insert($query) {
       $insert_row = $this->link->query($query) or die($this->link->error.__LINE__);

       //Validate insert
       if($insert_row) {
           header("Location: index.php?msg=".urlencode('Record Added'));
           exit();
       } else {
           die('Error : ('.$this->link->errno .') '.$this->link->error);
       }

   }
Zarkaylia
  • 61
  • 4
  • 13
  • Do you have any log to see what is arriving to your server? Plus are you using MySQL or SQL-Server? Remove the tags of products you don't use. – Cynical May 29 '16 at 19:01
  • @Cynical the OP use MariaDB .. is the same of mysql .. – ScaisEdge May 29 '16 at 19:10
  • Could you try `$query = "SELECT * FROM konsert WHERE konsertID=$id";` – Arulkumar May 29 '16 at 19:17
  • It's not complaining about a line in any of your files, it's complaining about a line in your SQL query – Mark Baker May 29 '16 at 19:25
  • Be careful! `$id` is subject to [SQL injection](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – EagleRainbow May 29 '16 at 19:27
  • Could you please show what `$db->insert($query)` exactly does? I find it bewildering that the error message talks about "line 336" of the SQL statement... No statement is even nearly that long here... – EagleRainbow May 29 '16 at 19:29
  • @EagleRainbow Curious, in what way is $id a risk? Good to know. And I'll add the insert function to the post. – Zarkaylia May 29 '16 at 20:32
  • @Cynical I use XAMPP, phpmyadmin, etc, and no I don't seem to have a log file for it. – Zarkaylia May 29 '16 at 20:32
  • @Arulkumar I've tried that, it returns nothing from the table. – Zarkaylia May 29 '16 at 20:32
  • Depending on how `$db->query` has been implemented, I would try to send along the value `"4711; TRUNCATE TABLE sakerhet;"`. Your query `$query = "SELECT * FROM konsert WHERE konsertID=".$id;` then suddenly would end up with `$query = "SELECT * FROM konsert WHERE konsertID=4711; TRUNCATE TABLE sakerhet;"`, which in fact consists of two queries - one, which returns what you want, and the other, which will cause you to lose all your data, as `mysql_query()` (for instance) just will execute both commands sequentially. You wouldn't be the first one getting hacked this way... – EagleRainbow May 29 '16 at 20:36
  • What is `$this->link` referring to? An instance of `mysqli`? – EagleRainbow May 29 '16 at 20:39
  • given that `$insert_row = $this->link->query($query) or die($this->link->error.__LINE__);`, I would assume that `336` simply is a concatenation of "line 3" (with which the error message ends) and the line of the current line where the error message is raised, i.e `36` -- there's no separator in the `die()` command... doah! – EagleRainbow May 29 '16 at 20:45
  • Just for the sake of error analysis, could you just add a "var_dump($query)" right in front of `$insert_row = $db->insert($query);` and post what's in there? – EagleRainbow May 29 '16 at 20:46
  • @EagleRainbow Ty, I'll have to look deeper into how to prevent such hacking. As for now, the insert function lies on rows 47-59 in a separate file, while the query sent to it lies on, indeed, row 36 in its file. I think that adding "var_dump($query)" resulting in nothing confirms the error lies before the query is even sent to the function? – Zarkaylia May 29 '16 at 20:55
  • The idea behind `var_dump($query)` is to verbatimly get, what is sent to the DB. Apparently, the DB doesn't like what we are sending. Given all the escape issues, I think it's good practice to see 1:1 what is getting sent to the DB. Perhaps this gives us the pivotal hint we all are looking for so desperately... – EagleRainbow May 29 '16 at 21:01
  • @EagleRainbow The DB is sent an person's ID number and two dates of the format "XXXX-XX-XX HH:MM". Does VARCHAR handle spaces between characters...? MAybe a stupid question but I'm grasping at anything here at this hour. – Zarkaylia May 29 '16 at 21:10
  • So, you get something like `INSERT INTO sakerhet (personalID, tidStart, tidSlut) VALUES ('4711', '2016-05-29 23:11', '2016-05-29 23:12')`, right? If `tidStart` and `tidSlut` are both typed `VARCHAR`, then the space inbetween there should not pose any problem at all... – EagleRainbow May 29 '16 at 21:12
  • What happens, if you verbatimely copy&paste that `INSERT` statement, which you just got and paste it in phpMyAdmin? Does the same error message get raised there as well? – EagleRainbow May 29 '16 at 21:13
  • @EagleRainbow Thank you, by narrowing it down like this I've lastly found that the 'personalID' column and its relation to a column 'namn' is not at all fetched from the database the way it should be from start and thus my code tries to send it to nothing. I need to join another column from another table. – Zarkaylia May 29 '16 at 21:23
  • Appreciating that we finally were able to catch that bug - so in short this means that MySQL wanted us to say that a column (or a value?) was not there? What a bad error message in that case! – EagleRainbow May 29 '16 at 21:25
  • @EagleRainbow A bad and very vague one indeed, I'd not call that a syntax error. That's a missing value or missing column. Pretty much sent me staring at the wrong thing for hours. Thank you for your help, I'll be adding what solved it once able. – Zarkaylia May 30 '16 at 08:01

1 Answers1

0

Final and working solution. This SQL error occured due to:

  • Missing table column. While the error was too vague to give this direct answer I put all input data into simple variables instead á "$selected = $_POST['name']" and echoed the variables á "echo $konsert;", etc, to check so the data was fetched properly from its form. Commenting out the query as I did.
  • Likely wrong use of either mysqli_real_escape_string or "->link->"? I do not work in sessions with this project as it's not required and won't go public so removing this will be alright for me.

Conclusion It wasn't as much a syntax error as the query having problems executing itself due to above. The syntax was correct.

Disclaimer This code is not 100% safe nor 100% done. The input fields are NOT sanitised and as was pointed out to me by @EagleRainbow it is not safe to use the "$id = $_GET['id'];".

Code

<?php
//Fetches the id of the konsert selected.
$id = $_GET['id'];

//Create DB object
$db = new Database();

//Create query to fetch personel
$query = "SELECT * FROM funktionar";

//Run above query
$personel = $db->select($query);

//Select all from table sakerhet
$query = "SELECT * FROM sakerhet";

//Run above query
$safety = $db->select($query);

//Fetch all from konsert matching the id
$query = "SELECT * FROM konsert WHERE konsertID=".$id;

//Run above query
$konsert = $db->select($query);

<?php
    if(isset($_POST['submit'])) {
        //Assign variables
        $selected = $_POST['safetyName'];
        $tidStart = $_POST['tidStart'];
        $tidSlut = $_POST['tidSlut'];
        $konsert = $id;

        //Simple validation
        if($selected == '' || $tidStart == '' || $tidSlut == ''){
            //Set error if any field is left empty
            $error = "V&auml;nligen fyll i alla f&auml;lt.";
            } else {
                $query = "INSERT INTO sakerhet (personalID, tidStart, tidSlut, konsertID) VALUES ('$selected', '$tidStart', '$tidSlut', '$konsert')";
                $insert_row = $db->insert($query);
        }
    }
?>

Code from database file

public function insert($query) {
       $insert_row = $this->link->query($query) or die($this->link->error.__LINE__);

       //Validate insert
       if($insert_row) {
           header("Location: index.php?msg=".urlencode('Record Added'));
           exit();
       } else {
           die('Error : ('.$this->link->errno .') '.$this->link->error);
       }

   }

Thanks for the help given.

Zarkaylia
  • 61
  • 4
  • 13