php 如何插入 PDO (sqllite3)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1176122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I insert into PDO (sqllite3)?
提问by kodai
I'm having a bit of trouble inserting into a sqlite3 database with pdo. You'll have to excuse my ignorance with PDO, it seems so foreign coming from Python's database interface.
我在使用 pdo 插入 sqlite3 数据库时遇到了一些麻烦。你必须原谅我对 PDO 的无知,它似乎来自 Python 的数据库接口。
So here's my problem. I have a simple insert:
所以这是我的问题。我有一个简单的插入:
$dbh = new PDO('sqlite:vets.db');
$count = $dbh->exec("INSERT INTO vets(name,email,clinic,streetname,citystatezip,link,phone,fax,animal,region,visible) VALUES ($name,$email,$clinic,$streetname,$citystatezip,$link,$phone,$fax,$animal,$region,$visible)");
$dbh = null;
I simply want to execute that SQL command on my database and be done with it. Though executing this script causes no errors, it never updates the database. I've tried all sorts of permissions on the database itself, even made it 777 but it doesn't make a difference.
我只想在我的数据库上执行该 SQL 命令并完成它。尽管执行此脚本不会导致任何错误,但它永远不会更新数据库。我已经尝试了对数据库本身的各种权限,甚至将其设为 777,但没有任何区别。
Could someone help me?
有人可以帮助我吗?
回答by Blixt
One of the great benefits of PDO is that you can create prepared statements. Here's some code from a PHP project of mine:
PDO 的一大好处是您可以创建准备好的语句。这是我的一个 PHP 项目中的一些代码:
$qry = $db->prepare(
'INSERT INTO twocents (path, name, message) VALUES (?, ?, ?)');
$qry->execute(array($path, $name, $message));
As you can see, I use ?where I want to insert a value, then I execute the query with an array of values that should be put in place of the question marks.
如您所见,我使用?要插入值的位置,然后使用应放置在问号处的值数组执行查询。
If you do this, your query will be much safer, and more likely to work (since a missing value would stop your query from working if you insert variables directly in the query like you do.)
如果你这样做,你的查询会更安全,更有可能工作(因为如果你像你一样直接在查询中插入变量,缺失值会阻止你的查询工作。)
回答by RaYell
You can have an error in your SQL query. You could print it and then try to execute it in some SQLite GUI interface like SQLite Database Browser.
您的 SQL 查询中可能有错误。您可以打印它,然后尝试在某些 SQLite GUI 界面(如SQLite Database Browser )中执行它。
// you can skip PDO part for now, because we know it doesn't work
// $dbh = new PDO('sqlite:vets.db');
$query = "INSERT INTO vets(name,email,clinic,streetname,citystatezip,link,phone,fax,animal,region,visible) VALUES ($name,$email,$clinic,$streetname,$citystatezip,$link,$phone,$fax,$animal,$region,$visible)";
echo $query;
// $count = $dbh->exec($query);
// $dbh = null;
I see that you are not wrapping your values in quotes, probably that's the source of the problem. Maybe some typos in table field names as well. All will come out once you actually see the query.
我看到您没有将您的值用引号括起来,这可能是问题的根源。也许表字段名称中也有一些拼写错误。一旦您真正看到查询,所有内容都会出现。

