我正在使用 CodeIgniter 构建站点。这是我自己建立的第一个与数据库交互的站点。我在这个项目中使用 MySQL。如何判断数据在保存到数据库之前是否需要转义?
最佳答案
我建议您习惯于使用准备好的语句。特别是因为您不熟悉使用数据库。您越早开始使用这些,就越容易成为第二天性。
例如,当我开始使用数据库时,我并不知道准备好的语句。当我与他们接触时,我体验到了自己的固执。因为我已经习惯了另一种做事方式。现在,这可能不是您自己的性格交易,但无论哪种方式,尽快开始都没有坏处。
准备好的语句允许您在查询中使用占位符。然后可以通过将这些占位符绑定(bind)到占位符来用实际值替换这些占位符。这个绑定(bind)过程会自动转义值。
这是一个(简单的)PDO示例:
$db = new PDO( /* some database parameters */ );
$statement = $db->prepare( 'INSERT INTO table VALUES( :username, :password )' );
$statement->bindValue( ':username', $dirtyUsername );
$statement->bindValue( ':password', $dirtyPassword );
$result = $statement->execute();
// result checking ommited for brevity
PDO 和准备好的语句有更多的可能性。例如,您可以轻松地在循环中重用准备好的语句,如下所示:
$statement = $db->prepare( 'INSERT INTO table VALUES( :username, :password )' );
foreach( $users as $dirtyUser )
{
$statement->bindValue( ':username', $dirtyUser->username );
$statement->bindValue( ':password', $dirtyUser->password );
$result = $statement->execute();
// result checking ommited for brevity
}
或者将占位符绑定(bind)传递给执行方法,如下所示:
$statement = $db->prepare( 'INSERT INTO table VALUES( :username, :password )' );
$result = $statement->execute( array(
':username' => $dirtyUsername,
':password' => $dirtyPassword
) );
// result checking ommited for brevity
……等等,等等
关于php - 如何知道 MySQL 何时需要转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2619295/