问题描述
我正在尝试将数据插入服务器上的数据库中.
I'm trying to insert data into a database that I have on my server.
要连接到我的数据库,我需要以下代码:
To connect to my database I have the following code:
<?php
$host = "/homes/49/jc192699/public_html/dbase/";
$database = "EduPro.db";
$dbhandle = new PDO("sqlite:".$host.$database);
try {
$dbhandle = new PDO("sqlite:".$host.$database);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
一切正常!我已经将其包含在我的代码中,所以这不是问题.
and this all works fine! I have included this into my code so that is not the issue.
这是我用于将数据插入数据库的代码:
Here is my code for inserting data into the database:
<?php
$sql = "INSERT INTO USERS (`userName`, `password`) VALUES (`test, `testy`)";
if ( $fetched = $dbhandle->query($sql)){
$fetched->execute(PDO::FETCH_BOTH);
echo "Success!";
}
else {
echo "Fail.";
}
?>
由于某种原因,它没有将数据插入数据库.我知道SQL语句是100%正确的,因为我已经在其他地方对其进行了测试.
It is not inserting the data into the database for some reason. I know that the SQL statement is 100% correct as I have tested it elsewhere.
有人可以帮助我吗?
推荐答案
您正在打开两个数据库连接.将您的代码更改为
you are opening two database connection. change your code to
$host = "/homes/49/jc192699/public_html/dbase/";
$database = "EduPro.db";
try {
$conn = new PDO("sqlite:".$host.$database);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
您不应在查询中使用反引号,而应使用单引号.并且该列也不应使用任何引号.
you should not use backquote instead using single quote in your query. and also column should not have any quotes.
try {
$sql = "INSERT INTO USERS (userName, password) VALUES ('test', 'testy')";
$sth = $conn->query($sql);
} catch(PDOException $e) {
echo $e->getMessage();
}
要获取使用此记录所需的记录
to fetch the records you need to use this
try {
$sth = $conn->query('SELECT * FROM USERS');
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
//$rows contains the fetched records in an associative array
var_dump($rows);
} catch(PDOException $e) {
echo $e->getMessage();
}
在此处详细了解PDO http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
learn more about PDO here http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
这篇关于使用PDO插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!