Recently we had a project due that I did not do very well on. I know it wont help my current grade, but I think understanding the concepts will be extremely beneficial to me in the long run. The assignment was to create a movie survey.
This is what I have so far for my formprocessor.php
<body>
<H1><u>The Vermont Web Designers Movie Survey</u></h1>
<?php
//I want to hold the users information that they entered, so they know that this is their survey
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
print "<p>$firstName $lastName's Movie Review - Spring 2018</p><hr>";
//I have values from 1 to 5 (ratings), I want to create a variable for each of them
$great = 0;
$good = 0;
$ok = 0;
$soso= 0;
$terrible = 0;
//I create an array to hold my selections. One for the movie ratings, another for the actor ratings.
$movieChoice = array($_POST['movie1'], $_POST['movie2'], $_POST['movie3']);
$actorChoice = array($_POST['actors1'], $_POST['actors2'], $_POST['actors3']);
//I use a loop to collect my movie choices.
for($i = 0; $i < 3; $i++){
if($movieChoice[$i] == 1){
//I increase the variable by 1 if it was selected.
$great++;
}
else if($movieChoice[$i] == 2){
$good++;
}
else if($movieChoice[$i] == 3){
$ok++;
}
else if($movieChoice[$i] == 4){
$soso++;
}
else{
$terrible++;
}
}
//I use another loop to hold my actor selections.
for($i = 0; $i < 3; $i++){
if($actorChoice[$i] == 1){
$great++;
}
else if($actorChoice[$i] == 2){
$good++;
}
else if($actorChoice[$i] == 3){
$ok++;
}
else if($actorChoice[$i] == 4){
$soso++;
}
else{
$terrible++;
}
}
print ('<table align= "center">
<tr><th colspan= "3">Movie</th>
<th>Question</th>
<th>Great</th>
<th>Good</th>
<th>Ok</th>
<th>So-So</th>
<th>Terrible</th>
</tr>
<tr><td colspan= "3">1: The Godfather Part 1</td>
<td>Quality of Movie</td>
<td>'.$movieChoice[$great].'</td>
<td>'.$movieChoice[$good].'</td>
<td>'.$movieChoice[$ok].' </td>
<td>'.$movieChoice[$soso].'</td>
<td>'.$movieChoice[$terrible].'</td>
</tr>
<tr><td colspan= "3"> </td>
<td>Quality of Actors</td>)
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr><td colspan= "3">2: Men of Honor</td>
<td>Quality of Movie</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr><td colspan= "3"> </td>
<td>Quality of Actors</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr><td colspan= "3">3: Three Days of the Condor</td>
<td>Quality of Movie</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr><td colspan= "3"> </td>
<td>Quality of Actors</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>');
?>
This is my form
<H1><u>The Vermont Web Designers Movie Survey</u></h1>
First Name: <input type= "text" size= "10" maxlength= "25" name= "firstName">
Last Name: <input type= "text" size= "10" maxlength= "25" name= "lastName"><br />
<hr>
<p>Please use a scale of 1 (first-rate; great; awesome) through 5 (really terrible) to answer each of these questions</p><br />
<hr>
<table align= "center">
<tr><th colspan= "3">Movie </th>
<th>Question</th>
<th>Great</th>
<th>Good</th>
<th>Ok</th>
<th>So-So</th>
<th>Terrible</th>
</tr>
<tr><td colspan= "3">1: The Godfather Part 1</td>
<td>Quality of Movie</td>
<td><input type= "radio" name= "movie1" value="1">1</td>
<td><input type= "radio" name= "movie1" value="2">2</td>
<td><input type= "radio" name= "movie1" value="3">3</td>
<td><input type= "radio" name= "movie1" value="4">4</td>
<td><input type= "radio" name= "movie1" value="5">5</td>
</tr>
<tr><td colspan= "3"> </td>
<td>Quality of Actors</td>
<td><input type= "radio" name= "actors1" value="1">1</td>
<td><input type= "radio" name= "actors1" value="2">2</td>
<td><input type= "radio" name= "actors1" value="3">3</td>
<td><input type= "radio" name= "actors1" value="4">4</td>
<td><input type= "radio" name= "actors1" value="5">5</td>
</tr>
<tr><td colspan= "3">2: Men of Honor</td>
<td>Quality of Movie</td>
<td><input type= "radio" name= "movie2" value="1">1</td>
<td><input type= "radio" name= "movie2" value="2">2</td>
<td><input type= "radio" name= "movie2" value="3">3</td>
<td><input type= "radio" name= "movie2" value="4">4</td>
<td><input type= "radio" name= "movie2" value="5">5</td>
</tr>
<tr><td colspan= "3"> </td>
<td>Quality of Actors</td>
<td><input type= "radio" name= "actors2" value="1">1</td>
<td><input type= "radio" name= "actors2" value="2">2</td>
<td><input type= "radio" name= "actors2" value="3">3</td>
<td><input type= "radio" name= "actors2" value="4">4</td>
<td><input type= "radio" name= "actors2" value="5">5</td>
</tr>
<tr><td colspan= "3">3: Three Days of the Condor</td>
<td>Quality of Movie</td>
<td><input type= "radio" name= "movie3" value="1">1</td>
<td><input type= "radio" name= "movie3" value="2">2</td>
<td><input type= "radio" name= "movie3" value="3">3</td>
<td><input type= "radio" name= "movie3" value="4">4</td>
<td><input type= "radio" name= "movie3" value="5">5</td>
</tr>
<tr><td colspan= "3"> </td>
<td>Quality of Actors</td>
<td><input type= "radio" name= "actors3" value="1">1</td>
<td><input type= "radio" name= "actors3" value="2">2</td>
<td><input type= "radio" name= "actors3" value="3">3</td>
<td><input type= "radio" name= "actors3" value="4">4</td>
<td><input type= "radio" name= "actors3" value="5">5</td>
</tr>
</table>
<hr>
<input type= "submit" value= "submit">
</form>
The real problem that I'm having trouble with is filling my array of movie choices, and actor choices, then printing that data for the user.
This is what I get when I run my code:
This is what I should be getting
DB Setup:
movies table
Fields: movie_id, movie_title
movie_ratings table
Fields: movie_ratings_id, movie_id, user_id, rating
actor_ratings table
Fields: actor_ratings_id, movie_id, user_id, rating
This way, you can store each individual rating individually, and do a COUNT and GROUP BY on your sql statement. That may get a little intense, since you're doing basic DB manipulation. You could always do a SELECT *, and then increase your Movie Ratings based on something like below.
The scope of this is not within answering the question though, and if you'd like to message/chat me, I can help you out that way.
ORIGINAL ANSWER BELOW:
First get your results from the database
$sql = "SELECT * FROM ratings";
// fetch results
Now that you have the results, you can structure it properly
I would do something like this. The reason I choose to do this is because then you have an associate array with named keys, and you'll be able to recall them later in a foreach loop or something similar.
$movieChoices = array(
array('title'=>"The Godfather Part 1",
'movieRatings' => array(
"great" => 0,
"good" => 0,
"ok" => 0,
"soso"=> 0,
"terrible" => 0,
),
'actorRatings' => array(
"great" => 0,
"good" => 0,
"ok" => 0,
"soso"=> 0,
"terrible" => 0,
)
),
array('title'=> "Men Of Honor",
'movieRatings' => array(
"great" => 0,
"good" => 0,
"ok" => 0,
"soso"=> 0,
"terrible" => 0,
),
'actorRatings' => array(
"great" => 0,
"good" => 0,
"ok" => 0,
"soso"=> 0,
"terrible" => 0,
)
),
array('title'=>"Three Days of Condor",
'movieRatings' => array(
"great" => 0,
"good" => 0,
"ok" => 0,
"soso"=> 0,
"terrible" => 0,
),
'actorRatings' => array(
"great" => 0,
"good" => 0,
"ok" => 0,
"soso"=> 0,
"terrible" => 0,
)
)
);
Which will give you something like this:
Array
(
[0] => Array
(
[title] => The Godfather Part 1
[movieRatings] => Array
(
[great] => 0
[good] => 0
[ok] => 0
[soso] => 0
[terrible] => 0
)
[actorRatings] => Array
(
[great] => 0
[good] => 0
[ok] => 0
[soso] => 0
[terrible] => 0
)
)
[1] => Array
(
[title] => Men Of Honor
[movieRatings] => Array
(
[great] => 0
[good] => 0
[ok] => 0
[soso] => 0
[terrible] => 0
)
[actorRatings] => Array
(
[great] => 0
[good] => 0
[ok] => 0
[soso] => 0
[terrible] => 0
)
)
[2] => Array
(
[title] => Three Days of Condor
[movieRatings] => Array
(
[great] => 0
[good] => 0
[ok] => 0
[soso] => 0
[terrible] => 0
)
[actorRatings] => Array
(
[great] => 0
[good] => 0
[ok] => 0
[soso] => 0
[terrible] => 0
)
)
)
Store your post variables the same way for ease of code use.
$movieChoice = array($_POST['movie1'], $_POST['movie2'], $_POST['movie3']);
$actorChoice = array($_POST['actors1'], $_POST['actors2'], $_POST['actors3']);
Use a loop to store both items.
There's no sense in looping through the same thing twice. Re use the code.
I use += 1, because it's more apparent what you're doing to the variable.
It's the same thing as ++, it's just my preference.
Also, while you're in here, you could write a SQL statement to update the row in the Database.
$sql = "UPDATE movie_ratings SET RATING = RATING + 1 WHERE movie_id = MOVIE_ID";
But, that's for later. So go ahead and update your current values you already have.
for ($i = 0; $i < 3; $i++) {
if ($movieChoice[$i] == 1) {
//I increase the variable by 1 if it was selected.
$movieChoices[$i]['movieRatings']["great"] += 1;
} else if ($movieChoice[$i] == 2) {
$movieChoices[$i]['movieRatings']['good'] += 1;
} else if ($movieChoice[$i] == 3) {
$movieChoices[$i]['movieRatings']['ok'] += 1;
} else if ($movieChoice[$i] == 4) {
$movieChoices[$i]['movieRatings']['soso'] += 1;
} else {
$movieChoices[$i]['movieRatings']['terrible'] += 1;
}
if ($actorChoice[$i] == 1) {
//I increase the variable by 1 if it was selected.
$movieChoices[$i]['actorRatings']["great"] += 1;
} else if ($actorChoice[$i] == 2) {
$movieChoices[$i]['actorRatings']['good'] += 1;
} else if ($actorChoice[$i] == 3) {
$movieChoices[$i]['actorRatings']['ok'] += 1;
} else if ($actorChoice[$i] == 4) {
$movieChoices[$i]['actorRatings']['soso'] += 1;
} else {
$movieChoices[$i]['actorRatings']['terrible'] += 1;
}
}
Now when you want to print the results, it's even easier to do so. You can use a foreach() loop to go through each movie result, and print their individual values out. Much easier than what you were doing, less code.
print '
<table align="center">
<tr>
<th colspan="3">Movie</th>
<th>Question</th>
<th>Great</th>
<th>Good</th>
<th>Ok</th>
<th>So-So</th>
<th>Terrible</th>
</tr>';
foreach($movieChoices as $choice) {
print '
<tr>
<td colspan="3">'.$choice['title'].'</td>
<td>Quality of Movie</td>
<td>'.$choice['movieRatings']['great'].'</td>
<td>'.$choice['movieRatings']['good'].'</td>
<td>'.$choice['movieRatings']['ok'].' </td>
<td>'.$choice['movieRatings']['soso'].'</td>
<td>'.$choice['movieRatings']['terrible'].'</td>
</tr>
<tr>
<td colspan="3"> </td>
<td>Quality of Actors</td>
<td>'.$choice['actorRatings']['great'].'</td>
<td>'.$choice['actorRatings']['good'].'</td>
<td>'.$choice['actorRatings']['ok'].' </td>
<td>'.$choice['actorRatings']['soso'].'</td>
<td>'.$choice['actorRatings']['terrible'].'</td>
</tr>
';
}
print '</table>';
In all honesty, this is a REALLY long result for this bit of code. If I had more to work with, I could break it down to a lot simpler for you. However, this will help with what you're trying to do.
I had some free time and decided to play around with your idea. You should be able to copy/paste this into a single file and it should work.
I don't intend my answer to be a final solution but I hope that it gives you some new ideas about to structure your program. Feel free to pick and choose what you will from it.
The main idea here is that it is storing the user's selections into the session so that we can increment it and display a running total in the last table. I tried to document the code as I went along but pls feel free to ask questions.
I've also tried to make it relatively dynamic so you can add movies, questions, choices and the form and form processor should handle it OK as long as you keep the data structures the same. The arrays that store the movies, choices, and questions also use associative keys (strings such as '1', '2' etc.) which slightly mimics what a relational DB would use. Add/remove elements to these arrays to see how the form changes.
Finally, there are some language constructs (??, square arrays []) which require PHP 7 to run. There are also some lines of code which are... ugly. I didn't try to find a nicer way to code them.
Ex. list($movieId, $questionId) = array_pad(explode('_', $key, 2), 2, null);.
Let me know if you run into issues.
<?php
session_start();
// The following 3 arrays just store movie, choices, and questions
// which we will use in form processing and also to display the form to the user.
// Could come from DB, file, or hard-coded like this.
//
// Play around with these 3 arrays to see how the application changes.
// A list of movies.
$movies = [
[
'id' => '1',
'title' => 'Taxi Driver',
'director' => 'Mr. Scor-say-zee',
],
[
'id' => '2',
'title' => 'The Mask',
'director' => 'I do not know',
],
];
// A list of choices that a user can select.
$choices = [
'1' => 'Terrible',
'2' => 'So-So',
'3' => 'OK',
'4' => 'Good',
'5' => 'Great',
];
// A list if rating categories.
$questions = [
'1' => 'Quality of Movie',
'2' => 'Quality of Actors',
'3' => 'Quality of Producers',
];
// The reset button was clicked. Clear the session and redirect back to self.
if (isset($_POST['reset'])) {
session_destroy();
header('Location: ' . $_SERVER['PHP_SELF']);
die;
}
// The form was submitted. Store the user's selection in to the session.
// Storing it in the session for simplicity but could store it to a file or DB or some other persistent storage.
if (isset($_POST['submit'])) {
// Loop over the POST data and extract the question ID and movie ID for each submitted answer.
foreach ($_POST as $key => $value) {
// The incoming POST data looks like: 1_1, 2_1, 2_2 etc.
// Split the string on the underscore which will give us the movie ID and question ID respectively.
// Once we know which movie and question is submitted store them, along with the actual rating, in the session.
// If it doesn't exist in the session, set it to 1.
// If it does exist in the session, just increment the value.
list($movieId, $questionId) = array_pad(explode('_', $key, 2), 2, null);
if (is_numeric($questionId) && is_numeric($movieId)) {
// Check if it is in the session already.
if (!isset($_SESSION['ratings'][$movieId][$questionId][$value])) {
$_SESSION['ratings'][$movieId][$questionId][$value] = 1;
} else {
$_SESSION['ratings'][$movieId][$questionId][$value] = $_SESSION['ratings'][$movieId][$questionId][$value] + 1;
}
}
}
}
?>
<!-- Display the form -->
<form method="post">
<?php
foreach ($movies as $movie) {
echo '<h2>' . $movie['title'] . '</h2>';
foreach ($questions as $questionId => $questionDescription) {
echo '<h3>' . $questionDescription . '</h3>';
foreach ($choices as $choiceValue => $choiceDescription) {
// Each row will have a name like: 1_1, 1_2, 2_1 etc.
// These represent the movie ID and question ID respectively.
// During form processing (above) we split the name on the underscore which give use the movie ID and question ID that the user submitted.
// There is a probably a better way to do this.
echo '<label>';
echo '<input type= "radio" name= "' . $movie['id'] . '_' . $questionId . '" value="' . $choiceValue . '">';
echo $choiceDescription;
echo '</label>';
}
}
echo '<hr />';
}
?>
<br>
<br>
<input type="submit" name="submit" value="Submit">
<input type="submit" name="reset" value="Reset">
</form>
<!-- Display the results from the session -->
<table border="1">
<caption>Favorite and Least Favorite Things</caption>
<tr>
<th>Movie</th>
<th>Question</th>
<?php
echo "<th>" . implode('</th> <th>', $choices) . "</th>";
?>
</tr>
<?php
foreach ($movies as $movie) {
echo '<tr>';
// Notice the rowspan grows with each question added.
echo '<th rowspan="' . count($questions) . '">' . $movie['title'] . '</th>';
foreach ($questions as $questionId => $questionDescription) {
// Open a new row on the 2nd and subsequent iterations.
if ((int)$questionId > 1) {
echo '<tr>';
}
echo '<th>' . $questionDescription . '</th>';
// Output the actual ratings from the session.
foreach ($choices as $choiceId => $choiceDescription) {
echo '<th>';
echo $_SESSION['ratings'][$movie['id']][$questionId][$choiceId] ?? 0;
echo '</th>';
}
}
echo '</tr>';
}
?>
</table>
I have a record fetch from database based on a dropdown selection.The result is shown as a table, in which the user is expected to tick his choice.After the selection,the user clicks a button which will automatically add his selection to a table.Now the issue is: the id that is fetched for each item changes when the button is clicked by turning it to ascending number.see image below:
For instance, in the table below, id 773,774,777,895 and 901 are selected.When Add to Float Button is cliked, the Id now becomes: 773,774,775,776,777(arranged ascending). See code below:
for Displaying Table
<table>
<tr>
<td><input type="text" value="<?php echo $r['item_code'];?>" name="itmcode[]" readonly="readonly"/></td>
<td><?php echo $r['description'];?></td>
<td><?php echo $r['qty'];?></td>
<td><?php echo $r['price_per_qty'];?>
<td><input type="text" value="<?php echo $r['total_value'];?>" name="tvalue[]" readonly="readonly" /></td>
<td><?php echo $r['preferred_supplier'];?></td>
<td><input type="checkbox" name="chkbx[]" value="<?php echo $r['id'];?>">
<input type="hidden" name="gid[]" value="<?php echo $r['id'];?>">
</tr>
</table>
Processing Script:
<?php
if(array_key_exists('chkbx', $_POST)&&(!empty($_POST['chkbx']))&&(isset($_POST['floatBtn']))){
foreach($_POST['chkbx'] as $rec=>$value)
{
$itm = $_POST['itmcode'][$rec];
$tval = $_POST['tvalue'][$rec];
$t = $_POST['gid'][$rec];
$apno =$_POST['aNo'];
$fno = $_POST['fno'];
echo "itm:".$itm." tval: ".$tval." t:".$t." appno:".$apno."fno:".$fno."<br/>";
}
}
?>
How can I correct this, so that it can display the correct id when the button is clicked after selecting.
Change your code like this
<table>
<tr>
<td><input type="text" value="<?php echo $r['item_code'];?>" name="itmcode[]" readonly="readonly"/></td>
<td><?php echo $r['description'];?></td>
<td><?php echo $r['qty'];?></td>
<td><?php echo $r['price_per_qty'];?>
<td><input type="text" value="<?php echo $r['total_value'];?>" name="tvalue[]" readonly="readonly" /></td>
<td><?php echo $r['preferred_supplier'];?></td>
<td><input type="checkbox" name="chkbx[]" value="<?php echo $r['id'];?>">
//change gid[] to gid[<?php echo $r['id'];?>]
<input type="hidden" name="gid[<?php echo $r['id'];?>]" value="<?php echo $r['id'];?>">
</td>
</tr>
</table>
in processing
<?php
if(array_key_exists('chkbx', $_POST)&&(!empty($_POST['chkbx']))&& (isset($_POST['floatBtn']))){
foreach($_POST['chkbx'] as $rec=>$value)
{
$itm = $_POST['itmcode'][$rec];
$tval = $_POST['tvalue'][$rec];
$t = $_POST['gid'][$value]; //--> changed from $_POST['gid'][$rec] to $_POST['gid'][$value]
$apno =$_POST['aNo'];
$fno = $_POST['fno'];
echo "itm:".$itm." tval: ".$tval." t:".$t." appno:".$apno."fno:".$fno."<br/>";
}
}
?>
The issue when you post the data with the checkbox checked, you get an array like this
Array
(
[itmcode] => Array
(
[0] => 1"
[1] => 1"
[2] => 1"
)
[tvalue] => Array
(
[0] => 5
[1] => 5
[2] => 5
)
[chkbx] => Array
(
[0] => 1
)
[gid] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
so when looping the $_POST['chkbx'], the value for
`$_POST['gid'][$rec] always loops with the keys of $_POST['chkbx'] which is 0,1,2 etc always. So you get values of $_POST['gid'][0], $_POST['gid'][1],$_POST['gid'][2], etc which is 773, 774, 775 respectively.
I've got a list of form fields in an html table. This page is designed to allow someone to modify multiple records at once...using an update query. Because I have multiple customer records present, I need to update based on the record Id. I thought that I was supposed to create a composite array then update the database by pointing to the various key, value pairs, but nothing seems to work...all help is appreciated..hoping its a small typo I'm not catching:
....SQL to pull data (works)...
echo "<form action='#' method='POST' >";
echo "<center><table>";
echo "<tr><th> Email Address </th> <th>Created On</th><th> Ip Address</th><th> Front of Card</th><th> Back of Card</th><th> Last 4 of Card</th><th> Decision</th><th> Notes (for Reject)</th>";
foreach ($customer as $row){
echo '<tr><input type="hidden" name="record[]" value='.$row[' id '].'/>
<td>'.$row["email"].' </td>
<td>'.$row["created_on"].'</td>
<td>'.$row["ip_address"].'</td>
<td>
<img class="fixed" src="imgReader.php?img='.$row[" card_front "].'"/>
</td>
<td>
<img class="fixed" src="imgReader.php?img='.$row[" card_back "].'"/>
</td>
<td><input type="number" name="last4[]" value="" /></td>
<td><select name="decision[]">
<option value="PENDING">Pending</option>
<option value="APPROVED">Approved</option>
<option value="DENIED">Denied</option>
<option value="DUPLICATE">Duplicate</option></select></td>
<td><input type="textarea" rows="5" name="notes[]" value="" /></td>
</tr>';
if ($_POST){
$last4 = $_POST["last4"];
$status = $_POST["decision"];
$notes = $_POST["notes"];
$ids = $_POST["record"];
$tableSet = array('last4' => $last4,
'decision' => $status,
'notes' => $notes,
'ids' => str_replace('/','', $ids)
);
var_dump($tableSet);
foreach( $tableSet as $i) {
$updateUserData = $db->prepare("UPDATE cards SET `last_4_cc` = :l4cc, `status` = :status, `notes` = :notes WHERE `id` = :record");
$updateUserData->execute([
':l4cc' => $i[$tableSet["last4"]],
':status' => $i[$tableSet["decision"]],
':notes' => $i[$tableSet["notes"]],
':record' => $i[$tableSet["ids"]]
]);
}
}
?>
This is my html codes for dynamic table rows. This duplicate the table fields by clicking the Add new button. The problem is I cannot insert all the filled data into the database. It would be nice if you can help me. Thanks a lot.
<!-- Time&Task -->
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<br>
<table class="table table-striped" id="maintable" width="50%" cellpadding="0" cellspacing="0" class="pdzn_tbl1" border="0px">
<tr>
<th>Time Start:</th>
<th>Time End:</th>
<th>Task:</th>
<th>Comment:</th>
</tr>
<tr class="rows">
<td style="padding:5px;">
<input type="time" name="item[0][timestart]" />
</td>
<td style="padding:5px;">
<input type="time" name="item[0][timeend]" />
</td>
<td style="padding:5px;">
<input type="text" name="item[0][tasks]" />
</td>
<td style="padding:5px;">
<input type="text" name="item[0][comment]" />
</td>
</tr>
</table>
<div id="add_new">ADD NEW</div>
<?php
if (isset($_POST['item']) && is_array($_POST['item'])) {
$items = $_POST['item'];
$i = 0;
foreach($items as $key => $value) {
echo 'Item '.$i++.': '.$value['timestart'].' '.$value['timeend'].' '.$value['tasks'].' '.value['comment'].'<br />';
}
}
?>
</div>
</div>
</div><!-- /.box-body -->
This is my sql query for inserting. here is the problem. I don't know how to loop to insert into the DB. Thanks. :D
<?php
if (isset($_POST['data']) && !empty($_POST['data'])) {
$timestart = htmlspecialchars($_POST['timestart']);
$timeend = htmlspecialchars($_POST['timeend']);
$tasks = htmlspecialchars($_POST['tasks']);
$comment = htmlspecialchars($_POST['comment']);
include('DBConnect.php');
$SQL = "INSERT INTO TSTable (timestart,timeend,tasks,comment) VALUES ('$timestart','$timeend','$tasks','$comment')";
if (mysqli_query($conn, $SQL)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
! Hi all, I found a solution already. Here are the correct codes. I hope it helps someone who needs it.
The html is still the same and only sql query part needed to fix.
if (isset($_POST['data'])) {
$timestart = $_POST['timestart'];
$timeend = $_POST['timeend'];
$tasks = $_POST['tasks'];
$comment = $_POST['comment'];
include('DBConnect.php');
$count= count($timestart);
for ($i=0; $i< $count; $i++){
if($timestart[$i] != null || !empty($timestart[$i])){
$SQL = "INSERT INTO TSTable (timestart,timeend,tasks,comment) VALUES ( '$timestart[$i]','$timeend[$i]','$tasks[$i]','$comment[$i]')";
}
if (mysqli_query($conn, $SQL)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
}
There are a few things here that will make your life easier if changed.
Input elements with the same name will be submitted as an array, in the order they appear. Standard procedure is to layout your html like so (a few fields removed for brevity);
<td><td><input name=timestart><input name=timeend><input name=tasks></td></tr>
<td><td><input name=timestart><input name=timeend><input name=tasks></td></tr>
<td><td><input name=timestart><input name=timeend><input name=tasks></td></tr>
... etc
This will give you a post structure such as ;
Array
(
[timestart] => Array
(
[0] => timestart 1
[1] => timestart 2
[2] => timestart 3
)
[timeend] => Array
(
[0] => timeend 1
[1] => timeend 2
[2] => timeend 3
)
[task] => Array
(
[0] => task 1
[1] => task 2
[2] => task 3
));
And insert with;
$timestart = $_POST['timestart'];
$timeend = $_POST['timeend'];
$task = $_POST['task'];
for($i=1 ; $i < count($timestart) ; $i++)
{
$sql = "INSERT INTO TSTable VALUES($timestart[$i],$timeend[$i],$task[$i]);"
... more code goes here..
}
I have the following table that fetches data from the database:
while($row = mysql_fetch_array($result))
{
echo '
<tr>
<td width="320">
<input type="checkbox" name="product_ID[]" value="'.$row['Product_ID'].'" />'.$row['Product_description'].'<br />
</td>
<td width="50">
<input type="text" name="product_cost[]" value="'.$row['Product_Retail_cost'].'" maxlength="3" size="3" />
</td>
<td width="50">
<input type="text" name="product_quantity[]" value="1" maxlength="3" size="1" />
</td>
</tr>';
}
What I would like to do, is insert the row into a table, making sure to insert any updated values from the two text boxes. The insert looks like this:
$product_ID = $_POST['product_ID'];
$product_cost = $_POST['product_cost'];
$product_quantity = $_POST['product_quantity'];
for ($i=0; $i<sizeof($product_ID);$i++)
{
$query="INSERT INTO mjj_ordered_products
(`Order_ID`,
`Product_ID`,
`Product_Quantity`,
`Product_Price`)
VALUES ((SELECT MAX(Order_ID) AS Order_ID FROM `mjj_orders`),
'".$product_ID[$i]."',
'".$product_quantity[$i]."',
'".$product_cost[$i]."')";
mysql_query($query) or die (mysql_error());
}
But while this inserts the correct Product_ID, the remaining two values inserted do not correspond to the selected checkbox, but rather by looping through the entire list.
The question: how do I insert the other 2 values associated to the checkbox into the databse?
Assuming the Product_ID is unique, you can pass it as the index in all arrays like
<input type="text" name="product_cost['.$row['Product_ID'].']" value="'.$row['Product_Retail_cost'].'" maxlength="3" size="3" />
And then do something like
foreach($product_ID as $id)
{
$query="INSERT INTO mjj_ordered_products
(`Order_ID`,
`Product_ID`,
`Product_Quantity`,
`Product_Price`)
VALUES ((SELECT MAX(Order_ID) AS Order_ID FROM `mjj_orders`),
'".$product_ID[$id]."',
'".$product_quantity[$id]."',
'".$product_cost[$id]."')";
mysql_query($query) or die (mysql_error());
}