【问题标题】:Resubmit Search Results From Array Back To MySQL DB with hidden fields使用隐藏字段将数组中的搜索结果重新提交回 MySQL 数据库
【发布时间】:2012-08-14 02:09:30
【问题描述】:

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

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

我正在用 PHP 和 MySQL 为我的公司编写一个简单的库存检查解决方案,我还是个新手,但正在学习。

我们有以下搜索表单,当输入产品的条形码时,它会显示来自数据库的结果,我想做的是在结果底部有一个按钮,上面写着“Checked OK”,它会重新提交信息返回数据库,更新时间戳,并有一个隐藏字段将“状态”更改为已检查。

数据库名称是“股票” 表名是“main_stock” 这些字段是: ID 当前时间戳 主类 类别 产品描述 条码 串行 状态

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

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

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

谢谢

乔恩

    <?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>

【问题讨论】:

    标签: php mysql arrays search


    【解决方案1】:

    欢迎来到 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}'
                   )");
    

    希望对您有所帮助。

    【讨论】:

    • 非常感谢您的帮助,我会试一试并回复
    • 没问题!希望对您有所帮助。
    • @Jon 如果您发现我的帖子有帮助,请考虑点击向上箭头为我的答案投票,并选择复选标记以接受答案。 :)
    • 你好,对不起,我有点卡住了,搜索页面有一个简单的输入框,输入条形码,按下提交,然后页面刷新到结果页面,我可以得到要传递到地址栏的条形码,但无法弄清楚如何获取 id 字段,因为这不是在初始页面上搜索的,id 字段是主索引。我看过重做搜索脚本,但我能找到的所有内容都将搜索到的内容传递到地址栏,而不是数据库中的字段,对不起,我想我自己搞糊涂了
    • @Jon 如果我理解正确,您已将表单中的所有值作为参数传递到 URL 中。您不一定需要提供id 参数(或任何您的数据库的主键),您可以简单地通过条形码搜索:SELECT * FROM table WHERE barcode = '{$myBarcode}。我回答你的问题了吗?
    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 2011-12-14
    • 2016-10-20
    • 2015-03-09
    • 2014-11-14
    • 1970-01-01
    • 2015-05-16
    • 2017-11-09
    相关资源
    最近更新 更多