我如何将变量放在mysql查询中?

时间:2015-05-29 03:40:50

标签: mysql

我有两个这样的变量

$date1 = $_POST['f_date1'];
$date2 = $_POST['f_date2'];

这是把它放进去的正确方法吗?

$sql = "SELECT location, COUNT(*) as Referrals,
        SUM(CASE WHEN leadstatus = 'Hired' THEN 1 ELSE 0 END) as Hired,
        SUM(CASE WHEN leadstatus = 'Failed' THEN 1 ELSE 0 END) as Failed
        FROM vtiger_leadscf
        LEFT JOIN vtiger_leaddetails ON vtiger_leadscf.leadid = vtiger_leaddetails.leadid
        WHERE location > '' AND (date_table BETWEEN '$date1' AND '$date2')
        GROUP BY location 
        ORDER BY Referrals DESC";

2 个答案:

答案 0 :(得分:1)

执行此操作的方式取决于您使用mysql的接口。

如果您使用(旧的和已弃用的)mysql_*界面(您不应该),那么在最小,在使用变量之前,您需要逃脱他们使用mysql_real_escape_string()

例如:

$date1 = mysql_real_escape_string($_POST['f_date1']);
$date2 = mysql_real_escape_string($_POST['f_date2']);

之后是的,您的查询结构很好(对于这种方法,您不应该使用它)。

理想情况下,您需要使用PDOmysqli,两者都支持预备语句。这个例子是PDO,只是因为。

$pdo = new PDO('mysql:host=localhost;dbname=whatever', 'username', 'password');

$stmt = $pdo->prepare("SELECT location, COUNT(*) as Referrals,
        SUM(CASE WHEN leadstatus = 'Hired' THEN 1 ELSE 0 END) as Hired,
        SUM(CASE WHEN leadstatus = 'Failed' THEN 1 ELSE 0 END) as Failed
        FROM vtiger_leadscf
        LEFT JOIN vtiger_leaddetails ON vtiger_leadscf.leadid = vtiger_leaddetails.leadid
        WHERE location > '' AND (date_table BETWEEN :startDate AND :endDate)
        GROUP BY location 
        ORDER BY Referrals DESC");

$stmt->execute(array(
  'startDate' => $date1,
  'endDate' => $date2
));

请在查询中注意使用:startDate:endDate。那些是由传递给$stmt->execute的关联数组填充的占位符。准备好的语句是首选,因为它们可以防止在将简单的值连接到查询中时可能发生的肮脏(查找:sql注入)。

mysqli_接口与不推荐使用的mysql_接口更相似,但它也支持预准备语句。

mysqli方法:

$mysqli = new mysqli('localhost', 'username', 'password', 'db');

$stmt = $mysqli->prepare("SELECT location, COUNT(*) as Referrals,
            SUM(CASE WHEN leadstatus = 'Hired' THEN 1 ELSE 0 END) as Hired,
            SUM(CASE WHEN leadstatus = 'Failed' THEN 1 ELSE 0 END) as Failed
            FROM vtiger_leadscf
            LEFT JOIN vtiger_leaddetails ON vtiger_leadscf.leadid = vtiger_leaddetails.leadid
            WHERE location > '' AND (date_table BETWEEN ? AND ?)
            GROUP BY location 
            ORDER BY Referrals DESC");

$stmt->bind_param("ss", $date1, $date2);

$stmt->execute();

注意关键区别在于使用?作为占位符(pdo也支持这个,我只是更喜欢命名占位符),以及绑定变量的方式。 "ss"指定'类型'被约束的价值。

我的个人偏好是针对PDO,纯粹是因为我更喜欢使用数组参数进行execute调用。

答案 1 :(得分:0)

这样:

$sql = "SELECT location, COUNT(*) as Referrals,
        SUM(CASE WHEN leadstatus = 'Hired' THEN 1 ELSE 0 END) as Hired,
        SUM(CASE WHEN leadstatus = 'Failed' THEN 1 ELSE 0 END) as Failed
        FROM vtiger_leadscf
        LEFT JOIN vtiger_leaddetails ON vtiger_leadscf.leadid = vtiger_leaddetails.leadid
        WHERE location > '' AND (date_table BETWEEN '" . $date1 . "' AND '" . $date2 . "')
        GROUP BY location 
        ORDER BY Referrals DESC";