使用 PHP 和 SQLite
我将使用一个小型 SQLite 数据库来存储我的应用程序将使用的一些数据。
然而,我无法获得使用 PHP 将数据插入数据库的语法来正确工作,下面是我尝试运行的代码:
<?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();
}
?>
我已经使用我编写的一些代码成功创建了 SQLite 数据库文件,但我似乎无法插入数据存入数据库。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能像这样简单地在查询中插入字符串。看一下 PDO::quote() 和 准备好的语句。
You can't simply insert strings inside your query like that. Take a look at PDO::quote() and prepared statements.
这在语法上没有任何错误,除非其中一个变量($day、$hour 等)返回空字符串。
$db->exec("INSERT INTO events (Day, Hour, Minute, Type, Lane) VALUES ($day, $hour, $minute, $type, $lane);");
话虽如此,我更担心 sql 注入,因为您将 $_POST 变量直接应用到 sql 语句中而不进行验证。
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.
您应该使用参数化查询。试试这个:
You should rather use parametrized queries. Try this:
您应该在修改 DML 语句(INSERT、DELETE、UPDATE)后使用
COMMIT;
显式提交事务。You should explicitly commit transactions after the modifying DML statements (INSERT, DELETE, UPDATE) with
COMMIT;
.