2010-01-04 131 views
0

此代碼有什麼問題?我得到一個空數組。我將一個PHP變量傳遞給查詢,但它不起作用;當我給硬編碼的值時,查詢返回一個結果。將PHP變量傳遞給MySQL查詢

echo $sub1 = $examSubject[$i]; 
$subType = $examType[$i]; 
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'"); 
print_r($query->result_array()); 
+2

知道'$ sub1'中的內容可能會有所幫助 - 或者做整個查詢的迴應也可以;-) – 2010-01-04 13:17:24

+0

@pascal $ sub1是一個代表主題名稱的字符串 – Saranya 2010-01-04 13:21:28

+0

Martin提出的問題是:你會得到什麼回聲$ SUB1;並echo $查詢; – 2010-01-04 13:23:41

回答

5

查找「SQL注入」。

我不熟悉$this->db->query;你使用什麼數據庫驅動程序?轉義變量的語法因驅動程序而異。

這裏是一個PDO例如:

$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)"; 
$stmt = $pdo->prepare($preqry); 

$stmt->bindparam(1,$name); 
$stmt->execute(); 
+1

+1,將一個變量直接引用到查詢字符串中是一種壞習慣,它可以讓你陷入麻煩:) – 2010-01-04 15:36:12

1

沒有看到你的數據庫抽象層($這個 - > DB)的確,這裏是從例1的調整代碼the mysql_fetch_assoc documentation

<?php 
    // replace as you see fit 
    $sub1 = 'CS1'; 

    // replace localhost, mysql_user & mysql_password with the proper details 
    $conn = mysql_connect("localhost", "mysql_user", "mysql_password"); 
    if (!$conn) { 
    echo "Unable to connect to DB: " . mysql_error(); 
    exit; 
    } 

    if (!mysql_select_db("mydbname")) { 
    echo "Unable to select mydbname: " . mysql_error(); 
    exit; 
    } 

    $sql = 'SELECT `dSubject_id` '; 
    $sql .= 'FROM `tbl_subject_details` '; 
    $sql .= "WHERE `dSubjectCode` ='$sub1';"; 

    $result = mysql_query($sql); 

    if (!$result) { 
    echo "Could not successfully run query ($sql) from DB: " . mysql_error(); 
    exit; 
    } 

    if (mysql_num_rows($result) == 0) { 
    echo "No rows found, nothing to print so am exiting"; 
    exit; 
    } 

    while ($row = mysql_fetch_assoc($result)) { 
    echo $row['dSubject_id']; 
    } 

    mysql_free_result($result); 

?> 

設我知道輸出是什麼,我猜它會說:6

+0

@Saranya:任何結果? – 2010-01-05 11:07:38

1

它是你使用的CodeIgniter框架(從$ this-> db-> query語句)。如果是這樣,你爲什麼不嘗試:

$this->db->where('dSubjectCode',$sub1); 
$query = $this->db->get('tbl_subject_details'); 

如果這不起作用,你有一個錯誤在前面的代碼和$ SUB1是不是你希望它是什麼。