Carlos Montanha
Carlos Montanha

Reputation: 31

PHP to sqlite3 - can't upload

I have been trying to make a project where I need to upload information to a sqlite3 database. For that I'm using simple PHP scripts.

I succeeded already uploading information from a PHP script to a database with something like this:

    <?php

    try
    {
    $db = new PDO('sqlite:mydatabase.db');

    $db->exec("INSERT INTO temps (zone,temperature) VALUES ('maia',77)");
    echo "Row Inserted\n";
    }
    catch(PDOException $e)
    {
            print $e->getMessage();
    }
    ?>

Now I am struggling to do the same with a script lie this:

<?php

        $data = htmlspecialchars($_GET["temp1"]);
        $file = "temps.txt";
        $current = file_get_contents($file);
        $current .= $data;
        file_put_contents($file, $current);

try
{
        $db = new PDO('sqlite:teste1.db');
        $db->exec('BEING;');
        $db->exec('INSERT INTO temps (temperature) VALUES ($temp1)');
        $db->exec('COMMIT;');
}
catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
}
?>

My table "temps" has a schema like this:

CREATE TABLE temps (temperature NUMERIC);

Is it because of the var type in the PHP since I declared it as numeric in the database? If so how can I solve that?

Appreciate all your ideas.

Thank you

Upvotes: 2

Views: 82

Answers (1)

VolkerK
VolkerK

Reputation: 96159

You might be interested in prepapred statements and (named|positional) parameters:

<?php
$temp1 = '1234';
try
{
    $db = new PDO('sqlite::memory:');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec('CREATE TABLE temps (temperature NUMERIC)');

    $stmt = $db->prepare('INSERT INTO temps (temperature) VALUES (?)');
    $stmt->execute( array($temp1) );
}
catch (PDOException $e) {
    echo $e->getMessage();
}

Upvotes: 1

Related Questions