Form loop db insertion + javascript altering - php

I basically need to check if there is an easier way to do this before I rewrite all the code. I have a fairly large form that I have each input named with []'s on the end so I can loop through via php for easy insertion.
<input type="hidden" name="currentdate[]" value="<?php echo date('mdY'); ?>">
<td><input style="width: 50px" type="text" name="jackname[]" /></td>
<td><input style="width: 20px" type="text" name="jackkey[]" /></td>
<td><input style="width: 50px" type="text" name="jackbeg[]" /></td>
<td><input style="width: 50px" type="text" name="jackend[]" /></td>
<td><input style="width: 50px" type="text" name="jackbegveh" /></td>
<td><input style="width: 50px" type="text" name="jackbegmon[]" /></td>
<td><input style="width: 50px" type="text" name="jackendveh" /></td>
<td><input style="width: 50px" type="text" name="jackendmon[]" /></td>
<td><input style="width: 50px" type="text" name="jacktx" disabled /></td>
There are quite a few more fields but you get the idea. I then use
foreach ($_POST['jackname'] as $row=>$name)
{
$jackname = $name;
$date = $_POST['currentdate'][$row];
$jackkey = $_POST['jackkey'][$row];
$jackbeg = $_POST['jackbeg'][$row];
$jackend = $_POST['jackend'][$row];
$jackbegveh = $_POST['jackbegveh'][$row];
$jackbegmon = $_POST['jackbegmon'][$row];
$jackendveh = $_POST['jackendveh'][$row];
$jackendmon = $_POST['jackendmon'][$row];
$jacktx = $_POST['jacktx'][$row];
if ($jacktx == '') {
$jacktx = '0';
}
if (empty($jackkey)) {
echo 'Skipped empty! <br />';
} else {
mysql_query("INSERT INTO `ticket_counts_jackson` VALUES('', '" . $date . "', '" . $jackname . "', '" . $jackkey . "', '" . $jackbeg . "', '" . $jackend . "', '" . $jackbegveh . "', '" . $jackbegmon . "', '" . $jackendveh . "', '" . $jackendmon . "', '" . $jacktx . "')", $mysql_link) or die(mysql_error());
echo 'Added the info the db! <br />';
}
}
I use the above to loop through the form and add it to the database. Now for my main question. I also want to add in some javascript to do a little math. Basically ($jackendveh - $jackbegveh) - ($jackendmon - $jackbegmon) and have that displayed in jacktx. Currently the only way I know of adding in the math calculations is to rename each input to a unique name and then rewrite my insert from 1 insert to 8 inserts.

I would add an ID to each input field like so
<td><input id="jackname" style="width: 50px" type="text" name="jackname[]" /></td>
<td><input id="jackkey" style="width: 20px" type="text" name="jackkey[]" /></td>
<td><input id="jackbeg" style="width: 50px" type="text" name="jackbeg[]" /></td>
<td><input id="jackend" style="width: 50px" type="text" name="jackend[]" /></td>
<td><input id="jackbegveh" style="width: 50px" type="text" name="jackbegveh" /></td>
<td><input id="jackname" style="width: 50px" type="text" name="jackbegmon[]" /></td>
<td><input id="jackname" style="width: 50px" type="text" name="jackendveh" /></td>
<td><input id="jackendmon" style="width: 50px" type="text" name="jackendmon[]" /></td>
<td><input id="jacktx" style="width: 50px" type="text" name="jacktx" disabled /></td>
and then using jQuery you should be able to do it like so
$(document).ready(function(){
$("input").change(function(){
var value = $("#jackendveh").val() - $("#jackbegveh").val() - $("#jackendmon").val() - $("#jackbegmon").val();
$("#jacktx").val(value);
});
});

i think this would be simple
// Function to save sql in array
function save_sql($table,$data,$ref)
{
if(!empty($data)) foreach($data as $k => $v) $str .= "$k = '$v',"; $str = substr($str,0,-1);
$sql = "INSERT INTO $table SET $str";
$run = mysql_query($sql) or die(mysql_error() . "-Ref# $ref");
return $run;
}
// Extract post arrays into variables
extract ($_POST);
foreach ($_POST['jackname'] as $row=>$name)
{
$jackname = $name;
$date = $currentdate[$row];
if ($jacktx[$row] == '') {
$jacktx[$row] = '0';
}
if (empty($jackkey)) {
echo 'Skipped empty! <br />';
} else {
save_sql("ticket_counts_jackson",array('date'=>$currentdata[$row],
'jackname'=>$name,'jackkey'=>$jackkey[$row],
'jackbeg'=>$jackbeg[$row], 'jackend'=>$jackend[$row])
,"An error while process your request");
}
}

I took from #Travis and modified his jquery to work with my situation as follows:
<script type="text/javascript">
$(document).ready(function(){
$("input").change(function(){
var value = $("#jackendveh").val() - $("#jackbegveh").val();
var valuetwo = $("#jackendmon").val() - $("#jackbegmon").val();
var valuethree = value - valuetwo;
$("#jacktx").val(valuethree);
});
});
</script>
So I will just have unique id's on each form section and have seperate jquery functions for each and use my original sql loop.

Related

PHP database UPDATE function only modified the first row?

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
echo "<td>Edit";
echo "<td>Delete";
}
?>
editcrew.php
<table>
<form action="handlecrewedit.php" method="post">
<tr>
<td>Crew Name:</td>
<td><input type="text" name="CrewName" id ="CrewName"required></td>
</tr>
<tr>
<td>Crew Rank:</td>
<td><input type="text" name="CrewRank" id="CrewRank" required></td>
</tr>
<tr>
<td>Start Date:</td>
<td><input type="text" name="StartDate" id="StartDate" required></td>
</tr>
<tr>
<td>End Date:</td>
<td><input type="text" name="EndDate" id="EndDate" required></td>
</tr>
<tr>
<td>Payroll No:</td>
<td><input type="text" name="PayrollNo" id="PayrollNo" required></td>
</tr>
<tr>
<td>Employee No:</td>
<td><input type="text" name="EmployeeNo" id="EmployeeNo" required></td>
</tr>
<tr>
<td>Watching Keeping:</td>
<td><input type="text" name="WatchKeeping" id="WatchKeeping" required></td>
</tr>
<tr>
<td>Active:</td>
<td><input type="text" name="Active" id="Active" required></td>
</tr>
<tr>
<td><input type="submit" value="Submit" ></td>
</tr>
</form>
</table>
handlecrewedit.php
<?php
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$CrewName = $_POST["CrewName"];
$CrewRank = $_POST["CrewRank"];
$StartDate = $_POST["StartDate"];
$EndDate = $_POST["EndDate"];
$PayrollNo = $_POST["PayrollNo"];
$EmployeeNo = $_POST["EmployeeNo"];
$WatchKeeping = $_POST["WatchKeeping"];
$Active = $_POST["Active"];
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT crew_id " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'] . "";
}
mysqli_query($con, $sqlQueryStr);
header('Location: crewlisting.php');
mysqli_close($con);
}
mysqli_close($con);
?>
This is another issue on my modifying entries. I'm not quite sure if I can simply copy and paste my delete code for my edit code, but here is some rough gauge of my table. Unlike the delete function, by selecting the edit function, it directs the user to the form page and it requires them to fill in the updated data.
Errors
Missing closing tag (?>) on here <form action="<?php echo $_SERVER['PHP_SELF']; ?" method="post">
$queryStr = "SELECT * " ."FROM crewlist"; should be $queryStr = "SELECT * FROM crewlist"
No closing tag comes for <br> on here echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
You don't know how many data passing for this $result = mysqli_query($con, $queryStr);, because there is no row count validation
There is no use of check this inside while loop. if (!mysqli_connect_errno($con))
If you are just updating the fields then you've placed the update query in the wrong place
Replace editcrew.php and handlecrewedit.php file code with below code.
editcrew.php
<table>
<form action="handlecrewedit.php" method="post">
<input type="hidden" name="crew_id" value="<?php echo $_GET['id']; ?>" />
<tr>
<td>Crew Name:</td>
<td><input type="text" name="CrewName" id ="CrewName"required></td>
</tr>
<tr>
<td>Crew Rank:</td>
<td><input type="text" name="CrewRank" id="CrewRank" required></td>
</tr>
<tr>
<td>Start Date:</td>
<td><input type="text" name="StartDate" id="StartDate" required></td>
</tr>
<tr>
<td>End Date:</td>
<td><input type="text" name="EndDate" id="EndDate" required></td>
</tr>
<tr>
<td>Payroll No:</td>
<td><input type="text" name="PayrollNo" id="PayrollNo" required></td>
</tr>
<tr>
<td>Employee No:</td>
<td><input type="text" name="EmployeeNo" id="EmployeeNo" required></td>
</tr>
<tr>
<td>Watching Keeping:</td>
<td><input type="text" name="WatchKeeping" id="WatchKeeping" required></td>
</tr>
<tr>
<td>Active:</td>
<td><input type="text" name="Active" id="Active" required></td>
</tr>
<tr>
<td><input type="submit" value="Submit" ></td>
</tr>
</form>
</table>
handlecrewedit.php
<?php
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$CrewName = $_POST["CrewName"];
$CrewRank = $_POST["CrewRank"];
$StartDate = $_POST["StartDate"];
$EndDate = $_POST["EndDate"];
$PayrollNo = $_POST["PayrollNo"];
$EmployeeNo = $_POST["EmployeeNo"];
$WatchKeeping = $_POST["WatchKeeping"];
$Active = $_POST["Active"];
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $crew_id . "";
mysqli_query($con, $sqlQueryStr);
}
header('Location: crewlisting.php');
mysqli_close($con);
?>
I think the suggested answers miss a small point.
It only updates the first row because you exit the while loop with the redirection header.
header('Location: crewlisting.php');
mysqli_close($con);
Place those two lines outside your while loop, and it should update each row.
Your while loop will than be:
while ($row = mysqli_fetch_array($result)) {
// not needed. if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'] . "";
//} closing bracket of if, but the if is not needed.
mysqli_query($con, $sqlQueryStr);
}
//after updating all rows, redirect
header('Location: crewlisting.php');
mysqli_close($con);

PHP conditionals for $message in mail

I know there is a simpler way to do this. What I'm trying to do is group fields by number and use isset to test if $_POST['item#'] value is empty. If that item# is not empty, I want to send corresponding color, quantity, and price. If there is more than one item submitted, I want to send multiples.
Here are my post variables:
$item1 = $_POST['item1'];
$color1 = $_POST['color1'];
$quantity1 = $_POST['quantity1'];
$price1 = $_POST['price1'];
$item2 = $_POST['item2'];
$color2 = $_POST['color2'];
$quantity2 = $_POST['quantity2'];
$price2 = $_POST['price2'];
$item3 = $_POST['item3'];
$color3 = $_POST['color3'];
$quantity3 = $_POST['quantity3'];
$price3 = $_POST['price3'];
$item4 = $_POST['item4'];
$color4 = $_POST['color4'];
$quantity4 = $_POST['quantity4'];
$price4 = $_POST['price4'];
$item5 = $_POST['item5'];
$color5 = $_POST['color5'];
$quantity5 = $_POST['quantity5'];
$price5 = $_POST['price5'];
$item6 = $_POST['item6'];
$color6 = $_POST['color6'];
$quantity6 = $_POST['quantity6'];
$price6 = $_POST['price6'];
$item7 = $_POST['item7'];
$color7 = $_POST['color7'];
$quantity7 = $_POST['quantity7'];
$price7 = $_POST['price7'];
$item8 = $_POST['item8'];
$color8 = $_POST['color8'];
$quantity8 = $_POST['quantity8'];
$price8 = $_POST['price8'];
I'm using isset to test if $_POST[] values are empty:
if( isset($_POST['item1']) )
{
$message = 'Item: '.$item1." \nColor: ".$color1." \nQuantity: ".$quantity1." \nPrice: ".$price1;
}
if( isset($_POST['item2']) )
{
$message = 'Item: '.$item2." \nColor: ".$color2." \nQuantity: ".$quantity2." \nPrice: ".$price2;
}
if( isset($_POST['item3']) )
{
$message = 'Item: '.$item3." \nColor: ".$color3." \nQuantity: ".$quantity3." \nPrice: ".$price3;
}
if( isset($_POST['item4']) )
{
$message = 'Item: '.$item4." \nColor: ".$color4." \nQuantity: ".$quantity4." \nPrice: ".$price4;
}
if( isset($_POST['item5']) )
{
$message = 'Item: '.$item5." \nColor: ".$color5." \nQuantity: ".$quantity5." \nPrice: ".$price5;
}
if( isset($_POST['item6']) )
{
$message = 'Item: '.$item6." \nColor: ".$color6." \nQuantity: ".$quantity6." \nPrice: ".$price6;
}
if( isset($_POST['item7']) )
{
$message = 'Item: '.$item7." \nColor: ".$color6." \nQuantity: ".$quantity7." \nPrice: ".$price7;
}
if( isset($_POST['item7']) )
{
$message = 'Item: '.$item8." \nColor: ".$color7." \nQuantity: ".$quantity8." \nPrice: ".$price8;
}
$items = $_POST['item'];
for ($i = 0; $i < count($items); $i++) {
if ($items[$i])){ //not necessarily the best way to check if it has a value
//do what you want with $items[$i], $color[$i], $quantity[$i], and $price[$]
}
}
For your HTML form inputs use:
<input type="text" name="item[]" />
Here is the requested HTML. I'm just learning so I'm sure there is a more efficient way to name inputs. I'm trying to group item-color-quantity-price, so that when the form is emailed, the relevant data is in a paragraph or table for each item.
<td align="center"><p><span>Item Name</span><br><input id="item1" type="text" name="item1"></p></td>
<td align="center"><p><span>Color</span><br><input id="color1" type="text" name="color1"></td>
<td align="center"><p><span>Quantity</span><br><input id="quantity1" type="text" name="quantity1"></td>
<td align="center"><p><span>Wholesale Price</span><br><input id="price1" type="text" name="price1"></td>
</tr>
<tr>
<td align="center"><p><input id="item2" type="text" name="item2"></p></td>
<td align="center"><p><input id="color2" type="text" name="color2"></p></td>
<td align="center"><p><input id="quantity2" type="text" name="quantity2"></p></td>
<td align="center"><p><input id="price2" type="text" name="price2"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item3" type="text" name="item3"></p></td>
<td align="center"><p><input id="color3" type="text" name="color3"></p></td>
<td align="center"><p><input id="quantity3" type="text" name="quantity3"></p></td>
<td align="center"><p><input id="price3" type="text" name="price3"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item4" type="text" name="item4"></p></td>
<td align="center"><p><input id="color4" type="text" name="color4"></p></td>
<td align="center"><p><input id="quantity4" type="text" name="quantity4"></p></td>
<td align="center"><p><input id="price4" type="text" name="price4"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item5" type="text" name="item5"></p></td>
<td align="center"><p><input id="color5" type="text" name="color5"></p></td>
<td align="center"><p><input id="quantity5" type="text" name="quantity5"></p></td>
<td align="center"><p><input id="price5" type="text" name="price5"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item6" type="text" name="item6"></p></td>
<td align="center"><p><input id="color6" type="text" name="color6"></p></td>
<td align="center"><p><input id="quantity6" type="text" name="quantity6"></p></td>
<td align="center"><p><input id="price6" type="text" name="price6"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item7" type="text" name="item7"></p></td>
<td align="center"><input id="color7" type="text" name="color7"></p></td>
<td align="center"><input id="quantity7" type="text" name="quantity7"></p></td>
<td align="center"><p><input id="price7" type="text" name="price7"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item8" type="text" name="item8"></p></td>
<td align="center"><p><input id="color8" type="text" name="color8"></p></td>
<td align="center"><p><input id="quantity8" type="text" name="quantity8"></p></td>
<td align="center"><p><input id="price8"type="text" name="price8"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item9" type="text" name="item9"></p></td>
<td align="center"><p><input id="color9" type="text" name="color9"></p></td>
<td align="center"><p><input id="quantity9" type="text" name="quantity9"></p></td>
<td align="center"><p><input id="price9" type="text" name="price9"></p></td>
</tr>
I converted all my input names to arrays and I have working loop. However, I need to format the foreach to produce an HTML email with table. It was working perfectly when echo-ing the data but once I formatted it to send as $message, it only sends the last $item.
Here is the foreach loop that works perfectly:
foreach ( $_POST['item'] as $items) {
{
echo '<table>';
echo '<tr>';
echo ' <td>', $items['name'], '</td>';
echo ' <td>', $items['color'], '</td>';
echo ' <td>', $items['size'], '</td>';
echo ' <td>', $items['quantity'], '</td>';
echo ' <td>', $items['price'], '</td>';
echo '</tr>';
}
echo '</table>';
}
HTMl email using the PHP mail function:
foreach ( $_POST['item'] as $items) {
$message = "
<html>
<body>
<table>
<tr>
<th>Name</th>
<th>Color</th>
<th>Size</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>" . $items['name'] . "</td>
<td>" . $items['color'] . "</td>
<td>" . $items['size'] . "</td>
<td>" . $items['quantity'] . "</td>
<td>" . $items['price'] . "</td>
</tr>
</table>
</body>
</html>
";
}

Hidden Default Form Values

I've got a simple form that I would like to be able to add a hidden value that is only used in the event the user doesn't enter a value. The values are for simple text input fields and can use HTML, PHP, JavaScript, JQuery, or any combination thereof. Let me explain further that the value attributes are already set to contain the values in the DB for that form currently. However, in the event there is no current value in the DB for that specific field and the user does not enter a value themselves, I would like a default value to be passed in the POST.
I've done some research and found examples of custom attributes, etc... but these will not work for me. As I'm using an array builder that passes all of the fields in the form as a single array to a new function. Any help would be greatly appreciated!
The code shown below is the creation of the form... As you can see two separate fields are created redundantly for however many rounds exist within the tournament. I've also provided output HTML code of a two round form. In the event the DB has NULL values for the field in question, and if the user doesn't enter a value of his/her own, I would like to pass the value of "false".
$rchkpos = array();
$rchkscore = array();
for ($i=0; $i<=$tournament['numRounds']; $i++)
{
$rchkthis = array("$i" => "round".$i."pos");
$rchkthis2 = array("$i" => "round".$i."score");
$rchkpos = array_merge($rchkpos, $rchkthis);
$rchkscore = array_merge($rchkscore, $rchkthis2);
if ($i > 0)
{
$roundpos = $rchkpos[$i];
$roundscore = $rchkscore[$i];
if (!is_null($stats2[$roundpos])){
$roundposvar = "$stats2[$roundpos]";
}else{
$roundposvar = false;
}
if (!is_null($stats2[$roundscore])){
$roundscorevar = "$stats2[$roundscore]";
}else{
$roundscorevar = false;
}
$team_stats.="
<tr valign='top'>
<td align='center'>" . LANG_MAN_ROUND . " $i " . LANG_MAN_POSITION . "</td>
<td class='alt1' align='center'>
<input type='text' name='round[".$rchkpos[$i]."]' value='$stats2[$roundpos]' size='40' maxlength='5' />
</td>
</tr>
<tr valign='top'>
<td align='center'>" . LANG_MAN_ROUND . " $i " . LANG_MAN_SCORE . "</td>
<td class='alt1' align='center'>
<input type='text' name='round[".$rchkscore[$i]."]' value='$stats2[$roundscore]' size='40' maxlength='5' />
</td>
</tr>";
}
}
Output HTML Example:
<tbody><tr valign="top">
<td align="center">Round 1 Position</td>
<td align="center" class="alt1">
<input type="text" maxlength="5" size="40" value="2" name="round[round1pos]">
</td>
</tr>
<tr valign="top">
<td align="center">Round 1 Score</td>
<td align="center" class="alt1">
<input type="text" maxlength="5" size="40" value="false" name="round[round1score]">
</td>
</tr>
<tr valign="top">
<td align="center">Round 2 Position</td>
<td align="center" class="alt1">
<input type="text" maxlength="5" size="40" value="false" name="round[round2pos]">
</td>
</tr>
<tr valign="top">
<td align="center">Round 2 Score</td>
<td align="center" class="alt1">
<input type="text" maxlength="5" size="40" value="false" name="round[round2score]">
</td>
</tr>
</tbody>
You can possibly do it like this:
HTML
<input type="text" name="name" />
<input type="hidden" name="name_default" value="name_default" />
PHP (after form submit)
if(!isset($_POST['name'])) {
$_POST['name'] = $_POST['name_default'];
}
Or make an aray like this:
$array_check = array('name', 'telephone', 'gender');
foreach($array_check AS $key => $value) {
if(!isset($_POST[$value])) {
$_POST[$value] = $_POST[$value."_default"];
}
}
Keep in mind that users can edit the values of the hidden inputs (with developer tools like Firebug), always check the input!
Other possible approach is to set the default values in a dedicated property in each html input and then replace the value of the field before the post using jQuery:
// before post
$('input').each(function () {
if ($(this).val() == '')
$(this).val($(this).attr('defaultvalue'));
});

inserting data to table from frontend wordpress

I'm trying to insert data to custom table from frontend as well as backend in wordpress.
Below is my code, its working if i insert the data from backend but its giving me Error 404 if i try to insert from frontend.
<?php
/*
Plugin Name: Custom Form
Description: Custom Plugin
Author: Bijay Luitel
*/
// Create the table if not exixts
?>
<style>
p {
display:block;
}
h3 {
height:20px;
padding:10px 5px;
}
</style>
<?php
//Short Codes
add_shortcode('form_bands','form_bands');
function form_bands(){
global $wpdb;
$this_page = $_SERVER['REQUEST_URI'];
$query1 = "SELECT * FROM grade";
$result1 = $wpdb->get_results($query1);
$query2 = "SELECT * FROM branch";
$result2 = $wpdb->get_results($query2);
if($_POST['action']==1 && $_POST['name'] != '' ){
$page_one_table = 'band';
$name =$_POST['name'];
$mailingAddress = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$url = $_POST['url'];
$telephone = $_POST['telephone'];
$gradeId = $_POST['grade'];
$branchId = $_POST['branch'];
$insertMe="INSERT INTO band ('Name', 'MailingAddress', 'City', 'State', 'Zip', 'Email', 'URL', 'Telephone', 'GradeID', 'BranchID') VALUES('$name', '$mailingAddress', '$city', '$state', '$zip', '$email', '$url', '$telephone', '$gradeId', '$branchId')";
$insert_page_one = $wpdb->query($insertMe);
//$insert_page_one = $wpdb->insert($page_one_table, $page_one_inputs);
$form_id = $wpdb->insert_id;
if($insert_page_one)
{
echo '<div id="successMsg" class="updated below-h2"><p>Operation Successful</p></div>';
}
else{
echo '<div id="successMsg" class="updated below-h2"><p>Error ! Recheck and tryagain.</p></div>';
}
}
elseif ($_POST['action']==1 && $_POST['name'] == ''){
echo '<div id="successMsg" class="updated below-h2"><p>Error ! Recheck and tryagain.</p></div>';
}
?>
<h2>Bands</h2>
<div class="postbox">
<form action="" method="post">
<div class="inside">
<table class="form-table">
<tr>
<th>Name :</th>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<th>Address :</th>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<th>City :</th>
<td><input type="text" name="city" /></td>
</tr>
<tr>
<th>State :</th>
<td><input type="text" name="state" /></td>
</tr>
<tr>
<th>Zip :</th>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
<th>Telephone :</th>
<td><input type="text" name="telephone" /></td>
</tr>
<tr>
<th>Email :</th>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<th>Url :</th>
<td><input type="text" name="url" /></td>
</tr>
<tr>
<th>Grade :</th>
<td><select name="grade">
<?php foreach($result1 as $row){
$value = $row->GradeID;
echo '<option value="'.$value.'">';
echo $row->Grade;
echo "</option>";
}?>
</select></td>
</tr>
<tr>
<th>Branch :</th>
<td><select name="branch">
<?php foreach($result2 as $row){
$value = $row->BranchID;
echo '<option value="'.$value.'">';
echo $row->Name;
echo "</option>";
}?>
</select></td>
</tr>
</table>
<p class="submit">
<input type="submit" name="add_form" class="button-primary" value="Submit" />
</p>
<input type="hidden" name="action" value="1" />
</form>
</div>
</div>
<?php
}
function myForm ()
{
add_menu_page('Forms', 'Forms', '','forms', '');
add_submenu_page("forms", "Bands", "Bands", 0, "Bands", "form_bands");
}
add_action('admin_menu','myForm');
How can i solve this problem? Please Help me
I expect the issue you're having relates to your use of a "reserved" post variable name, of 'name'.
The WordPress Codex page for Register_Taxonomy() contains the list of "reserved terms".
Further, your action attribute on your form tag is missing your URL. That's handled OK in current browsers, but may cause unexpected behavior in some older browsers, and isn't guaranteed to work in future.
Better practice is to remove this attribute altogether, if you're not going to use it, because the spec strongly discourages authors from leaving it empty:
The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.
(This info re the action attribute thanks to #mercator with this answer )

Why the mysql update query in php not working?

Please help me regarding the problem specified in the title.
Input form page code:
<?
db_connect();
$query1 = "SELECT *, DATE_FORMAT(eventdate,'%m/%d/%y') AS
eventdate,DATE_FORMAT(throughdate,'%m/%d/%y') AS throughdate FROM events WHERE id = " . mysql_real_escape_string($_REQUEST['id']);
$result1 = mysql_query($query1) or die("Error - query failed " . mysql_error());
if ( mysql_num_rows($result1) == 0 ) {
print "<p>Error - no such event.</p>\n";
return;
}
else {
$qry_event1 = mysql_fetch_array($result1);
}
// default the formaction to the query
if (! isset($_REQUEST['formaction']) ) { $_REQUEST['formaction'] = 'query'; }
?>
<form name="eventform" method="post" action="act_updevent.php">
<input type="hidden" name="submit_check" value="1">
<input type="hidden" name="formaction" value="form">
<!-- if we are editing, $id will exist. Pass it along. -->
<input type="hidden" name="id" value="<?php $qry_event1['id'];?>">
<table>
<tr>
<td align="right" valign="center"><b><? displayformlabel('eventdate','Event Date:')?>
</b></td>
<td><input name="eventdate" value="<? echo $qry_event1['eventdate']; ?>">
<a name="calendar1here" id="calendar1here" href="JavaScript:;"
onClick="cal1.select(document.forms[0].eventdate,'calendar1here','MM/dd/yy'); return
false;">
<img src="resources/calendar.gif" alt="Calendar Icon" width="20" height="20"
border="0"></a>
</td>
</tr>
<tr>
<td align="right" valign="center"><b><? displayformlabel('throughdate','Through:')?>
</b></td>
<td><input name="throughdate" value="<? echo $qry_event1['throughdate']; ?>">
<a name="calendar2here" id="calendar2here" href="JavaScript:;"
onClick="cal2.select(document.forms[0].throughdate,'calendar2here','MM/dd/yy'); return
false;">
<img src="resources/calendar.gif" alt="Calendar Icon" width="20" height="20"
border="0"></a>
<span class="formnotes">Leave blank if only one day event</span>
</td>
</tr>
<tr>
<td align="right"><b><? displayformlabel('title','Event Title:')?></b></td>
<td><input name="title" size="50" maxlength="50" value="<? echo $qry_event1['title'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('website','Event Website:')?></td>
<td><input name="website" size="50" maxlength="100" value="<? echo
$qry_event1['website']; ?>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('email','Event Email:')?></td>
<td><input name="email" size="50" maxlength="100" value="<? echo
$qry_event1['email'];?>"></td>
</tr>
<tr>
<td align="right" valign="top"><? displayformlabel('notes','Notes:')?></td>
<td><textarea name="notes" style="width: 320px; height: 60px;"><? echo
$qry_event1['notes']; ?></textarea></td>
</tr>
<tr>
<td align="right"><? displayformlabel('venue','Venue:')?></td>
<td><input name="venue" size="50" maxlength="50" value="<? echo $qry_event1['venue'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('address','Address:')?></td>
<td><input name="address" size="50" maxlength="50" value="<?echo
$qry_event1['address'];?>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('city','City:')?></td>
<td><input name="city" size="50" maxlength="50" value="<?echo $qry_event1['city'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('state','State:')?></td>
<td><input name="state" size="3" maxlength="2" value="<?echo $qry_event1['state'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('lat','Latitude:')?></td>
<td><input name="lat" size="15" maxlength="15" value="<? echo $qry_event1['lat'];?>">
</td>
</tr>
<tr>
<td align="right"><? displayformlabel('lon','Longitude:')?></td>
<td><input name="lon" size="15" maxlength="15" value="<? echo $qry_event1['lon'];?>">
<span class="formnotes">Look up
coordinates using above address information.</span>
</td>
</tr>
<tr>
<td align="right"><? displayformlabel('accurate','Accurate:')?></td>
<td><input name="accurate" type="checkbox" value="1" <?php if
(isset($qry_event1['accurate'])) { echo 'checked="checked"'; }?>>
<a href="JavaScript:;" class="formnotes" onClick="window.open('<?php
print $vsf->self;?>?action=accuratehelp','helpwin','width=435,height=220');">Whats
this?</a>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
Update page:
<?php
// updates a record in the database
// do validation (shared with update logic)
$id = $_REQUEST['id'];
$eventdate = $_REQUEST['eventdate'];
$throughdate = $_REQUEST['throughdate'];
$title = $_REQUEST['title'];
$website = $_REQUEST['website'];
$email = $_REQUEST['email'];
$notes = $_REQUEST['notes'];
$venue = $_REQUEST['venue'];
$address = $_REQUEST['address'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$lat = $_REQUEST['lat'];
$lon = $_REQUEST['lon'];
$accurate = $_REQUEST['accurate'];
$errorwasthrown="";
$database = 'mapcal';
// database server
$dbsvr = 'localhost';
// username
$dbuser = 'root';
// password
$dbpass = 'usbw';
function db_connect() {
global $dbsvr,$dbuser,$dbpass,$database;
static $dbcon;
if ( ! $dbcon ) {
$dbcon = mysql_connect($dbsvr,$dbuser,$dbpass);
if (! mysql_select_db($database) ) {
die("Failure connecting to database - " . mysql_error());
}
}
}
if (! $eventdate ) {
adderrmsg('eventdate','Event date cannot be blank.');
$errorwasthrown=1;
}
else {
// else date wasn't blank, so validate it
if (! preg_match("/^\d\d\/\d\d\/\d\d$/",$eventdate) ) {
adderrmsg('eventdate',"Event date must be in format mm/dd/yy.");
$errorwasthrown=1;
}
}
if ($throughdate && ! preg_match("/^\d\d\/\d\d\/\d\d$/",$throughdate) ) {
adderrmsg('throughdate',"Through date must be in format mm/dd/yy.");
$errorwasthrown=1;
}
if (! $title ) {
adderrmsg('title','Title cannot be blank.');
$errorwasthrown=1;
}
if ($errorwasthrown) {
include('dsp_editevent.php');
}
else {
db_connect();
// format the date correctly for mysql
$dateparts = split("/",$eventdate);
$eventdate = "$dateparts[2]/$dateparts[0]/$dateparts[1]";
if ($throughdate) {
$dateparts = split("/",$throughdate);
$throughdate = "$dateparts[2]/$dateparts[0]/$dateparts[1]";
$throughdate = "'" . mysql_real_escape_string($throughdate) . "'";
}
else {
$throughdate = 'NULL';
}
// format event website if necessary
if ($website && ! preg_match("/:\/\//",$website) ) {
$website = "http://" . $website;
}
// update record in the database
$query = "UPDATE events SET ";
$query .= "eventdate = '" . mysql_real_escape_string($eventdate) . "', " .
"throughdate = " . $throughdate . ", " .
"title = '" . mysql_real_escape_string($title) . "', " .
"website = '" . mysql_real_escape_string($website) . "', " .
"email = '" . mysql_real_escape_string($email) . "', " .
"notes = '" . mysql_real_escape_string($notes) . "', " .
"venue = '" . mysql_real_escape_string($venue) . "', " .
"address = '" . mysql_real_escape_string($address) . "', " .
"city = '" . mysql_real_escape_string($city) . "', " .
"state = '" . mysql_real_escape_string($state) . "', " .
"lat = '" . mysql_real_escape_string($lat) . "', " .
"lon = '" . mysql_real_escape_string($lon) . "', " .
"accurate = '" . mysql_real_escape_string($accurate) . "' " .
"WHERE id = " . mysql_real_escape_string($id);
if ( ! mysql_query($query) ) {
exit("Query failed! - $query");
}
print "<p style='color: green'>Event <b>$title</b> was updated.</p>\n";
include('dsp_listevents.php');
} // close else ! errorwasthrown
?>
What i can see after printing the query is that it is not getting the value of id but all the fields from the form but why?
Keep the Id value in quotes.
"WHERE id = '" . mysql_real_escape_string($id)."'";

Categories