gpt4 book ai didi

javascript - 重复自处理表格

转载 作者:行者123 更新时间:2023-11-29 10:52:02 25 4
gpt4 key购买 nike

我的问题是创建一个自处理表单,该表单插入数据库然后刷新,递增数组以更改表单中的相关信息。 (尽管如果有更简单或更好的方法来做到这一点,我洗耳恭听)。

所以网站本质上是相当于锻炼日记的数字版本。用户从选择菜单中选择模板名称,然后在数据库中查询该模板,然后将结果返回到变量。练习名称和每个练习的组数(将用于计算表单刷新的最大次数)被传递到各自的数组中:$exerciseName[];和 $setNum[];

This is a screenshot of the form.我的问题是如何设置逻辑,以便我可以继续提交,直到最后一个练习的最后一组,最终提交后,将进入不同的页面。

我正在使用 mysql_ 函数,我知道这是不受欢迎的,但它是用于使用 PHP 5.2.12 的学校,这是我的队友所知道的,所以我没有其他选择。我没有尝试阻止 mysql 注入(inject),因为我不打算将此版本上线。

以下是选择锻炼类型和锻炼模板的代码:

    session_start();
$user = $_SESSION['email'];
//This script
$thisScript = htmlentities($_SERVER['PHP_SELF']);

if ($user) {
require("include/connect2db.inc.php");
require("include/htmlHead.inc");
//Default page buttons
$cardioBtn = $_POST['cardioBtn'];
$resistanceBtn = $_POST['resistBtn'];

//Cardio submit
$cardioSubmit = $_POST['cardioSubmit'];

if ((empty($cardioBtn))
&& (empty($resistanceBtn))
&& (empty($selectSubmit))
&& (empty($cardioSubmit))) {
echo <<<BODYDOC
<article id="newDayArticle">
<header>
<h2>Category</h2>
</header>
<fieldset id="ndFieldset">
<form action="$thisScript" method="POST" >
<button id="cardioButton" name="cardioBtn" value="cardioBtn" >Cardio</button>
<button id="resistanceButton" name="resistBtn" value="resistBtn" >Resistance</button>
</form>
</fieldset>
<!-- <div id="selection"></div>
<div id="template"></div> -->
</article>
BODYDOC;
} else if (isset($cardioBtn)) {
//Build cardio form
echo "<h2>Cardio</h2>";
echo <<<BODYDOC
<fieldset>
<legend>Cardio Log</legend>
<form action="$thisScript" method="POST">
<input type="number" name="distance" placeholder="Distance of Run" required />
<input type="number" name="duration" placeholder="Run Duration" required />
<button id="cardioSubmit" name="cardioSubmit">Submit</button>
<button id="back" type="button" onclick="document.location.href='newday.php';" value="Back">Back</button>
</form>
</fieldset>
BODYDOC;
} else if (isset($cardioSubmit)) {
$thisScript = htmlentities($_SERVER['PHP_SELF']);
//Cardio page
$distance = $_POST['distance'];
$duration = $_POST['duration'];
$date = date("Y-m-d");
//Submit cardio data to DB
updateCardio($distance, $duration, $user, $date);
//Show user stats in table
cardioStats($distance, $duration);
//End cardio form
} else if (isset($resistanceBtn)) {
//Workout template select
$selectSubmit = $_POST['selectSubmit'];
//page to select workout template
buildSelect();
//End resistance select
}//End else if

//Require footer
require("include/htmlFoot.inc");
mysql_close();
} else {
//Redirect users not logged in
require("include/redirect.php");
} //End redirect else

这里是选择函数和用于构建表单并将其插入数据库的函数。

    function buildSelect() {
//Check if resistance button submitted
//Query for template names
$query = "SELECT templateName, templatePosition
FROM templates
WHERE userID = 0
ORDER BY templatePosition";
$result = mysql_query($query)
or
die("<b>Query Failed</b><br /> $query<br />" . mysql_error());
//Find number of rows
$numRows = mysql_num_rows($result);

//Array with spaces/capitals
$templateArray = array();

//Array with no spaces/no capitals
$noSpacesArray = array();

//Get template names and build arrays
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$templateName = $row[0];
$position = $row[1];

//Build array in order by pushing to $templateArray
array_push($templateArray, $templateName);

//Build array without spaces or capitals in $noSpacesArray()
$templateName = str_replace(' ', '', $templateName);
$templateName = strtolower($templateName);
array_push($noSpacesArray, $templateName);
} //End while
}//End for
//Check array values
//print_r($templateArray);
//print_r($noSpacesArray);
//Build page
echo <<<BODYDOC
<br />
<h2>Resistance</h2>
<form action="log.php" method="POST" >
<fieldset>
<legend>Resistance Templates</legend>\n
BODYDOC;

echo "<select name='mySelect' id='mySelect'>\n";
echo "\t<option value=''>Choose One</option>\n";

//Build Template
//Build Template
for ($i=0; $i < count($templateArray); $i++) {
//value='$noSpacesArray[$i] is for no spaces, all lower case
//value='$templateArray[$i] is for First letter capital, with spaces
echo "\t<option value='$templateArray[$i]'>$templateArray[$i]</option>\n";
} //End list generation
echo "</select>\n";

echo <<<BODYDOC
<input type="submit" name="selectSubmit" value="Submit" />
<br />
</fieldset>
</form>
BODYDOC;
} //End function buildSelect

//Function uses template name as argument in an SQL query to find exercise template
//Returns exercise IDs, exercise names, and # of sets per exercise in that template
function getResult($template) {
//Query template name and get templateID
$query = "SELECT templateID
FROM templates
WHERE templateName = '$template'";

$result = mysql_query($query)
or
die("<b>Query Failed</b><br />$query<br />" . mysql_error());

//This part made me smash my head into a wall
$templateID = mysql_fetch_object($result);
$templateID = $templateID->templateID;

//Get exercise template, exercise names, and number of sets with query
$query = "SELECT exerciseID, exerciseName, numSets
FROM exercises
WHERE templateID = $templateID";

$result = mysql_query($query)
or
die("<b>Query Failed</b><br />$query<br />" . mysql_error());

return $result;
} //End getExercises
//Get number of exercises
function getExerciseNum($result) {
//Get number
$numRows = mysql_num_rows($result);
return $numRows;
}//End getExerciseNum
//Get exercise names as array
function exerciseList($result, $numRows) {
//Initialize exercise name array
$exerciseArray = array();
//Exercise array increment
//
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$exerciseName = $row[1];
//Push names to array
array_push($exerciseArray, $exerciseName);
} //End while
} //End for
//Return name array
return $exerciseArray;
}//End exerciseList()

//Get number of sets per exercise
function getSets($result, $numRows) {
//
$setsArray = array();
//
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$numSets = $row[2];
//Push to array
array_push($setsArray, $numSets);
} //End while
} //End for
//Return array
return $setsArray;
} //End setsPerExercise()

//Build log form using query result and exercise name increment ($x)
function buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date) {

$logSubmit = $_POST['logSubmit'];
//echo "numRows = " . $numRows;
static $x = 0;
echo "<br />X = $x";
if (empty($logSubmit)) {
echo "<form action='$thisScript' method='POST' name='log' id='log'>\n";
echo "<fieldset>\n";
echo "<legend>$template</legend>\n";

echo "<h2>$exerciseArray[0]</h2>\n";
echo "<input type='hidden' name='exerciseArray[]' value='$exerciseArray[$x]'/>\n";
$j = 1;
//Generate exercise form with loop
for ($i=0; $i < $setsArray[$i]; $i++) {

echo "<fieldset>";
echo "<legend>Set $j</legend>\n";
//Use $template in a hidden value to work around issue of value being lost after submitting form
echo <<<BODYDOC
<label>Weight</label>
<input type="text" name="weight[]" required /> \n

<label>Reps</label>
<input type="number" name="reps[]" required /> \n

<label>Rest Time</label>
<input type="number" name="rest[]" required /> \n

<label>Notes</label>
<textarea name="notes[]"></textarea>
<input type="hidden" name="set[]" value='$j' />
<input type="hidden" name='mySelect' value='$template' />

</fieldset>
BODYDOC;
$j++;
} //End form for loop
echo "<br /><button type='submit' name='logSubmit'>Submit</button>\n";
echo "</fieldset>\n";
echo "</form>\n";
echo "<p><a href='newday.php'>Back</a></p>\n";

//Increment exerciseNameArray counter so next form dispays next exercise name
} //End if empty submit
if (isset($logSubmit)) {
//POSTed
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];

//Update Log
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date);
} //End else if
} //End buildLog($template, $x) function

function updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date) {

//Insert data with query
$numRows = count($exerciseArray);
echo "count exerciseArray = " . $numRows;
for ($i=0; $i < $numRows; $i++) {
$insert[$i] = "INSERT INTO stats_resistance
(userID, template, exerciseName, set, weight, reps, rest, notes, date)
VALUES
('$user','$template', $exerciseArray[$i]','$set[$i]','$weight[$i]','$reps[$i]','$rest[$i]', '$notes[$i]', '$date')"
or
die(mysql_error());

$result[$i] = mysql_query($insert[$i])
or
die(mysql_error());
} //End for
//Increment $x and pass it back to buildLog
//$x++;
//return $x;
} //End updateLog()

这是 log.php 表单文件:编辑:向 PHP_SELF 添加了 htmlentities 并更改了一些逻辑。

    session_start();
//User
$user = $_SESSION['email'];
$date = date("Y-m-d");

//
$template = $_POST['mySelect'];
//Set log submit button
$logSubmit = $_POST['logSubmit'];

//Check if user is signed in
if ($user) {
if ($template) {
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);

//Return query
$result = getResult($template); //Returns result of template
//numRows
$numRows = getExerciseNum($result);
//Return exercise array
$exerciseArray = exerciseList($result, $numRows); //Returns set of exercises in template

//For some reason, $result and $numRows is empty after being passed into $exerciseArray
//Reinitialize
$result = getResult($template); //Returns result of template
//numRows
$numRows = getExerciseNum($result);
//Return sets per exercise as array
$setsArray = getSets($result, $numRows);

//Build form
buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date);

//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} else if (empty($template)){
//Do something if template is empty
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");

echo "<p>Seems the template is empty</p>\n";
echo "<p>Template = $template</p>\n";

//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} //End if ($template)
} /*else if (($user) && (isset($logSubmit))) {
//If user is signed in and log has been submitted
//Get form values and insert into database
require("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);

echo "<pre>\n";
echo "print_r of POST<br />";
print_r($_POST);
echo "</pre>\n";
//Get Workout and POST info
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];
//Check if form is submitted, if so, insert into db
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date);

echo "<p>Entered update log else/if block</p>\n";

//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
}*/ else if (!isset($user)) {
//If user not logged in
require("redirect.php");
}

最佳答案

您可以在表单的操作中使用 PHP_SELF (例如 <?php echo htmlentities ($ _ SERVER ['PHP_SELF']); ?> )。 See this article这解释了为什么我们需要htmlentities 。这个 PHP_SELF 变量包含当前脚本的路径。

您可以将所有逻辑放在模板之前,您应该检查以下内容:

  • 是否发生了页面提交?
    • 如果是,请检查提交的数据是否有错误。
      • 如果没有错误,则处理并保存信息。如果存在发送模板错误的数组。
  • 如果没有,则无需执行任何操作。

因此,当提交表单时,所有内容都将始终在同一页面上提交。

关于javascript - 重复自处理表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43562052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com