Repeat self-processing form - javascript

My question is over creating a self-processing form that inserts to a database and then refreshes, incrementing arrays to change relevant info in the form. (though if there is an easier or better way to do this, I'm all ears).
So site is essentially a digital equivalent to an exercise journal. The user selects a template name from a select menu, then it queries the database for that template, then returns the result to a variable. The exercise names and number of sets per exercise (which will be used to calculate maximum number of form refreshes) are passed into their own respective arrays: $exerciseName[]; and $setNum[];
This is a screenshot of the form.
My question is how to go about setting up the logic so that I can keep submitting until the last set of the last exercise, where upon the final submission, would take to a different page.
I am using mysql_ functions, which I know is frowned upon, but it is for school which uses PHP 5.2.12 and that is what my teammates know so I have no other options. I haven't tried to prevent mysql injections because I don't intend to take this version online.
Here is the code for selecting type of workout and workout template:
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
Here is the select function and functions for building the form and inserting it into the database.
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()
Here is the log.php form file:
Edit: Added htmlentities to PHP_SELF and changed some logic.
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");
}

You can use PHP_SELF (eg <?php echo htmlentities ($ _ SERVER ['PHP_SELF']); ?>) In the action of the form. See this article which explains why we need htmlentities. This PHP_SELF variable contains the path to the current script.
All the logic you can place where you have, before the template, where you should check the following:
Did happen a page submit?
If yes, check for errors with submitted data.
If there are no errors treats and saves the information. If there are send an array with errors for the template.
If not, nothing to do.
Thus, when there is submission of the form everything will always be submitted on the same page.

Related

Inserting value from one table to another in MySql with javascript and jQuery

I'm trying to get 3 values to insert from the table, 'parents' to the table, 'children' in MySql. One of the values, entitled "code" inserts perfectly. However, I can't get the other two, "email" and "website" to insert. When I add them to the javascript code, it just inserts "code" 3 times. Can someone help me please? Here's the code that inserts just the 'code' field from parents to children:
$("a#reply").one("click", function() {
var comCode = $(this).attr("name");
var parent = $(this).parent();
parent.append("<br /><form id='reply-form-toggle' action='' method='post'><input type='text' name='user' placeholder='Your Name *' required='required' required><br><textarea class='form-text' name='new-reply' id='new-reply' placeholder='Your Reply' required='required'></textarea><input type='hidden' name='code' value='"+comCode+"' /><span style='float: right;'><a onclick='hideReplyForm();'>Cancel</a> <input type='submit' class='form-submit' id='form-reply' name='new_reply' value='Reply' /></span></form>");
});
Here is the insertion code:
<?php
// new comment
if(isset($_POST['new_comment'])) {
$new_com_name = $_SESSION['user'];
$new_com_email = $_POST['email'];
$new_com_website = $_POST['website'];
$new_com_text = $_POST['comment'];
$new_com_date = date('Y-m-d H:i:s');
$new_com_code = generateRandomString();
// automatically inserts the ESCAPE CHARACTER - Now content will insert into database with single quote character
$new_com_name = addslashes($new_com_name);
$new_com_email = addslashes($new_com_email);
$new_com_website = addslashes($new_com_website);
$new_com_text = addslashes($new_com_text);
if(isset($new_com_text)) {
$sql = "INSERT INTO `parents` (`user`, `email`, `website`, `text`, `date`, `code`) VALUES ('$new_com_name', '$new_com_email', '$new_com_website', '$new_com_text', '$new_com_date', '$new_com_code')";
$result=$dbCon->query($sql);
if ($result === TRUE) {
echo "<script type='text/javascript'>alert('Thank you for your comment! We will review it and hopefully approve it within 24 hours.');</script>";
}else{
echo "<script type='text/javascript'>alert('Your comment has not been submitted.');</script>";
}
}
header("Location: ");
}
// new reply
if(isset($_POST['new_reply'])) {
$new_reply_name = $_SESSION['user'];
$new_reply_email = $_POST['email'];
$new_reply_website = $_POST['website'];
$new_reply_text = $_POST['new-reply'];
$new_reply_date = date('Y-m-d H:i:s');
$new_reply_code = $_POST['code'];
// automatically inserts the ESCAPE CHARACTER - Now content will insert into database with single quote character
$new_reply_name = addslashes($new_reply_name);
$new_reply_email = addslashes($new_reply_email);
$new_reply_website = addslashes($new_reply_website);
$new_reply_text = addslashes($new_reply_text);
if(isset($new_reply_text)) {
$sql = "INSERT INTO `children` (`user`, `par_email`, `par_website`, `text`, `date`, `par_code`) VALUES ('$new_reply_name', '$new_reply_email', '$new_reply_website', '$new_reply_text', '$new_reply_date', '$new_reply_code')" or die(mysqli_error());
$resultReply=$dbCon->query($sql);
if ($resultReply === TRUE) {
echo "<script type='text/javascript'>alert('Thank you for your reply! We will review it and hopefully approve it within 24 hours.');</script>";
}else{
echo "<script type='text/javascript'>alert('Your reply has not been submitted.');</script>";
}
}
header("Location: ");
}
?>

It cant loop other polls out. It just can show the first id of the polls

It always come out with one polls only. Although i have different polls saved in database. It always can show the first id of the database.
<form action="" method="post" name="pollFrm">
<?php
//include and initialize Poll class
include 'Poll.class.php';
$poll = new Poll;
//get poll and options data
$pollResult= $poll->getPolls();
?>
<div class="pollContent">
<?php echo !empty($statusMsg)?'<p class="stmsg">'.$statusMsg.'</p>':''; ?>
<form action="" method="post" name="pollFrm">
<h3><?php echo $pollResult['poll']['subject']; ?></h3>
<ul>
<?php foreach($pollResult['name'] as $opt){
echo '<li><input type="radio" name="voteOpt" value="'.$opt['id'].'" >'.$opt['name'].'</li>';
} ?>
</ul>
<input type="hidden" name="pollID" value="<?php echo $pollResult['poll']['id']; ?>">
<input type="submit" name="voteSubmit" class="button" value="Vote">
Results
</form>
</div>
</form>
This is the function to get polls. I have try to delete the single. but it cant works.
public function getPolls($pollType){
$pollData = array();
$sql = "SELECT * FROM ".$this->pollTbl." WHERE status = '1' ORDER BY created DESC";
$pollResult = $this->getQuery($sql, $pollType);
if(!empty($pollResult)){
if($pollType == 'single'){
$pollData['poll'] = $pollResult;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$pollResult['id']." AND status = '1'";
$optionResult = $this->getQuery($sql2);
$pollData['name'] = $optionResult;
}else{
$i = 0;
foreach($pollResult as $prow){
$pollData[$i]['poll'] = $prow;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$prow['id']." AND status = '1'";
$optionResult = $this->getQuery($sql2);
$pollData[$i]['name'] = $optionResult;
}
}
}
return !empty($pollData)?$pollData:false;
}
/*
* Runs query to the database
* #param string SQL
* #param string count, single, all
*/
private function getQuery($sql,$returnType = ''){
$result = $this->db->query($sql);
if($result){
switch($returnType){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
return !empty($data)?$data:false;
}
Your function getPolls has a default parameter of $pollType = 'single' passing nothing through to the function will result it resolving to the default of 'single'.
As that parameter is being passed down to getQuery function it's always only going to get one. I would suggest removing the default parameter entirely and changing the method to:
public function getPolls($pollType){

Uncaught ReferenceError: output is not defined when using jQuery $.post() in file file

I have a dynamic search which uses jQuery and a PHP search file to dynamically show the results below. I just changed my log in scripts and sessions; now i am having issues with a search bar that searches through the members in a DB. When I was going through the testing I see that on each keyUp the jQuery function runs properly but there is some sort of issue inside of my search.php file. It seems like there is no $userCount or $userCount = 0 because it will display "There Were No Search Results"which only happens when it equals $userCount== 0
Here are the parts of my index.php
<script type="text/javascript">
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt == '') {
// $.post("includes/search.php", {searchVal:searchTxt},
// function(output){
// $("#userResults").html(output);
// });
}else{
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
console.log(output);
}
}
</script>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Or Last Name | Press Space To View All Employees" onkeyup="searchUserQ();" />
<submit type="submit" />
div id="userResults">
</div>
</form>
and here is my search.php file
<?php
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%' or
lastName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$passwordQ = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$passwordQ' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Any suggestions why this is happening?
The reason for the error in the title is that you have console.log(output) outside the callback function. This has two problems: First, the variable output is not in scope; second, it runs immediately, not after the AJAX call returns. Move it into the callback:
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
console.log(output);
$("#userResults").html(output);
});
}
}

Get mysql column of a clicked item

I have searched endlessly for an answer but have found none. I am trying to get the id of a clicked item. The item that I am clicking is from mysql database and has been displayed through a for loop. When the item is clicked I am taken to another page. In this page I want to utilize the id from the clicked item to get other information from that row in mysql database; this much I can do. The problem is getting the id from the clicked item and sending it.
This is the most recent way that I tried:
First I displayed the items from mysql.
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
$code = "<div id=\"challenge_preview\"><h7 class=\"challenge_preview_item\"
id=\"challenge_preview_name\"></h7><a href=\"challengeprofile.php\">
<video
class=\"challenge_preview_item\" id=\"challenge_video\"
src=\"".mysql_result($result, $i)."\"></video></a></div>";
echo $code;
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
Than I put the id in a hidden form so that I could attempt to POST it to the other page:
<form action="<?php echo $current_file; ?>" method="POST">
<input type="hidden" name="id" value="14">
</form>
On the script.php file that is included in both pages, I put
$(#challenge_video).click(function(){ <?php $id = $_POST['id']; ?> ;});
And on the page that the id is being posted to I put
<?php
include 'script.php';
echo getChallengeData('name', 'id', $id)
?>
Please help, Thank you
These are the edits
<div id='challenge_previews'>
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
echo "<div id=\"challenge_preview\"><video class=\"challenge_preview_item challenge_video\" src=\"".mysql_result($result, $i)."\"></video></div>";
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
<form action="<?php echo $current_file; ?>" method="GET">
<input type="hidden" name="id" value="14">
</form>
</div>
This is the code for page 2
<h1 id="challenge_profile_name">
<?php
$id = substr(base64_decode($_GET['id']),6);
echo getChallengeData('name', 'id', $id);
?>
</h1>
This is the code for the getChallengeData method in the core.inc.php
function getChallengeData($field1, $field2, $field3)
{
$query = "SELECT `$field1` FROM `challenge_name` WHERE `$field2` = '$field3'";
if($query_run = mysql_query($query))
{
if($query_result = mysql_result($query_run, 0, $field1))
{
return $query_result;
}
}
}
That error that I'm getting has to do with the implementation of the getChallengeData method on page 2. The error says
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 10 in C:\xampp\htdocs\ChallengeNetworkWebsite\core.inc.php on line 42

Create session variables out of looped database values

I am attempting to create a variable from a database array when an HTML link is clicked. The goal is to redirect the user to a form populated using one piece of array data. In other words, the database will be queried and form populated according to which link is clicked (whatever the values of $row[1], $row[2], and $row[3] are).
<?php
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
If anyone can provide me with some incite as to how I could accomplish this I'd appreciate it greatly.
Please read more about sessions here
Then, to answer your question:
First you need to start the session, as simple as session_start(); on the top of your script.
Second you need to instantiate session variables with the DB values like this: $_SESSION['var'] = $value;.
Third, in the html file or whatever, where the form relies, just check for it:
if(isset($_SESSION['var'])) {
echo '<input type="text" value="'.$_SESSION['var'].'" />';
} else {
echo '<input type="text" value="" />';
}
and use the value if it is set.
L.E:
So... first thing's first... session_start(); without it, there is no point of having session.
Second, you create it like $_SESSION['some_name'] = $row[1] so that var will keep the value from $row[1]. I am presuming that it's the value you need. Do NOT do do it like $_SESSION['$row1'] because first of all this is incorrect, you will NOT have the value of row1 there. You need an unique name so that you can call it where you have the form.
The above code will become something like this:
<?php
session_start();
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
$_SESSION['first_row'] = $row[1];
$_SESSION['second_row'] = $row[2];
$_SESSION['third_row'] = $row[3];
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
and, where you have the form and the <input type = "text" value = "" /> so where you need the value, just do it like this:
<input type = "text" value = "<?php echo (isset($_SESSION['first_row']) ? $_SESSION['first_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['second_row']) ? $_SESSION['second_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['third_row']) ? $_SESSION['third_row'] : ''); ?>" />
Hope this helps! :D

Categories

Resources