我想建立一個類來從用戶輸入中定義的表中選擇記錄。如何將一組條件傳遞給select查詢類?
我的計劃是將一個讀取用戶輸入條件的類作爲數組讀取,因爲其他表具有不同數量的條件。因此我想要創建一個適用於所有人的課程。
主要想實現這樣的說法:
select * from table_name where condition1=value1 AND condition2=value2
其中一些條件變化取決於用戶輸入。
我所做的就是這個類:
class SelectQuery {
private $Error;
public $conn;
public $table;
public function __construct($conn){ //establish connection
$this->conn = $conn;
}
public function SelectData($table,$cols,array $conds){
$this->table = $table;
if($cols)
{
if($conds)
{
$i=0; $cond='';
foreach ($conds as $key => $value){
if($i==0)
{
$cond .= $key. '=' .$value;
}
else
{
$cond .= ' AND ' .$key. '=' .$value;
}
$i++;
}
$sql = 'SELECT '.$cols.' FROM '.$table.' WHERE '.$cond.'';
$stmt = oci_parse($this->conn, $sql);
oci_execute($stmt);
$rows = oci_fetch_all($stmt, $data, null, null, OCI_FETCHSTATEMENT_BY_COLUMN);
if($rows)
{
return $rows['0']['0'];
}
else
{
return NULL;
}
}
else
{
$sql = 'SELECT {$cols} FROM {$table}';
$stmt = oci_parse($this->conn, $sql);
oci_execute($stmt);
$rows = oci_fetch_all($stmt, $data, null, null, OCI_FETCHSTATEMENT_BY_COLUMN);
if($rows)
{
return $rows['0']['0'];
}
else
{
return NULL;
}
}
}
}
,這是數據是如何發送從形式:
$manager = new OracleConnectManager();
$conn = $manager->establishConnection(); //establish connection
if($conn){
$table = 'MAIN';
$cols= '*';
$conds = array(
'id_number' => $_POST['id_number'],
'firstname' => $_POST['firstname'],
'secondname' => $_POST['secondname'],
'thirdname' => $_POST['thirdname'],
'familyname' => $_POST['familyname'],
'department' => $_POST['department'],
);
$sel = new SelectQuery($conn);
$dth = $sel->SelectData($table,$cols,$conds);
echo $dth;
}
當我運行代碼我得到這個錯誤:
Warning: oci_execute(): ORA-00936: missing expression
(在SelectQuery
類,行:oci_execute($stmt)
; )
Warning: oci_fetch_all(): ORA-24374: define not done before fetch or execute and fetch
(在SelectQuery
類,線:$rows = oci_fetch_all($stmt, $data, null, null, OCI_FETCHSTATEMENT_BY_COLUMN);
)
並且沒有輸出。
任何幫助,將不勝感激。
感謝
簡單的方法是打印你的'$ sql'並取出實際形成的查詢。通常一個簡單的錯誤! –
你是對的!我不知道爲什麼我沒有想到這個XD ..聲明看起來像這樣: SELECT * FROM main WHERE id_number = 123456 AND name = value1 AND second = value2 AND family = value3 – Engineeroholic
所以我想最新的錯誤是引號值..'value1'而不是value1 – Engineeroholic