我是SQLite的新手,目前正在尝试将其用于项目。 我创建了一个函数,如果已经存在一个具有给定名称的行,则插入一个新行。 但是,我似乎无法从函数内部访问数据库变量。什么也没发生。
我的第一次尝试抛出错误:
$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);
我尝试将db-variable作为参数传递。该网站不再引发错误,但没有发生插入。 (是的,我在没有if子句的情况下尝试过它: - )
$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);
答案 0 :(得分:0)
未经测试,但您可以尝试这样的事情:
function newWH($name, $cap, $letDb)
{
$letResult = $letDb->query("SELECT COUNT(*) as count FROM warehouses WHERE name = " . $name);
$row = $letResult->fetchArray();
if ($row > 0) {
$letDb->query("INSERT INTO warehouses (name, cap) VALUES (" . $name. ", " . $cap . ")");
}
}
答案 1 :(得分:0)
$db
声明为全局 name
列为VARCHAR,因此您必须在SQL说明中用引号括起其值因此:
$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)
{
global $db;
$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);
name