0

My code:

<?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>";
}
?>

My idea is, that sNr equals the index of an array so that I can later easily write the input from the html (what will be some kind of count or size) to an other table on my database (with sNr as foreign key).

VKen
  • 4,964
  • 4
  • 31
  • 43
Hans Olo
  • 3
  • 2
  • There is no way you can do it in the fashion that you have here. You will have to call a javascript async method to postback to the server then write to the array. However, you will not have that accessible unless you keep an array in a session for later. Why not use a localStorage instead of PHP Array? – RealSollyM Feb 21 '19 at 09:30

2 Answers2

0

A few thoughts, Hans.

(1) PHP is not able to interact with a user (i.e. detect DOM events like button clicks or text input into an <input> field or etc). That's because once the DOM has been rendered and control turned over ot the user, PHP has finished running. It has no functionality to interact with the user. Use javascript/jQuery.

(2) Here is a simple bit of (untested) code that might do what you want:

Here is a proposed slight improvement on your code:

    $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;

Here is a working demo of the example:


$(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>

Notes on my code example:

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: https://stackoverflow.com/a/54757176/1447509

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*)
cssyphus
  • 37,875
  • 18
  • 96
  • 111
0

Here's how I do it ...

First a PHP snippet to grab the client POST request and save/update the form data in the db. The PDO.inc.php handles creating prepared statement, filtering, etc. I don't care about any output, status return, etc - so I don't bother checking status of query, just execute and end.

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

?>

Then in my HTML form, I bring in jquery and set up a handler for OnChange/etc. events that I want to trigger a save on

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

And then finally I print out a textarea, input type, radio button set, etc.

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>");

As a user types in the textarea (or selects a checkbox or radio button, etc) each change triggers the http POST call to save the contents of whatever is being modified. Last triggered event wins and is what is actually kept in DB.

ivanivan
  • 2,155
  • 2
  • 10
  • 11