简体   繁体   English

从添加到使用 SQL 查询数组的 foreach 循环的输入元素中捕获/插入特定值

[英]Capturing/INSERT specific value from an input element added to a foreach loop that uses a SQL query array

So, I have been working on this one issue for about a week.所以,我一直在研究这个问题大约一个星期。 I've found a lot of similar questions with solutions like this one or this one , but I haven't had much luck with them.我发现了很多类似的问题,有类似this onethis one 的解决方案,但我对它们的运气并不好。

My issue is, I am trying to capture a specific value from any one of the input elements associated with returned results from a foreach loop.我的问题是,我试图从与 foreach 循环返回的结果相关联的任何一个输入元素中捕获特定值。 Like a search engine, a query is submitted, results are returned, and each result has a "Rating" slider added to it which a user should be able to rate and submit, on any of the results, a unique rating for that result.像搜索引擎一样,提交查询,返回结果,每个结果都添加了一个“评级”滑块,用户应该能够对任何结果进行评级并提交该结果的唯一评级。

My "rating" range input object:我的“评级”范围输入对象:

<form action='#' method='POST'>
<input class='rating' type='range' name='rating_s' min='0' max='100' step='1' value='50' /></i>
<input class="rateglowbutton" type=submit value=Rate />
</form>

That sits within a foreach loop (I know, lots of echoes for formatting, it is what it is):它位于 foreach 循环中(我知道,有很多用于格式化的回声,就是这样):

// array
$audios = $wpdb->get_results($wpdb->prepare("
SELECT a.aud_id
     , a.date
     , a.teacher
     , a.title
     , a.teach_desc
     , a.venue
     , a.genre
     , a.url
     , GROUP_CONCAT(t.tag_name SEPARATOR ', ') tag_name
  FROM audio_tag_xref atx
 RIGHT 
  JOIN audios a 
    ON atx.aud_id = a.aud_id
  LEFT 
  JOIN audio_tags t 
    ON atx.tag_id = t.tag_id
WHERE (a.title LIKE '%$strKey%' 
     OR a.venue LIKE '%$strKey%' 
     OR a.teach_desc LIKE '%$strKey%' 
     OR a.genre LIKE '%$strKey%')
 GROUP 
    BY a.aud_id
 ORDER 
    BY a.aud_id DESC
     ",$strKey));

<?php echo "<table>"; ?>
<?php foreach($audios as $i => $audio){ ?>
<?php echo "<tr>";
echo "<tr><h3>".$audio->title."</h3></tr>";
echo "<tr>".$audio->url."</tr>";
echo "</br>";
echo "<tr>".$audio->aud_id."</tr>";
echo "</br>";
echo "<tr><b>".$audio->teacher."</b></tr>";
echo "</br>";
echo "<tr><i>".$audio->date."</i></tr>";
echo " &nbsp| &nbsp";
echo "<tr><i>".$audio->venue."</i></tr>";
echo "</br>";
echo "<tr>".$audio->genre."</tr>";
echo "</br>";
echo "<tr>".$audio->teach_desc."</tr>";
echo "</tr>";
echo "</br>";
echo "</br>"; ?>

<form action='#' method='POST'>
<input class='rating' type='range' name='rating_s[]' min='0' max='100' step='1' value='50' /> &nbsp<i class="fa fa-plus" aria-hidden="true"></i></div>
<input class="rateglowbutton" type=submit value=Rate />
</form>

<?php } ?>
<?php echo "</table>"; ?>

The submitted rating of which is then inserted into a rating table in my database:然后将提交的评分插入到我的数据库中的评分表中:

<?php
if (isset($_POST['rating_s'])) {
$userid = md5($_SERVER['REMOTE_ADDR']);
$rate = $_POST['rating_s'];
$aud_id = "$audio->aud_id";
$sql = $wpdb->query($wpdb->prepare("INSERT INTO ratings (rate, aud_id, user_id) VALUES ('$rate', '$aud_id', '$userid')",$rate,$aud_id,$userid));
if ($sql) {
    echo "</br>";
    echo "<div class='rate_msg_cont'><div class='rate_msg'>You gave a rating of $rate for teaching ID: $aud_id.</div></div>";
        }
    }
?>

But, I can't get both the rate, and the aud_id to correctly be inserted into the rating table.但是,我无法同时将费率和 aud_id 正确插入到评分表中。 At best, I was able to get the rating, but not the aud_id it "belongs" to on the page (the input object that is rendered for its respective returned $audio result).充其量,我能够获得评级,但无法获得它在页面上“属于”的 aud_id(为其各自返回的 $audio 结果呈现的输入对象)。 I've tried to following:我试图遵循:

  • The POST/insert php code above left inside (at end) of the foreach. POST/insert php 代码在 foreach内部(末尾)的左上方。 This results in all returned results from the string search ($strKey) that are returned by the foreach being given the rating that was submitted for any of the input element (so, index [0],[1],[2],[3],[n]...get the same rating).这将导致所有由 foreach 返回的字符串搜索 ($strKey) 返回的结果被赋予为任何输入元素提交的评级(因此,索引 [0],[1],[2],[ 3],[n]...获得相同的评分)。 Though, it does grab the aud_ids correctly, it just grabs all of them in a single submission.虽然它确实正确地获取了 aud_ids,但它只是在一次提交中获取了所有这些。
  • The POST/insert php code above left outside (below) of the foreach.上面的 POST/insert php 代码位于 foreach 的外部(下方)。 This results in only the LAST returned result (if 5 audios returned, index [4]) regardless of which result's input element is used to submit the rating.无论使用哪个结果的输入元素提交评级,这只会导致最后返回的结果(如果返回 5 个音频,索引 [4])。 Still, it captures the rating and the aud_id, just for the wrong (always the last) returned result.尽管如此,它仍会捕获评级和 aud_id,仅针对错误的(始终是最后一个)返回结果。
  • Trying to sort out the use of the index key by adding [] to the input name=, as in the included code here, trying to implement the $i (key) to various elements I thought would work ($aud_id, $rate), etc.尝试通过将 [] 添加到输入名称 = 来整理索引键的使用,就像这里包含的代码一样,尝试将 $i(键)实现到我认为可行的各种元素($aud_id,$rate) , 等等。

Is this a matter of not indexing the input elements correctly in the foreach?这是没有在 foreach 中正确索引输入元素的问题吗? Maybe an issue with handling the arrays?也许是处理数组的问题? Something else entirely?完全是别的什么?

To sum up: I have a search page that uses an input text box for users to enter a keyword string.总结一下:我有一个搜索页面,它使用输入文本框供用户输入关键字字符串。 The string returns an array that a foreach loop uses to output the queried results, including an input object to allow users to rate the audio.该字符串返回一个数组,foreach 循环使用该数组来输出查询结果,其中包括一个允许用户对音频进行评级的输入对象。 The rates can be submitted just fine, but they end up not being associated with the result audio that the user it actually trying to rate.可以很好地提交费率,但它们最终不会与用户实际尝试评价的结果音频相关联。

How can I ensure that when a result is rated, the rating and the respective aud_id are inserted together as a new entry in the ratings table?如何确保在对结果进行评级时,将评级和相应的 aud_id 作为新条目插入到评级表中?

Visual, if it helps:视觉,如果有帮助:

Query result查询结果

Huge thanks to anyone in advance for some help.非常感谢任何人的帮助。

First off looking at this from a distance... I see you using PDO, but then I see you escaping the entire point of PDO.首先从远处看这个……我看到你在使用 PDO,但后来我看到你逃避了 PDO 的全部意义。

You should not echo your values directly into your query string... You should bind them.您不应该将您的值直接回显到您的查询字符串中...您应该绑定它们。

I just want to give you a small PDO example(not particularly related to yours), that way maybe you can use it as a guide to fix your own errors.我只想给你一个小的 PDO 例子(与你的没有特别的关系),这样也许你可以用它作为指南来修复你自己的错误。

            <table class="table table-bordered table-striped mb-none" id="datatable-editable">
                <thead>
                    <tr>
                        <th>Accout Type | User's Name | Email Address</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="tablebody">
                    <?
                        $DbHost     = ""; // The host where the MySQL server resides
                        $DbDatabase = ""; // The database you are going to use
                        $DbUser     = ""; // Username
                        $DbPassword = ""; // Password
                        // --- PDO Info
                        $dsn = 'mysql:host='.$DbHost.';dbname='.$DbDatabase; 
                        $DbOptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
                        $DBH = new PDO($dsn, $DbUser, $DbPassword, $DbOptions);
                        $qs = "SELECT * FROM `users` WHERE `accountid`=:accountid";
                        $q = $DBH->prepare($qs);
                        $q->bindValue(':accountid',(integer)$userrow['accountid'], PDO::PARAM_INT);
                        $q->execute();
                        while($row = $q->fetch(PDO::FETCH_ASSOC))
                        {
                            if($userrow['access'] >= $row['access'])
                            {
                                ?>
                                    <tr id="row<?=$row['id'];?>">

                                        <?
                                            $qs2 = "SELECT COUNT(*) AS `count` FROM `accounts` WHERE `admin` = :id";
                                            $q2 = $DBH->prepare($qs2);
                                            $q2->bindValue(':id', (integer)$row['id'], PDO::PARAM_INT);
                                            $q2->execute();
                                            $count = $q2->fetch(PDO::FETCH_ASSOC)['count'];
                                            $isAdmin = 'false';
                                            $fontStyle = " style='color:blue;'";
                                            $userType = "Developer";
                                            if($row['access'] == 40)$userType = "Accountant";
                                            if($row['access'] == 60)$userType = "Administrator";
                                            if($row['access'] == 99)$userType = "Internal Administrator";
                                            if($row['access'] == 100)$userType = "Internal Developer";                                                
                                            $root = "<span class='label label-info'>$userType</span>&nbsp;";
                                            if($count > 0)
                                            {
                                                $isAdmin = 'true';
                                                $fontStyle = " style='font-weight:bold;color:red;'";
                                                $root = "<span class='label label-danger'>Root</span>&nbsp;";
                                            }

                                        ?>
                                        <td><span style="color:red;"><?=$root;?></span><span<?=$fontStyle;?>><?=ucfirst(strtolower($row['firstname']))."&nbsp;".ucfirst(strtolower($row['lastname']));?> - <?=$row['email'];?></span></td>
                                        <?
                                            if($count == 0)
                                            {
                                                ?>
                                                    <td><a class="mb-xs mt-xs mr-xs" href="javascript:edit(<?=$row['id'];?>, '<?=$row['firstname'];?>', '<?=$row['lastname'];?>', '<?=$row['email'];?>', <?=$row['access'];?>, <?=$isAdmin;?>)">Edit</a></td>
                                                <?
                                            }
                                            else
                                            {
                                                ?><td>This account cannot be modified here.</td><?
                                            }
                                        ?>

                                    </tr>
                                <?
                            }
                            else
                            {
                                ?>
                                    <tr id="row<?=$row['id'];?>">

                                        <?
                                            $qs2 = "SELECT COUNT(*) AS `count` FROM `accounts` WHERE `admin` = :id";
                                            $q2 = $DBH->prepare($qs2);
                                            $q2->bindValue(':id', (integer)$row['id'], PDO::PARAM_INT);
                                            $q2->execute();
                                            $count = $q2->fetch(PDO::FETCH_ASSOC)['count'];
                                            $isAdmin = 'false';
                                            $fontStyle = " style='color:blue;'";
                                            $root = "<span class='label label-info'>User Account</span>&nbsp;";
                                            if($count > 0)
                                            {
                                                $isAdmin = 'true';
                                                $fontStyle = " style='font-weight:bold;color:red;'";
                                                $root = "<span class='label label-danger'>Root Account</span>&nbsp;";
                                            }
                                        ?>
                                        <td><span style="color:red;"><?=$root;?></span><span<?=$fontStyle;?>><?=ucfirst(strtolower($row['firstname']))."&nbsp;".ucfirst(strtolower($row['lastname']));?> - <?=$row['email'];?></span></td>
                                       <td>You do not have access to modify this account.</td>                                            
                                    </tr>
                                <?
                            }
                        }
                    ?>

                </tbody>
            </table>            

OK, thanks to everyone's help here and some further input/trial and error, I've landed on a solution.好的,感谢这里的每个人的帮助以及一些进一步的输入/试验和错误,我已经找到了一个解决方案。 I still will be doing some cleanup as suggested, but here is the idea and code that got each input element to act uniquely:我仍然会按照建议进行一些清理,但这里的想法和代码使每个输入元素都具有独特的作用:

The form element revised:表单元素修改:

<?php echo " <form action='#' method='POST'>"; ?>
<?php echo " <input type='hidden' name='audio_index' value='" . $i . "' />"; ?>
<?php echo " <input type='hidden' name='audio_id' value='" .$teaching->aud_id. "' />"; ?>
<?php echo " <div class='range_container'>"; ?>
<?php echo " <div class='rate_sym'>"; ?>
<?php echo " <i class='fa fa-minus' aria-hidden='true'></i> &nbsp"; ?>
<?php echo " <input class='rating' type='range' name='rating_s' min='0' max='100' step='1' value='50' /> &nbsp"; ?>
<?php echo " <i class='fa fa-plus' aria-hidden='true'></i>"; ?>
<?php echo " </div>"; ?>
<?php echo " </div>"; ?>
<?php echo " <div class='rate_container'>"; ?>
<?php echo " <div class='ratescr_container'></div>"; ?>
<?php echo " <input class='rateglowbutton' type='submit' value='Rate' />" ?>
<?php echo " </div>"; ?>
<?php echo " </form>"; ?>
echo " </td>";
echo " </tr>"; ?>

The POST code revised: POST 代码修改:

<?php
if (isset($_POST['rating_s']) && isset($_POST['audio_id'])) {
$table = "ratings";
$parama = $_POST['audio_id'];
$paramb = $_POST['rating_s'];
$paramc = md5($_SERVER['REMOTE_ADDR']);
$sql = $wpdb->query($wpdb->prepare("INSERT INTO $table (a_id, rating, u_id) VALUES ('$parama', '$paramb', '$paramc')"));
if (query) {
    echo "</br>";
    echo "<div class='rate_msg_cont'><div class='rate_msg'>Hooray! You rated 
audio $parama a $paramb.</div></div>";
    }
}
?>

Notice the additional hidden input elements in the form to generate the index for each audio returned and the "audio_id" for the rating input to utilize.请注意表单中的附加隐藏输入元素,用于为返回的每个音频生成索引,并为要使用的评级输入生成“audio_id”。 Again, I understand the cleanup and security improvements that can (will) be implemented, but I wanted to post this as a working solution for anyone who needs a tip if dealing with the same or similar.同样,我理解可以(将)实施的清理和安全改进,但我想将此作为工作解决方案发布给任何需要提示处理相同或类似问题的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM