2015-11-02 126 views
0

我正在創建一個簡單的自定義搜索表單。這種形式搜索表'oc_product',我在那裏創建了一個新的'gcode'列。我在其中一個產品的這一列中插入了一個示例數據。是否有必要在一個新的tpl文件中創建一個新的db/mysql連接,在php中創建,就像'information/contact'一樣。我稱之爲'gcode/gcode'。 我試過了,但無法從搜索結果中找到結果。它重定向到index.php。 我的代碼是:Opencart自定義mysql搜索表單

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="searchform"> 
    <input type="text" name="name"> 
    <input type="submit" name="submit" value="Search"> 
</form> 


if(isset($_POST['submit'])){ 
    if(isset($_GET['go'])){ 
    if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){ 
    $name=$_POST['name']; 
    //connect to the database 
    $db=mysql_connect ("localhost", "username_demo", "pwddemo123") or die ('I cannot connect to the database because: ' . mysql_error()); 
    //-select the database to use 
    $mydb=mysql_select_db("db_demo"); 
    //-query the database table 
    $sql="SELECT * FROM oc_product WHERE gcode LIKE '%" . $name . "%'"; 
    //-run the query against the mysql query function 
    $result=mysql_query($sql); 
    //-create while loop and loop through result set 
    while($row=mysql_fetch_array($result)){ 
      $gcode =$row['gcode']; 
    //-display the result of the array 
    echo '<span>'."This product is genuine".$gcode.'</span>'; 

    } 
    } 
    else{ 
    echo "<p>Please enter a search query</p>"; 
    } 
    } 
    } 

不限例如搜索的柱,並從列獲取數據。

+0

我想我不需要告訴你,你不應該再使用mysql_的東西了嗎?問題似乎與'if(isset($ _ GET ['go']))'...你已經在你的表單聲明中定義了'post',而不是'get'。嘗試只是消除這種情況 –

+1

是的胡利奧是正確的我刪除了isset函數,並保持它_POST,並表現良好。 –

回答

0

不太理解你的問題。你想從一列中獲取數據嗎?還可以使用mysql_fetch_assoc,而不是mysql_fetch_array 與$ _ POST 替換$ _GET此外,您的選擇是錯誤的說法,這樣做:

<? 
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%$name%'"; 
$result = mysql_query($sql); 
$results = mysql_num_rows($result); 
for($i=0; $i<$results; $i++) 
{ 
$row = mysql_fetch_assoc($result); 
$gcode = $row['gcode']; 
// Here list it the way you want 
echo $gcode.'<br>'; 
} 
?> 
+0

$ raw_results = mysql_query(「SELECT * FROM oc_product WHERE('gcode' LIKE'%」。$ query。「%')」)or die(mysql_error());我進一步修改了一下 –

0

,你需要創建一個模型或只需在搜索模型添加這個字段是由它搜索。我不確定這是否是您想要完成的任務,還需要確保清理請求並在發生SQL注入攻擊之前將其轉義。

+0

你試過了,但對我來說太複雜了,因爲我缺乏時間瞭解opencart搜索結構。然而,我做了一個自定義的tpl文件與控制器和數據庫抓取在正常的PHP搜索'喜歡'的SQL函數,所以atlast得到它的工作方式。 –