tags:

views:

82

answers:

4

I am going to use a small SQLite database to store some data that my application will use.

I cant however get the syntax for inserting data into the DB using PHP to correctly work, below is the code that i am trying to run:

<?php
    $day = $_POST["form_Day"];
    $hour = $_POST["form_Hour"];
    $minute = $_POST["form_Minute"];
    $type = $_POST["form_Type"];
    $lane = $_POST["form_Lane"];

    try
    {
        $db = new PDO('sqlite:EVENTS.sqlite');
        $db->exec("INSERT INTO events (Day, Hour, Minute, Type, Lane) VALUES ($day, $hour, $minute, $type, $lane);");
        $db = NULL;
    }
    catch(PDOException $e)
    {
        print 'Exception : '.$e->getMessage();
    }
?>

I have successfully created a SQLite database file using some code that i wrote but i just cant seem to insert data into the database.

+2  A: 

You can't simply insert strings inside your query like that. Take a look at PDO::quote() and prepared statements.

Alexandre Jasmin
A: 

there's nothing syntactically wrong with this, unless one of the vars ($day, $hour, etc) returns an empty string.

$db->exec("INSERT INTO events (Day, Hour, Minute, Type, Lane) VALUES ($day, $hour, $minute, $type, $lane);");

having said that, i'd be more worried about sql injection because you're applying $_POST variables directly into an sql statement without validation.

stillstanding
A: 

You should explicitly commit transactions after the modifying DML statements (INSERT, DELETE, UPDATE) with COMMIT;.

newtover
A: 

You should rather use parametrized queries. Try this:

$db = new PDO('sqlite:EVENTS.sqlite');
$stmnt = $db->prepare("INSERT INTO events (Day, Hour, Minute, Type, Lane) VALUES (:day, :hour, :minute, :type, :lane);");
$stmnt->execute( array('day'=>$day,'hour'=>$hour, 'minute'=>$minute, 'type'=>$type, 'lane'=>$lane) );
$db = NULL;
My Other Me