从数组重新提交搜索结果返回到具有隐藏字段的MySQL数据库

时间:2012-08-17 15:47:02

标签: php mysql arrays search

我在这里的第一篇文章,即使我是这个非常有用的网站的常客 -

我想知道是否有人可以帮助我解决以下问题:

我正在为我的公司用MySQL编写一个简单的股票检查解决方案,我仍然是新手但是学习。

我们有以下搜索表单,当输入产品的条形码时显示数据库的结果,我想要做的是在结果底部有一个按钮,显示“Checked OK”,重新提交info返回数据库,更新时间戳,并有一个隐藏字段将“状态”更改为已选中。

数据库名称是“stock” 表名是“main_stock” 这些领域是: ID curr_timestamp mastercategory 类别 product_desc 条码 串行 状态

每个搜索只提供一个结果,因为条形码是唯一的

我坚持的一点是如何将结果导入表单以便能够将它们重新提交回数据库

这仅供受保护网络内部使用,非常感谢任何帮助

由于

乔恩

    <?php



    $dbHost = 'localhost'; // localhost will be used in most cases

    // set these to your mysql database username and password.

    $dbUser = 'xxxxxxxx'; 
    $dbPass = 'xxxxxxx';
    $dbDatabase = 'stock'; // the database you put the table into.

    $con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL         Server. Error: " . mysql_error());
    mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}.         Error: " . mysql_error());

    // Set up our error check and result check array

    $error = array();
    $results = array();

    // First check if a form was submitted. 
    // Since this is a search we will use $_GET

    if (isset($_GET['search'])) {   
    $searchTerms = trim($_GET['search']);   
    $searchTerms = strip_tags($searchTerms); // remove any html/javascript.      

    if (strlen($searchTerms) < 2) {      
    $error[] = "Search terms must be longer than 2 characters.";   
    }else {      
    $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.   
    }      

    // If there are no errors, lets get the search going.   

    if (count($error) < 1) {      
    $searchSQL = "SELECT mastercategory, category, product_desc, barcode, serial FROM main_stock         WHERE ";            

    // grab the search types.      
    $types = array();      
    $types[] = isset($_GET['barcode'])?"`barcode` LIKE '%{$searchTermDB}%'":''; 
    $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not         checked)            

    if (count($types) < 1)         
    $types[] = "`barcode` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked                

    $andOr = isset($_GET['matchall'])?'AND':'OR';      
    $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `barcode`"; // order by title.      
    $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" .         mysql_error() . "<br />SQL Was: {$searchSQL}");            

    if (mysql_num_rows($searchResult) < 1) {         
    $error[] = "The scanned barcode {$searchTerms} is not in the database.";      
    }else {         
    $results = array(); // the result array         
    $i = 1;         
    while ($row = mysql_fetch_assoc($searchResult)) {            
    $results[] = "{$i}:Product Name&nbsp;:&nbsp;<br />&nbsp;&nbsp;{$row['product_desc']}        <br />Master Category&nbsp;:&nbsp;<br />&nbsp;&nbsp;{$row['mastercategory']}<br />Sub         Category&nbsp;:&nbsp;<br />&nbsp;&nbsp;{$row['category']}<br />Barcode&nbsp;:&nbsp;{$row['barcode']}        <br />Serial No.&nbsp;:&nbsp;{$row['serial']}";            
    $i++;         
    }      
    }   
    }
    }
    function removeEmpty($var) {   
    return (!empty($var)); 
    }?>

    <html>   

    <title>Search Form</title>   
    <BODY onLoad="document.forms.searchForm.search.focus()">  
    <form action="index.php">
  <center>
    <span class="formcentjc">
      <input type=submit value="Home" />
      </span>
  </center>
</form>  
    <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?>      

    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="GET" name="searchForm" class="cent">
    <onLoad="document.searchForm.search()">
    <table width="196" border="1">
     <tr>
        <th bgcolor="#D6D6D6" style="text-align: center" scope="col">Search For:</th>
      </tr>
      <tr style="text-align: center">
        <td class="cent1">
          <input name="search" type="text" onFocus="this.value='';" value="<?php echo isset        ($searchTerms)?htmlspecialchars($searchTerms):''; ?>" size="28" maxlength="15" />
          <span style="text-align: center"></span></td>
      </tr>
    </table>
    </form> 
    <p>
     <tr>
        <td bgcolor="#D6D6D6"><form action="addproduct.php">
          <center>
             <span class="formcentjc">
              <input type=submit value="Add New Product" />
              </span>
          </center>
        </form></td>
      </tr>
      <tr>
    </p>

    <?php 
    echo (count($results) > 0)?"SUCCESS: {$searchTerms} :<br /><br />" . implode("", $results):""; 
    ?>   
    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow!

这里的想法是从数据库中获取数据,并重新填充表单。当我构建这样的页面时,我通常在URL中有一个参数包含MySQL行的主键,我想抓住,就像这样mypage.php?id=37

如果$_GET['id']已设置且为数字,则我会运行如下查询:

$id = mysqli::real_escape_string($_GET['id']);
$data = mysqli::query("SELECT * FROM table WHERE id = '{$id}'");

//Check to see if we got any data back :)

然后,我们可以再次填充表单:

<input name="value1" type="hidden" value="<?php echo stripslashes($data['value1'])" />

再次从用户提交数据后,运行如下查询:

$id = mysqli::real_escape_string($_GET['id']);
$value1 = mysqli::real_escape_string($_POST['value1']);
$value2 = mysqli::real_escape_string($_POST['value2']);
mysqli::query("UPDATE table SET value1='{$value1}', value2='{$value2}' ... WHERE id = '{$id}' LIMIT 1");

修改

从我收集的信息中,详细信息页面上的按钮将提交(我猜测其产品名称)其中一个返回的产品返回数据库,以及搜索的时间和状态排序

当你遍历所获取的结果数组以向用户显示它们时,我会收集产品的名称并将其推送到这样的数组上:

$fetchedProducts = array();

while (/*Loop condition to loop through fetched results*/) {
  array_push($loopVariable['productName'], $fetchedProducts);

  //Build HTML to display results
}

//Insert into database
$products = mysqli::real_escape_string(json_encode($fetchedProducts));
$timestamp = strtotime("now");
$status = "some status";

mysqli::query("INSERT INTO searchRecords (
                  `id`, `products`, `timestamp`, `status`
               ) VALUES (
                  NULL, '{$products}', '{$timestamp}', '{$status}'
               )");

希望有所帮助。