如何将输入 (onchange) 中的文本写入 PHP/HTML 中的数组?

How can I write a text from input (onchange) to an array in PHP/HTML?

我的代码:

<?php
$testthis[] = 0;

$mysql = new mysqli("host","name","password","database");
if($mysql->connect_error) {
    echo "connection error: ".mysqli_connect_error()."<br/>";
}
else {
    echo "<p>succeed</p>";
}   

$result = $mysql->query("SELECT * FROM t_table;");
while($line = $result->fetch_array()) {
    $help = $line["sNr"];

    echo "<tr><td>".htmlspecialchars($line["sNr"])."</td>"
        ."<td>".htmlspecialchars($line["c2"])."</td>"
        ."<form action='my.php' method='post'>"


// **Here is the mess:**

        ."<td>"."<input type='text' name='$help' value='$help' onchange=".$testthis[$help] = $_POST[$help]."/>"
        ."</td>"
        ."\n </tr></form>";
}
?>

我的想法是,sNr 等于数组的索引,这样我以后就可以轻松地将 html 的输入(某种计数或大小)写入一个other table 在我的数据库中(使用 sNr 作为外键)。

一些想法,汉斯。

(1) PHP 无法与用户交互(即检测 DOM 事件,例如按钮点击或文本输入到 <input> 字段等)。那是因为一旦 DOM 被呈现并且控制权移交给用户,PHP 就完成了 运行。它没有与用户交互的功能。 使用javascript/jQuery.

(2) 这是一段简单的(未经测试的)代码,可以满足您的需求:

这是对您的代码提出的轻微改进建议:

    $result = $mysql->query("SELECT * FROM t_table;");
    while($line = $result->fetch_array()) {
    $help = $line["sNr"];

    $htmlOut = "<tr>
            <td>" .htmlspecialchars($line["sNr"]). "</td>
            <td>" .htmlspecialchars($line["c2"]). "</td>
            <td>
                <form action='my.php' method='post'>
                    <input id="myFormID" type='text' name='$help' value='$help' onchange=".$testthis[$help] = $_POST[$help]."/>
                </form>
            </td>
        </tr>";
        
    $htmlOut .= "
        <input id='snr_hidden' type='hidden' value='" .$line["sNr"]. "' />
        <input id='phlp_hidden' type='hidden' value='" .$_POST[$help]. "' />
        <!-- Note: you need jQuery library loaded before you can use jQuery js library-->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#myFormID').blur(function(){
                    var tst = $(this).val();
                    var snr = $('#snr_hidden').val();
                    var pst = $('#phlp_hidden').val();
                    if (tst !== snr){
                        $('#myFormID').val(pst);
                    }
                });
            }); //END document.ready
        </script>
    ";

    echo $htmlOut;

这是示例的工作演示:


$(document).ready(function(){
    $('#myFormID').blur(function(){
        var val = $(this).val();
        var tst = $('#hdnHelpVal').val();
        var pst = $('#hdnPostVal').val();
        if (val !== tst){
            $('#inpCompare').val(pst);
        }else{
            $('#inpCompare').val(val);
        }
    });
    
    $('#myFormID').focus(); //START with cursor in first input field
}); //END document.ready
table{border:1px solid #ccc;border-collapse:collapse;padding:5px;}
input{width:250px;}

div{color:#aaf;font-family:sans-serif;margin:25px 0;}
span{color:#89a;}
aside{display:inline;color:blue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
    <tr>
        <td>
            <form action='my.php' method='post'>
                <input id="myFormID" type='text' value='The hidden HELP valueDELETEME' />
            </form>
        </td>
        <td>
            <input id="inpCompare" type='text' placeholder="Tab over to this field" />
        </td>
    </tr>
</table>
<input id="hdnHelpVal" type="hidden" value="The hidden HELP value" />
<input id="hdnPostVal" type="hidden" value="Data received via $_POST" />

<div>When you tab to the right-side field, jQuery/javascript will check the value in the left field and do something based on whether the contents == the hidden input field<br><br><span>If the left side is not (exactly) "<aside>The hidden HELP value</aside>", then the javascript code will fetch the value from input#hdnPostVal and place that data into the right side</span> </div>


关于我的代码示例的注释:

1. Just as your code is not complete, my example is not a working example. Please just 
use it to get ideas, and try some of the ideas in your project.

2. PHP is great at building an HTML page and spitting it out to the user. But once 
the user has control, PHP is done. Finished. PHP has no way to interact with the user, 
or to detect user events like button clicks, or changes to a drop-down, or etc. 
***Use javascript/jQuery***

3. If you aren't comfortable working with javascript, I recommend learning how to use 
jQuery (a javascript library) so you can come up to speed quickly and save typing.

Read this: 

4. Don't use:
        "<td>Something here</td>" . "<td>Summat else</td>";
when you can use:
        "<td>Something here</td><td>Summat else</td>";

5. When working on tables, make sure all your HTML is placed *within* <td> elements. 
Do not place <form> tags, or divs, or etc, between rows, or between <td>s - for example, 
this is wrong:

    <tr><td></td>In between text<td></td></tr>  <=== text is between <td> elements

This is also wrong:

  <tr><td>Text in table cell</td><td>Text</td></tr>
    Never put anything BETWEEN rows
  <tr><td>Text</td><td>Text</td></tr>
        

6. One way to transfer data from PHP to javascript is to write it into a hidden text 
field as you are building the HTML code *(study how I did that in the above example)*.
After the DOM is written, the data just sits there, hidden, until javascript retrieves 
it.

7. Note that if using the above idea, the data in that hidden input field is visible 
to anyone who presses `F12` and snoops around using DevTools. A more secure way is to 
save the data on the PHP side (either in MySQL or in a text file on the server) and 
retrieve it on-the-fly using AJAX (which is actually pretty *easy*)

我是这样做的...

首先是一个 PHP 片段来获取客户端 POST 请求和 save/update 数据库中的表单数据。 PDO.inc.php 处理创建准备好的语句、过滤等。我不关心任何输出、状态 return 等 - 所以我不会费心检查查询的状态,只需执行并结束。

<?php
    include('security.php');
    include('PDO.inc.php');

    $q="update qualityEval set ".$_POST['thingID']."=?, date_last_modified=? where evaluator=? and course=?";
    $qa=array($_POST['thingVal'],time(),$_SESSION['user'],$_SESSION['course']);
    $res=executeQuery($q,$qa);

?>

然后在我的 HTML 表单中,我引入 jquery 并为 OnChange/etc 设置一个处理程序。我想触发保存的事件

<script type="text/javascript" src="/ct3-code/jquery.min.js"></script>
<script type="text/javascript">
    function SaveChange(thingToSave){
        var pass_data = {
                    'thingID' : thingToSave.name,
                    'thingVal' : thingToSave.value,
                };
                $.ajax({
                    url : "/ct3-code/saveIt.php",
                    type : "POST",
                    data : pass_data,
                    success : function(data) {
                    }
                });
                return false;
    }
</script>

最后我打印出文本区域、输入类型、单选按钮集等。

print("<tr bgcolor=#ffffff><td colspan=4>Comments on <strong>".$secTitle."</strong><br />
        <textarea onInput=\"SaveChange(this);\" rows=7 cols=80 wrap=physical id=\"".$k."Comments\" name=\"".$k."Comments\">");
        if($res[1][$k."Comments"]!==null){print($res[1][$k."Comments"]);}
print("</textarea>");

当用户在文本区域中键入内容(或选择复选框或单选按钮等)时,每次更改都会触发 http POST 调用以保存正在修改的内容。最后触发的事件获胜并且是实际保存在数据库中的内容。