需要一些帮助来理解下面的示例代码,以使用 odbc 连接数据库并检索数据。我确实理解 sql 查询..那不是问题
function getObject($query, $params, &$output)
{
global $connect;
$result = odbc_prepare($connect, $query);
odbc_execute($result, $params);
$j=0;
while($object = odbc_fetch_array($result))
{
$output[$j++] = $object;
}
}
function _getDeviceByIdentification($identification)
{
$query =
"SELECT * FROM Device"
." WHERE Identification = ?'".$identification."'";
$params = array(
$identification);
getObject($query, $params, $ret);
return $ret;
最佳答案
您的查询不正确。不要在查询中传递值,这就是占位符 ?
的用途。
function _getDeviceByIdentification($identification) {
$query = "SELECT * FROM Device WHERE Identification = ?";
$params = array($identification);
getObject($query, $params, $ret);
return $ret;
驱动程序将占位符 ?
与值(无论 $identification
包含什么)交换,并转义任何特殊字符。
例如,假设您有 $identification = "olde' iphone";
。直接将其传递给查询:
$query ="SELECT * FROM Device WHERE Identification = '$identification'";
会产生错误的查询,因为它的结果是:
SELECT * FROM Device WHERE Identification = 'olde' iphone';
^ string closed, the rest of the query is unexpected
但是,当驱动程序看到 '
时,它就知道要避开它。
SELECT * FROM Device WHERE Identification = 'olde\' iphone';
因此 '
不再是封装字符。
$params = array($identification);
创建一个映射到占位符的术语数组(它们按照它们在数组中出现的顺序进行映射,并且按照在数组中出现的顺序进行映射)询问)。如果您按照代码执行,您可以看到该数组最终在 http://php.net/manual/en/function.odbc-execute.php 中使用。 (这实际上是进行绑定(bind)的)。
关于php - 检索和保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47286773/