使用PDO创建mysql查询函数,不会插入行
试图掌握如何使用 PDO,并且我正在使用一些预制函数来使事情在我想要执行查询时变得更简单。第一个连接,第二个运行查询。
不幸的是,它不允许我使用 dbquery() 插入行。 SELECT 工作正常,只是似乎无法让其他任何东西工作。
这是代码:
function dbConnect()
{
global $dbh;
$dbInfo['database_target'] = "localhost";
$dbInfo['database_name'] = "mysqltester";
$dbInfo['username'] = "root";
$dbInfo['password'] = "password";
$dbConnString = "mysql:host=" . $dbInfo['database_target'] . "; dbname=" . $dbInfo['database_name'];
$dbh = new PDO($dbConnString, $dbInfo['username'], $dbInfo['password']);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = $dbh->errorInfo();
if($error[0] != "")
{
print "<p>DATABASE CONNECTION ERROR:</p>";
print_r($error);
}
}
function dbQuery($queryString)
{
global $dbh;
$query = $dbh->query($queryString);
$i = 0;
foreach ($query as $query2)
{
$queryReturn[$i] = $query2;
$i++;
}
if($i > 1)
{
return $queryReturn;
}
else
{
return $queryReturn[0];
}
}
Trying to get a grasp of using PDO, and I'm using some pre-made functions to make things simpler for when I want to do a query. First one connects, second runs the query.
Unfortunately it won't let me INSERT rows using dbquery(). SELECT works fine, just can't seem to get anything else to work.
Here's the code:
function dbConnect()
{
global $dbh;
$dbInfo['database_target'] = "localhost";
$dbInfo['database_name'] = "mysqltester";
$dbInfo['username'] = "root";
$dbInfo['password'] = "password";
$dbConnString = "mysql:host=" . $dbInfo['database_target'] . "; dbname=" . $dbInfo['database_name'];
$dbh = new PDO($dbConnString, $dbInfo['username'], $dbInfo['password']);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = $dbh->errorInfo();
if($error[0] != "")
{
print "<p>DATABASE CONNECTION ERROR:</p>";
print_r($error);
}
}
function dbQuery($queryString)
{
global $dbh;
$query = $dbh->query($queryString);
$i = 0;
foreach ($query as $query2)
{
$queryReturn[$i] = $query2;
$i++;
}
if($i > 1)
{
return $queryReturn;
}
else
{
return $queryReturn[0];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PDO::query 仅适用于返回结果集的查询(例如
SELECT
)对于插入/更新/删除,请参见PDO ::exec
如果您要将用户提供的数据插入到 DBMS 中,我强烈建议您使用 PDO 的预准备语句功能来提供自动转义以防止 SQL 注入。
例如,
请参阅 PDO::prepare 和 PDOStatement::execute
PDO::query Only works with queries that return a result set (e.g.
SELECT
)For INSERT/UPDATE/DELETE see PDO::exec
If you are going to be inserting user provided data into your DBMS I strongly suggest using the prepared statement functionality of PDO to provide automatic escaping to prevent SQL injection.
e.g.
See PDO::prepare and PDOStatement::execute