如何在mysql查询中使用循环生成的php变量

时间:2017-04-10 11:42:10

标签: php mysql variables

我需要的帮助不大。请问如何将sql_query的PHP值“ $ filtr_zamestnanci_ID ”。代码在这里:

<?php  
if (isset($_POST["filtr_zamestnanci_ID"])) {
    for ($a = 0; $a < count($_POST["filtr_zamestnanci_ID"]); $a++) {
        $filtr_zamestnanci_ID .="AND companies_text_records_user_ID = '".$_POST["filtr_zamestnanci_ID"][$a]."'&nbsp;";
    }
}else {
    $filtr_zamestnanci_ID = "";
}

echo "filtr_zamestnanci_ID :".$filtr_zamestnanci_ID;

mysql_query("SET CHARACTER SET utf8"); 
$sql_1 =
    mysql_query("SELECT * FROM companies_text_records
        LEFT JOIN companies ON companies_text_records_company_ID = company_ID
        LEFT JOIN login_users ON user_id = companies_text_records_user_ID
        WHERE companies_text_records_relative_to = '0'
        '".$filtr_zamestnanci_ID."'
        ORDER BY companies_text_records_ID DESC");
?>

如果我没有循环传递它,一切都OK。但是循环输出根本不起作用。也许在“ $ filtr_zamestnanci_ID ”的格式中出现了什么?

2 个答案:

答案 0 :(得分:1)

尝试以下方法。还将解决您的SQL注入问题:

<?php
    $conn = new PDO("mysql:host=$hostname;dbname=$db_name;charset=utf8mb4", $db_username, $db_password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_POST["filtr_zamestnanci_ID"])) {
    for ($a = 0; $a < count($_POST["filtr_zamestnanci_ID"]); $a++) {
        $filtr_zamestnanci_ID = $_POST["filtr_zamestnanci_ID"][$a];

        $stmt = $conn->prepare("SELECT * FROM companies_text_records
                            LEFT JOIN companies ON companies_text_records_company_ID = company_ID
                            LEFT JOIN login_users ON user_id = companies_text_records_user_ID
                        WHERE companies_text_records_relative_to = '0'
                        AND companies_text_records_user_ID = :company_text_records_user_id
                        ORDER BY companies_text_records_ID DESC");

        if ($stmt->execute(array(':company_text_records_user_id' => $filtr_zamestnanci_ID))) {
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $someField = $row['columnFromDatabase'];
            }
            echo 'success';
        }
    }
}else {
    $filtr_zamestnanci_ID = "";
}
?>

答案 1 :(得分:0)

  

警告mysql_query,mysql_fetch_array,mysql_connect等..扩展在PHP 5.5.0中已弃用,并且已在PHP 7.0.0中删除。   相反,应该使用MySQLi或PDO_MySQL扩展。

1)在AND

之前留出空格
$filtr_zamestnanci_ID .=" AND companies_text_records_user_ID = '".$_POST["filtr_zamestnanci_ID"][$a]."'";

2)删除附加的单引号,以便在'".$filtr_zamestnanci_ID."'

子句中添加
"SELEC‌​T * FROM companies_text_records LEFT JOIN companies ON companies_text_records_company_ID = company_ID LEFT JOIN login_users ON user_id = companies_text_records_user_ID WHERE companies_text_records_relative_to = '0' ".$filtr_zamestnanci_ID." ORDER BY companies_text_records_ID DESC"