I'm new to SQLite and currently trying to use it for a project. I've created a function that inserts a new row if one with the given name doesn't exist already. However, I can't seem to access the database-variable from inside the function. Nothing is happening.
My first try throws an error:
$db = new SQLite3("name.db");
$db->exec("CREATE TABLE IF NOT EXISTS warehouses (id INTEGER PRIMARY KEY, name VARCHAR(255), adjacent_l INTEGER DEFAULT null, adjacent_r INTEGER DEFAULT null, chem_a INTEGER DEFAULT 0, chem_b INTEGER DEFAULT 0, chem_c INTEGER DEFAULT 0, cap INTEGER)");
function newWH($name, $cap)
{
$letResult = $db->query("SELECT * FROM warehouses WHERE name = " . $name);
$letArray = (array) $letResult;
if (empty($letArray)) {
$db->query("INSERT INTO warehouses (name, cap) VALUES (" . $name . ", " . $cap . ")");
}
}
newWH("wh1", 10);
I tried passing the db-variable as a parameter. The website no longer throws an error, but no inserts are happening. (And yes, I've tried it without the if-clause :-)
$db = new SQLite3("name.db");
$db->exec("CREATE TABLE IF NOT EXISTS warehouses (id INTEGER PRIMARY KEY, name VARCHAR(255), adjacent_l INTEGER DEFAULT null, adjacent_r INTEGER DEFAULT null, chem_a INTEGER DEFAULT 0, chem_b INTEGER DEFAULT 0, chem_c INTEGER DEFAULT 0, cap INTEGER)");
function newWH($name, $cap, $letDb)
{
$letResult = $letDb->query("SELECT * FROM warehouses WHERE name = " . $name);
$letArray = (array) $letResult;
if (empty($letArray)) {
$letDb->query("INSERT INTO warehouses (name, cap) VALUES (" . $name . ", " . $cap . ")");
}
}
newWH("wh1", 10, $db);