函数

时间:2015-07-14 16:23:26

标签: php mysql

我有一个网络表单,用户输入名称并从下拉列表中选择“程序”名称。我有一个javascript函数,允许用户在想要在表单中输入多个名称时添加框。选择程序并将其插入表格后,将生成主键(LINE_ID)。将名称插入到另一个表中,然后在其各自的列中使用名称和LINE_ID。

    <div>
<label>Name:</label>
<tr>
<td><input type ="Text" name="yourname"/></td>
<td><input onclick="addBox(this);" type="button" value="+ Add Another Name"/></td>
</tr>
</div>

<script type="text/javascript">
        var BoxNum = 0;
        var NameCount = [];
    function addBox(input) {
    console.log(input);
        BoxNum ++;
            var row ='<input name = "BoxNum'+BoxNum+'">';
        $(input).before(row);
        NameCount.push(BoxNum);
        $('#nameCount').val(NameCount);
        };
    </script>

将使用预先存在的HTML输入框(1)输入显示的第一个名称,用户单击按钮(2)将生成其他框。

    <?php

    $name = $_POST['yourname'];
    $program = $_POST['PROGRAM_NAME'];
        mysql_query("INSERT INTO prod_activity (PROGRAM_ID) (SELECT PROGRAM_ID FROM tc_program WHERE PROGRAM_NAME='$program' AND ZONE_ID=4)");
        $lineid = mysql_insert_id();
        // THIS WORKS:
mysql_query("INSERT INTO tc_user (USER_NAME, LINE_ID) VALUES ('$name','$lineid')");
        $ElementNo = 0;
    function POSTALLNAMES(){
        //$ElementNo = 0;
        $ElementNo ++;
        $nameCount = $_POST['nameCount'];
        $nameelement = explode(",", $nameCount);
        $NameCountLgth = sizeof($nameelement);
        foreach ($nameelement as $value){
        $RealName = $_POST["BoxNum${value}"];
// THIS DOES NOT WORK:
        mysql_query("INSERT INTO tc_user (USER_NAME, LINE_ID) VALUES ('$RealName','$lineid')");}}
            POSTALLNAMES();

我第一次尝试使用HTML(1)框插入$ lineid变量时,所有内容都正确地插入到tc_user中。我第二次尝试用javascript生成的输入框(2)来做它没有。当我在POSTALLNAMES()之后回显变量$ lineid时;运行时,它为$ lineid提供了正确的值,告诉我该变量在任何时候都没有被重置。

当我从(2)中的Insert语句中取出LINE_ID / $ lineid并将其保留在(1)中时,所有内容都会按预期插入(带有ID的名字和没有附加名称的名字)。

1 个答案:

答案 0 :(得分:0)

如上所述,在许多方面可以改进您的代码。我强烈建议您研究如何使用PDO和预处理语句,以及如何正确执行用户提交数据的输入验证 永远记住:永远不要相信客户!您的网站在某些时候受到攻击,这只是时间的问题。不管你认为它有多么小或无趣。

我还注意到没有使用任何连贯的编码风格,这使得其他人(和你自己)阅读代码变得更加困难。这种情况只会让你困扰,并且不会让某人花时间真正帮助你。这就是为什么建议选择一种最常见的编码风格,并坚持不懈地坚持它。在撰写本文时,建议使用PSR-2。

最后,您的代码和问题:
问题本身很简单。您还没有传递您尝试在函数中使用的变量,因此它不存在,而是为您提供null值(和通知)。哪会让MySQL抱怨缺少价值。我已经修复了这个问题,并稍微清理了一下你的代码。还添加了一些评论,进一步突出了我所做的和为什么,以及还有什么需要做的 请享用! :)

<?php

// CF: Validate input, to make sure you actually get something that could be a valid name.
$name = filter_input (INPUT_POST, 'yourname', FILTER_VALIDATE_REGEXP, "/^[a-z\\pL][a-z\\d\\pL '-]+\\z/iu");
$program = filter_input (INPUT_POST, 'program_name', FILTER_VALIDATE_REGEXP, '/^[a-z\\d][a-z\\d_-]+');

// CF: You could validate the input of $_POST['boxes'] here too, instead of inside the function.
$userBoxes = array ();
if (is_array ($_POST['boxes'])) {
    $userBoxes =  $_POST['boxes'];
}

// CF: If any of the above validations failed, show an error here, re-display the
// form with the previous values already filled in, and abort further processing of
// the POSTed data.

// Fill out the necessary details here. The PHP manual will help you on that.
$db = new PDO ();

$stmt = $db->prepare ("INSERT INTO prod_activity (PROGRAM_ID) (
        SELECT PROGRAM_ID FROM tc_program WHERE PROGRAM_NAME=? AND ZONE_ID=4)");
$stmt->exec (array ($program));
$lineId = $db->llastInsertId();

// THIS WORKS:
$stmt = $db->prepare ("INSERT INTO tc_user (USER_NAME, LINE_ID) VALUES (:name, :line_id)");
$stmt->exec (array (':name' => $name, ':line_id' => $lineId));

// CF: What's this for?
$ElementNo = 0;

if (!save_names ($db, $lineId, $userBoxes)) {
    // CF: Something failed, I presume. Handle it.
}

/**
 * Runs through the array of boxes, and saves them with the lineID.
 * 
 * @param PDO $db A connection to the database.
 * @param int $lineId {A useful description}
 * @param array $boxes {A useful description}
 * @return void (for now)
 */
function save_names (PDO $db, $lineId, $boxes)
{
    // CF: What's this for?
    // $ElementNo = 0;
    $ElementNo ++;

    $nameelement = explode(",", );

    // CF: This is not used. Should be removed if not used in the actual code as well.
    $NameCountLgth = sizeof ($nameelement);

    // CF: Prepare the statement outside of the loop, so that we can re-use it.
    $stmt = $db->prepare ("INSERT INTO tc_user (USER_NAME, LINE_ID) VALUES (:name, :id)")
    foreach ($boxes as $realName) {
        // CF: Add validation here, as I did above. If not added at the start of the script.
        if (!validate ($realName)) {
            // CF: Handle the error somehow here. Either by skipping the record, or
            // returning from the function with an error.
        }

        $stmt->exec (array (':name' => $RealName, ':id' =>$lineId));
    }
}