首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >PHP MySQL单页多表单多提交

PHP MySQL单页多表单多提交
EN

Stack Overflow用户
提问于 2012-03-07 05:38:44
回答 3查看 6.1K关注 0票数 0

我正在尝试过滤,使用一个表单来过滤数据库,然后提供一种方法来更新过滤后的数据。我可能做的不是最好的方法,但它已经很接近工作了。问题似乎是,当我按下“更新”按钮时,一些变量被清除;计数和ID。

我已经通过将count设置为会话变量来修复它,但是没有办法通过ID来做到这一点。我不确定为什么count会被擦除,所以如果有人能告诉我,我将不胜感激。

我的代码的更新部分在没有过滤器部分的情况下工作得很好,同样,问题是id变量是空的。我已经测试了所有其他变量,并在update语句中添加了一个常量for ID用于测试。这是我的代码。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?php
session_start();
?>

<?php
$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name="inventory"; // Database name 
$tbl_name="computers"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 

mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form 
$school=$_POST['school'];
$make=$_POST['make'];
$model=$_POST['model'];
$barcode=$_POST['barcode'];
$location=$_POST['location'];
?>

    <?php
    include 'nav-bar.php';
    ?>

    <h2 align="center">Filter Computers</h2>
    <form name="form" method="post" style="margin: 0; text-align: center;">
    <p><label>School Name:</label><input type="text" name="school" size="8" id="school" tabindex="1"</p>
    <p><label>Make:</label><input type="text" name="make" size="25" id="make" tabindex="1"</p>
    <p><label>Model:</label><input type="text" name="model" size="25" id="model" tabindex="1"</p>
    <p><label>Barcode:</label><input type="text" name="barcode" size="12" id="barcode" tabindex="1"</p>
    <p><label>Location:</label><input type="text" name="location" size="25" id="location" tabindex="1"</p>
    <p><label>Serial:</label><input type="text" name="serial" size="25" id="location" tabindex="1"</p>
    <p><label>Date Acquired yyyy-dd-mm:</label><input type="text" name="date" size="8" id="location" tabindex="1"</p>
    <p><label>Processor:</label><input type="text" name="processor" size="25" id="location" tabindex="1"</p>
    <p><label>RAM:</label><input type="text" name="ram" size="25" id="location" tabindex="1"</p>
    <p><input align="center" type="submit" name="Filter" value="Filter">
    </form>

    <?php

    if($_POST['Filter']){
    $sql = "SELECT * FROM $tbl_name WHERE school like '%$school' AND make like '%$make' AND model like '%$model' AND location like '%$location'";
    $result=mysql_query($sql);

    // Count table rows 
    $count=mysql_num_rows($result);
    $_SESSION['count']=$count;


    ?>

    <strong>Update Multiple Computers</strong><br> 
    <table width="500" border="0" cellspacing="1" cellpadding="0">
    <form name="form1" method="post" action="">
    <tr> 
    <td>
    <table width="500" border="0" cellspacing="1" cellpadding="0">


    <tr>
    <td align="center"><strong>Id</strong></td>
    <td align="center"><strong>School</strong></td>
    <td align="center"><strong>Make</strong></td>
    <td align="center"><strong>Model</strong></td>
    <td align="center"><strong>Barcode</strong></td>
    <td align="center"><strong>Location</strong></td>
    </tr>

    <?php
    while($rows=mysql_fetch_array($result)){
    ?>
    <tr>
    <td align="center"><?php $id[]=$rows['id']; ?><?php echo $rows['id']; ?></td>
    <td align="center"><input name="school[]" type="text" id="school" value="<?php echo $rows['school']; ?>"></td>
    <td align="center"><input name="make[]" type="text" id="make" value="<?php echo $rows['make']; ?>"></td>
    <td align="center"><input name="model[]" type="text" id="model" value="<?php echo $rows['model']; ?>"></td>
    <td align="center"><input name="barcode[]" type="text" id="barcode" value="<?php echo $rows['barcode']; ?>"></td>
    <td align="center"><input name="location[]" type="text" id="location" value="<?php echo $rows['location']; ?>"></td>
    </tr>

    <?php
    }
    ?>
    <tr>
    <td colspan="4" align="center"><input type="submit" name="Update" value="Update"></td>
    </tr>
    </table>
    </td>
    </tr>
    </form>
    </table>
    <?php
    }
    // Check if button name "Update" is active, do this 
    if(isset($_POST['Update'])){
    for($i=0;$i<$_SESSION['count'];$i++){
    $sql1="UPDATE $tbl_name SET school='$school[$i]', make='$make[$i]', model='$model[$i]' , barcode='$barcode[$i]' , location='$location[$i]' WHERE id='$id[$i]'";
    $result1=mysql_query($sql1);
    }
    session_destroy();
    }
    if(isset($result1)){
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=update_multiple.php\">";
    }
    ?>`

当然,任何帮助都是非常感谢的。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-03-07 06:18:14

请看看这个。我在您的代码中添加了两行代码,ID正在被获取,您可以相应地更新数据。我已经在这里做了注释..

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?php
$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name="inventory"; // Database name 
$tbl_name="computers"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 

mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form 
$school=$_POST['school'];
$make=$_POST['make'];
$model=$_POST['model'];
$barcode=$_POST['barcode'];
$location=$_POST['location'];
//Note here
$id = $_POST['id'];
?>

    <?php
    include 'nav-bar.php';
    ?>

    <h2 align="center">Filter Computers</h2>
    <form name="form" method="post" style="margin: 0; text-align: center;">
    <p><label>School Name:</label><input type="text" name="school" size="8" id="school" tabindex="1"</p>
    <p><label>Make:</label><input type="text" name="make" size="25" id="make" tabindex="1"</p>
    <p><label>Model:</label><input type="text" name="model" size="25" id="model" tabindex="1"</p>
    <p><label>Barcode:</label><input type="text" name="barcode" size="12" id="barcode" tabindex="1"</p>
    <p><label>Location:</label><input type="text" name="location" size="25" id="location" tabindex="1"</p>
    <p><label>Serial:</label><input type="text" name="serial" size="25" id="location" tabindex="1"</p>
    <p><label>Date Acquired yyyy-dd-mm:</label><input type="text" name="date" size="8" id="location" tabindex="1"</p>
    <p><label>Processor:</label><input type="text" name="processor" size="25" id="location" tabindex="1"</p>
    <p><label>RAM:</label><input type="text" name="ram" size="25" id="location" tabindex="1"</p>
    <p><input align="center" type="submit" name="Filter" value="Filter">
    </form>

    <?php

    if($_POST['Filter']){
    $sql = "SELECT * FROM $tbl_name WHERE school like '%$school' AND make like '%$make' AND model like '%$model' AND location like '%$location'";
    $result=mysql_query($sql);

    // Count table rows 
    $count=mysql_num_rows($result);
    $_SESSION['count']=$count;


    ?>

    <strong>Update Multiple Computers</strong><br> 
    <table width="500" border="0" cellspacing="1" cellpadding="0">
    <form name="form1" method="post" action="">
    <tr> 
    <td>
    <table width="500" border="0" cellspacing="1" cellpadding="0">


    <tr>
    <td align="center"><strong>Id</strong></td>
    <td align="center"><strong>School</strong></td>
    <td align="center"><strong>Make</strong></td>
    <td align="center"><strong>Model</strong></td>
    <td align="center"><strong>Barcode</strong></td>
    <td align="center"><strong>Location</strong></td>
    </tr>

    <?php
    while($rows=mysql_fetch_array($result)){
    ?>
    <tr>
    <td align="center"><?php $id[]=$rows['id']; ?><?php echo $rows['id']; ?></td>
    <td align="center"><input name="school[]" type="text" id="school" value="<?php echo $rows['school']; ?>"></td>
    <td align="center"><input name="make[]" type="text" id="make" value="<?php echo $rows['make']; ?>"></td>
    <td align="center"><input name="model[]" type="text" id="model" value="<?php echo $rows['model']; ?>"></td>
    <td align="center"><input name="barcode[]" type="text" id="barcode" value="<?php echo $rows['barcode']; ?>"></td>
    <td align="center"><input name="location[]" type="text" id="location" value="<?php echo $rows['location']; ?>"></td>
    <!-- Note here-->
    <input type="hidden" name="id[]" id="id" value="<?php echo $rows['id']; ?>" />
    </tr>

    <?php
    }
    ?>
    <tr>
    <td colspan="4" align="center"><input type="submit" name="Update" value="Update"></td>
    </tr>
    </table>
    </td>
    </tr>
    </form>
    </table>
    <?php
    }
    // Check if button name "Update" is active, do this 
    if(isset($_POST['Update'])){
    for($i=0;$i<$_SESSION['count'];$i++){
    $sql1="UPDATE $tbl_name SET school='$school[$i]', make='$make[$i]', model='$model[$i]' , barcode='$barcode[$i]' , location='$location[$i]' WHERE id='$id[$i]'";
    $result1=mysql_query($sql1);
    }
    session_destroy();
    }
    if(isset($result1)){
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=update_multiple.php\">";
    }
    ?>

我希望这会对你有所帮助。

票数 0
EN

Stack Overflow用户

发布于 2012-03-07 05:49:36

这就是隐藏输入的用途。为您的id添加一个:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<input type="hidden" name="id[]" value="<?=$rows['id']?>" />

而且,您不需要保存计数。您可以使用count($id)计算数组中的项数。

最后,清理你的输入。永远不要将用户提交的数据直接放入查询中。对于整数使用intval,对于字符串使用mysql_real_escape_string,或者使用预准备语句。

票数 2
EN

Stack Overflow用户

发布于 2012-03-07 05:42:45

你不应该让count成为一个会话变量,你应该只有一个表单--你可以有多个提交按钮。

在表单中,只提交<form></form>之间的内容。

以下是代码的一个改进的重构版本:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?php

// Database connection settings
$host     = 'localhost';
$username = '';
$password = '';
$db_name  = 'inventory';
$tbl_name = 'computers';

// Connect to server and select database.
mysql_connect($host, $username, $password) or die('cannot connect'); 
mysql_select_db($db_name) or die('cannot select DB');

// Perform updates
if (isset($_POST['Update']))
{
    $value_fields = array('school', 'make', 'model', 'barcode', 'location');

    foreach ((array) $_POST['id'] as $counter => $id)
    {
        $user_values = array();
        foreach($value_fields as $field_name)
        {
            if (isset($_POST[$field_name][$counter]))
            {
                $user_values[] = $field_name . ' = "' . mysql_real_escape_string($_POST[$field_name][$counter]) . '"';
            }
        }
        if (!empty($user_values))
        {
            $sql = 'UPDATE ' . $tbl_name . ' SET ' . implode(', ', $user_values) . ' WHERE id = "' . intval($id) . '"';
            mysql_query($sql);
        }
    }
}

// Build select command
$where = array('TRUE');

$filter_fields = array('school', 'make', 'model', 'barcode', 'location', 'serial', 'date', 'processor', 'ram');

if (empty($_POST['filter']))
{
    $user_filter = array_fill_keys($filter_fields, '');
}
else
{
    $user_filter = (array) $_POST['filter'];

    foreach($filter_fields as $filter_field)
    {
        if (empty($user_filter[$filter_field]))
        {
            $user_filter[$filter_field] = '';
        }
        else
        {
            $term = str_replace(array('=', '_', '%'), array('==', '=_', '=%'), $user_filter[$filter_field]);
            $term = mysql_real_escape_string($term);
            $where[] = $filter_field . ' LIKE "%' . $term . '%" ESCAPE "="';
        }
    }
}

$sql = 'SELECT id, school, make, model, barcode, location FROM ' . $tbl_name . ' WHERE ' . implode(' AND ', $where);
$result = mysql_query($sql);

// Output
function safe_output($str)
{
    return str_replace(array("'", '"'), array("&#39;", "&quot;"), htmlspecialchars($str));
}

?>

<?php include('nav-bar.php'); ?>

<form method="post">
    <h2 align="center">Filter Computers</h2>
    <div style="margin: 0; text-align: center;">
        <p><label>School Name:</label><input type="text" name="filter[school]" size="8" value="<?php echo safe_output($user_filter['school']); ?>" /></p>
        <p><label>Make:</label><input type="text" name="filter[make]" size="25" value="<?php echo safe_output($user_filter['make']); ?>" /></p>
        <p><label>Model:</label><input type="text" name="filter[model]" size="25" value="<?php echo safe_output($user_filter['model']); ?>" /></p>
        <p><label>Barcode:</label><input type="text" name="filter[barcode]" size="12" value="<?php echo safe_output($user_filter['barcode']); ?>" /></p>
        <p><label>Location:</label><input type="text" name="filter[location]" size="25" value="<?php echo safe_output($user_filter['location']); ?>" /></p>
        <p><label>Serial:</label><input type="text" name="filter[serial]" size="25" value="<?php echo safe_output($user_filter['serial']); ?>" /></p>
        <p><label>Date Acquired yyyy-dd-mm:</label><input type="text" name="filter[date]" size="8" value="<?php echo safe_output($user_filter['date']); ?>" /></p>
        <p><label>Processor:</label><input type="text" name="filter[processor]" size="25" value="<?php echo safe_output($user_filter['processor']); ?>" /></p>
        <p><label>RAM:</label><input type="text" name="filter[ram]" size="25" value="<?php echo safe_output($user_filter['ram']); ?>" /></p>
        <p><input align="center" type="submit" value="Filter">
    </div>

    <strong>Update Multiple Computers</strong><br> 
    <table width="500" border="0" cellspacing="1" cellpadding="0">
        <tr>
            <td align="center"><strong>Id</strong></td>
            <td align="center"><strong>School</strong></td>
            <td align="center"><strong>Make</strong></td>
            <td align="center"><strong>Model</strong></td>
            <td align="center"><strong>Barcode</strong></td>
            <td align="center"><strong>Location</strong></td>
        </tr>
<?php while ($row = mysql_fetch_array($result)): ?>
        <tr>
            <td align="center"><input name="id[]" type="hidden" value="<?php echo $row['id']; ?>" /><?php echo $row['id']; ?></td>
            <td align="center"><input name="school[]" type="text" value="<?php echo safe_output($row['school']); ?>" /></td>
            <td align="center"><input name="make[]" type="text" value="<?php echo safe_output($row['make']); ?>" /></td>
            <td align="center"><input name="model[]" type="text" value="<?php echo safe_output($row['model']); ?>" /></td>
            <td align="center"><input name="barcode[]" type="text" value="<?php echo safe_output($row['barcode']); ?>" /></td>
            <td align="center"><input name="location[]" type="text" value="<?php echo safe_output($row['location']); ?>" /></td>
        </tr>
<?php endwhile; ?>
        <tr>
            <td colspan="6" align="center"><input type="submit" name="Update" value="Update" /></td>
        </tr>
    </table>
</form>

这里有很多东西需要学习:

  1. 尽可能地将输出或视图从逻辑和处理代码中分离出来。请注意,HTML仅从末尾开始。
  2. 如果你不清理你的输入($_POST)和输出(echo),你很容易受到几种类型的攻击,比如SQL注入和XSS。因此,您始终需要在使用之前清除用户输入,并在回显之前清除输出。
  3. 要构建更新和选择查询,我们将使用implode函数以及数组($user_values (用于UPDATE,$where用于SELECT )。
  4. 我们在SELECT之前进行更新,以便输出显示为已更新。
  5. LIKE子句很难正确构建,因为用户可能希望搜索"100%",但是这个百分比字符不能与SQL命令的百分比混淆。这就是为什么我们在这一部分中有一些复杂而神秘的代码行。
  6. mysql_real_escape_stringintval函数负责清理用户输入。
  7. 我们已经使用safe_outputhtmlspecialchars创建了一个str_replace函数来清理输出。< code >H231
  8. 我们已经努力使一个完整的HTML数组到达输出阶段。
  9. 当HTML启动时,我们已经完成了所有的工作:安全更新、安全选择、过滤器都在$user_filter数组中,结果在$result资源中。我们只需要输出。
  10. 在超文本标记语言中,不能有多个元素具有相同的ID,也不需要每个表单输入都有一个ID。因此,我删除了无用的I。
  11. 我重命名了过滤器输入名称。瞧一瞧。这样,我们就可以拥有一个筛选器数组。
  12. 在这种情况下,"tabindex“属性是无用的,所以它们也被删除了。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9596379

复制
相关文章
比较字符串(忽略空格,忽略大小写)
总时间限制: 1000ms内存限制: 65536kB描述 判断两个由大小写字母和空格组成的字符串在忽略大小写,且忽略空格后是否相等。 输入两行,每行包含一个字符串。输出若两个字符串相等,输出YES,否则输出NO。样例输入 a A bb BB ccc CCC Aa BBbb CCCccc 样例输出 YES 源码如下: #include <iostream> using namespace std; bool compareTwoStringIgnoreCases(string a,string b); in
用户1631856
2018/04/12
3.2K0
16:忽略大小写的字符串比较
16:忽略大小写的字符串比较 总时间限制: 1000ms 内存限制: 65536kB描述 一般我们用strcmp可比较两个字符串的大小,比较方法为对两个字符串从前往后逐个字符相比较(按ASCII码值大小比较),直到出现不同的字符或遇到'\0'为止。如果全部字符都相同,则认为相同;如果出现不相同的字符,则以第一个不相同的字符的比较结果为准(注意:如果某个字符串遇到'\0'而另一个字符串还未遇到'\0',则前者小于后者)。但在有些时候,我们比较字符串的大小时,希望忽略字母的大小,例如"Hello"和"hell
attack
2018/04/03
1.7K0
忽略大小写比较字符串大小
一般我们用 strcmpstrcmp 可比较两个字符串的大小,比较方法为对两个字符串从前往后逐个字符相比较(按 ASCII 码值大小比较),直到出现不同的字符或遇到 \0 为止。
莫浅子
2022/11/18
1.2K0
python 字符串比较忽略大小写的方法
A.正则表达式,使用IGNORECASE标志 >>> import re >>> m = re.search('multi', 'A mUltiCased string', re.IGNORECASE) >>> bool(m) True B.在比较前把2个字符串转换成同样大写,用upper()方法,或小写,lower() >>> s = 'A mUltiCased string'.lower() >>> s 'a multicased string' >>> s.find('multi') 2
py3study
2020/01/14
8.3K0
python 字符串搜索替换(忽略大小写)
re.IGNORECASE text = 'UPPER PYTHON, lower python, Mixed Python' re.findall('python', text, flags=re.IGNORECASE) ['PYTHON', 'python', 'Python'] re.sub('python', 'snake', text, flags=re.IGNORECASE) 'UPPER snake, lower snake, Mixed snake'
用户5760343
2022/01/10
1K0
Swift4 获取String子字符串
都说Swift2和Swift3不是同一门语言,但是我怎么觉得Swift4有时看着也像别人家的孩子。。。。 这里主要是更新下以前的写的Swift3的String相关知识:
韦弦zhy
2018/09/11
6270
Swift 字符串和字符
Swift 字符串通过 String 类型来表示,也可以表示为 Character 类型值的集合。
Swift社区
2021/11/26
7930
Swift基础 字符串和字符
翻译自:https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html
郭顺发
2023/07/17
1920
Swift基础 字符串和字符
go 生成随机字符串和获得定长字符串
挑战A.I.,赢百万奖金......了解更多详情>>> 随机字符串 //RandomStr 随机生成字符串 func RandomStr(length int) string { str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" bytes := []byte(str) result := []byte{} r := rand.New(rand.NewSource(time.Now().UnixNano
solate
2019/07/19
1.8K0
ToStringBuilder如何忽略null和空字符串
日常开发中,经常用org.apache.commons.lang3.builder.ToStringBuilder工具类来记录日志,比如:
菩提树下的杨过
2022/05/09
1.1K0
Swift教程(三)--字符串和字符
字符串是一系列的字符,比如说 “hello, world”或者 “likeyou”。Swift 的字符串用 String类型来表示。 String的内容可以通过各种方法来访问到,包括作为 Character值的集合。
roc
2019/07/31
6070
获得定长字符串
        C#中的字符串是Unicode编码,length是Unicode的Char的个数。所以,假如一个字符串中中英文混杂,又想获得一个固定宽度的字符串,就比较麻烦。单纯转换成字节再截取难免会碰到半个汉字的问题。         下面实现了这样的功能,返回固定字节长度的字符串,如果发生截断,后面补充2个或者3个“.”,根据截断点的位置决定。 /// <summary>         /// 返回定长的字符串,如果发生截取,在后面补充两个或三个"."         /// Author:jetz
用户1075292
2018/01/23
7880
Swift3 获取String子字符串Substring简单扩展
Swift3更新后不兼容Swift2了,刚开始看Swift,发现好多方法都不能用了啊,那就只能自己摸索了,同时也在这与大家分享分享,正好让大家帮我指正。
韦弦zhy
2018/09/11
6700
Python 字符串的大小写(一)
文章链接: https://icodeq.com/2021/6a332b281b55/
Zkeq
2022/05/18
5770
Swift3.0 for 循环和遍历字符串
未经允许不得转载:RffanLAB|Rffan实验室 » Swift3.0 for 循环和遍历字符串
用户2353021
2020/05/09
9010
[译]Swift中的空字符串
Swift 一个特色就是有很多的语法糖,初学可能觉得hold不住,实际用的时候倒是挺便利。
小刀c
2022/08/16
9800
Python字符串的大小写(二)
文章链接: https://icodeq.com/2021/28d6866714c1/
Zkeq
2022/05/18
5960
字符串——459. 重复的子字符串
示例 1: 输入: s = “abab” 输出: true 解释: 可由子串 “ab” 重复两次构成。
向着百万年薪努力的小赵
2022/12/02
1.4K0
字符串中查找子串_cstring查找子字符串
假设要从主串 s = “goodgoogle” 中找到 t = “google” 子串。根据我们的思考逻辑,则有:
全栈程序员站长
2022/09/24
3K0
字符串中查找子串_cstring查找子字符串
Java 字符串大小写转化
str.toLowerCase() 将String转换为小写,如果字符串中没有应该被转换的字符,返回原字符串
桑鱼
2020/04/24
1.2K0
Java 字符串大小写转化

相似问题

如何在Nextjs中设置背景图像?

214

如何在白色背景上显示Libgdx粒子效果?

11

粒子设计器设置背景图像

10

OpenglES混合粒子而不是背景粒子

30

如何将粒子-js设置为背景?

11
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文