簡體   English   中英

如何為select語句編寫sql查詢

[英]how to write sql query for select statement

$dep=$_SESSION['dep'];
$type="DON’T DO’S";
$res=  mysql_query("select * from treatment where treatment_dep='$dep' and treatment_type='$type'");
while($res1=  mysql_fetch_array($res)){ 
    echo $res1['treatment_treatment'];
}

僅當我從查詢中刪除“ and treatment_type ='$ type'”時,此查詢才有效。 這是因為$ type包含單引號。

如何編寫查詢來解決此類問題。

這將幫助您檢查錯誤。

   // Perform Query
    $result = mysql_query($query);

    // Check result
    // This shows the actual query sent to MySQL, and the error. Useful for debugging.
    if (!$result) {
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $query;
        die($message);
    }
$dep=$_SESSION['dep'];
$type="DON’T DO’S";

//Sanitize it for SQL as follows
$type = str_replace("'", "''", trim($type));
//Sanitization Complete

$res=  mysql_query("select * from treatment where treatment_dep='$dep' and treatment_type='$type'");
while($res1=  mysql_fetch_array($res)){ 
    echo $res1['treatment_treatment'];
}

嘗試將變量中的引號字符更改為\\',如下所示:

$type = "DON\'T DO\'S";

如果您需要對動態數據執行此操作,則可以使用

$type = strtr($type, "'", "\'");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM