unable to validate table in controller of laravel 5.4 - php

i have function in controller that repeatedly generates a table via ajax request
i want to validate table every time ajax makes request to this function
how can i validate the start date and law reg no of the table when ajax fetches it with click of button.
my code for function:
public function postlawsdata()
{
$lawdata = Input::get('law_type_id');
$sublawdata = Input::get('law_sub_type_id');
$start_date = Input::get('start_date');
$res_div = '';
$sub_law_count = count($sublawdata);
$validate_laws = '';
if (count($sublawdata) > 0) {
for ($i = 0; $i < count($lawdata); $i++) {
$law_details = DB::table('tbl_law_master')->where('id', $lawdata[$i])->select('tbl_law_master.id as law_id', 'tbl_law_master.lm_id', 'tbl_law_master.law_name')->first();
$sublaw_details = DB::table('tbl_law_sub_master')
->where('tbl_law_sub_master.lm_id', $lawdata[$i])
->whereNull('tbl_law_sub_master.deleted_at')
->select('tbl_law_sub_master.id as sublaw_id', 'tbl_law_sub_master.sub_law_name', 'tbl_law_sub_master.lms_id')->get();
if (count($sublaw_details) > 0) {
$res_div .= '<table width="100%" border="0" class="table table-striped table-bordered table-hover">';
$res_div .= '<tr>
<td colspan="2" rowspan="2">
<strong>' . $law_details->lm_id . ' (' . $law_details->law_name . ')</strong>
</td>
<td >
<span class="required" aria-required="true">* </span><input type="text" value="' . $start_date . '" placeholder="DD-MM-YYYY (Start Date)" name="law_start_date[]" id="law_start_date" att_law_id="' . $lawdata[$i] . '" class="date-picker required locationformstyle locationparentsd dynamiclocationparentsd' . $lawdata[$i] . '">
</td></tr><tr><td>
<span class="required" aria-required="true">* </span><input type="text" placeholder="Law Registration No." name="law_reg_no" id="law_reg_no" class="locationformstyle required">
</td>
</tr>';
foreach ($sublaw_details as $sublawdetails) {
if (in_array($sublawdetails->sublaw_id, $sublawdata)) {
$res_div .= '<tr>
<td width="220">Start Date: <input type="text" name="sub_law_start_date[]" placeholder="DD-MM-YYYY" onfocus="this.blur()" class="locationformstyle date-picker dynamiclocationparentsd' . $lawdata[$i] . '" att_law_id="' . $lawdata[$i] . '"> </td>
<td width="220">End Date: <input type="text" name="sub_law_end_date[]" placeholder="DD-MM-YYYY" onfocus="this.blur()" class="locationformstyle date-picker"></td>
<td align="left"><strong>' . $sublawdetails->lms_id . ' (' . $sublawdetails->sub_law_name . ')</strong>
<input type="hidden" class="locationformstyle" name="company_sub_laws[]" value="' . $sublawdetails->sublaw_id . '">
</td>
</tr>
';
}
}
$res_div .= '</table>';
}
}
} else {
$validate_laws = 'Please Select Atleast One Law';
}
$data = array(
'law_info' => $res_div,
'validate_laws' => $validate_laws,
'sub_law_count' => $sub_law_count
);
return json_encode($data);
}

create a new validator like so;
public function postlawsdata()
{

$validator = Validator::make($request->all(), [
'start_date' => 'required',
//add other fields here with custom validation rules
]);

if ($validator->passes()) {
$lawdata = Input::get('law_type_id');
$sublawdata = Input::get('law_sub_type_id');
$start_date = Input::get('start_date');
$res_div = '';
$sub_law_count = count($sublawdata);
$validate_laws = '';
if (count($sublawdata) > 0) {
for ($i = 0; $i < count($lawdata); $i++) {
$law_details = DB::table('tbl_law_master')->where('id', $lawdata[$i])->select('tbl_law_master.id as law_id', 'tbl_law_master.lm_id', 'tbl_law_master.law_name')->first();
$sublaw_details = DB::table('tbl_law_sub_master')
->where('tbl_law_sub_master.lm_id', $lawdata[$i])
->whereNull('tbl_law_sub_master.deleted_at')
->select('tbl_law_sub_master.id as sublaw_id', 'tbl_law_sub_master.sub_law_name', 'tbl_law_sub_master.lms_id')->get();
if (count($sublaw_details) > 0) {
$res_div .= '<table width="100%" border="0" class="table table-striped table-bordered table-hover">';
$res_div .= '<tr>
<td colspan="2" rowspan="2">
<strong>' . $law_details->lm_id . ' (' . $law_details->law_name . ')</strong>
</td>
<td >
<span class="required" aria-required="true">* </span><input type="text" value="' . $start_date . '" placeholder="DD-MM-YYYY (Start Date)" name="law_start_date[]" id="law_start_date" att_law_id="' . $lawdata[$i] . '" class="date-picker required locationformstyle locationparentsd dynamiclocationparentsd' . $lawdata[$i] . '">
</td></tr><tr><td>
<span class="required" aria-required="true">* </span><input type="text" placeholder="Law Registration No." name="law_reg_no" id="law_reg_no" class="locationformstyle required">
</td>
</tr>';
foreach ($sublaw_details as $sublawdetails) {
if (in_array($sublawdetails->sublaw_id, $sublawdata)) {
$res_div .= '<tr>
<td width="220">Start Date: <input type="text" name="sub_law_start_date[]" placeholder="DD-MM-YYYY" onfocus="this.blur()" class="locationformstyle date-picker dynamiclocationparentsd' . $lawdata[$i] . '" att_law_id="' . $lawdata[$i] . '"> </td>
<td width="220">End Date: <input type="text" name="sub_law_end_date[]" placeholder="DD-MM-YYYY" onfocus="this.blur()" class="locationformstyle date-picker"></td>
<td align="left"><strong>' . $sublawdetails->lms_id . ' (' . $sublawdetails->sub_law_name . ')</strong>
<input type="hidden" class="locationformstyle" name="company_sub_laws[]" value="' . $sublawdetails->sublaw_id . '">
</td>
</tr>
';
}
}
$res_div .= '</table>';
}
}
} else {
$validate_laws = 'Please Select Atleast One Law';
}
$data = array(
'law_info' => $res_div,
'validate_laws' => $validate_laws,
'sub_law_count' => $sub_law_count
);
return json_encode($data);

}

return response()->json(['error'=>$validator->errors()->all()]);
}
add use Validator; at the top.

Related

jquery datepicker is not working text box is present in controller PHP

I have a function in controller
public function getCourseDetails() {
$this->view->js[] = URL . 'views/manageTeam/js/course.js';
$this->view->getcourses = $this->model->GetassignCourses($_REQUEST['courseid']);
if (empty($this->view->getcourses)) {
echo 'Nothing to display';
exit;
} else {
$output = '';
$output .= '
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th style=" width: 60%;"> Course Name </th>
<th style=""> Start Date </th>
<th style=""> End Date </th>
<th><input type="checkbox" id="selecctall"/> </th>
</tr> </thead>
';
$i = 1;
foreach ($this->view->getcourses as $courses):
if ($courses['adm'] == 0) {
$checked = '';
$clas = "";
} else {
$checked = 'checked="checked"';
// $clas = "disabled";
}
// $checked = isset($courses['adm'])!=0 ? 'checked="checked"' : '';
$output .= '
<tr>
<td>' . $i . '</td>
<td>' . $courses['c_name'] . '</td>
<td><input type="text" id="txtFrom" /></td>
<td><input type="text" id="txtTo" /></td>
<td><input name="checkbox[]" id="d_checkbox'.$i.'" class="checkbox1" ' . $checked . ' type="checkbox" value="' . $courses['c_id'] . '"></td>
</tr>
';
$i++;
endforeach;
$output .= "</table></div>";
$output .= '<input type="hidden" name="c_id" value="' . $_REQUEST['courseid'] . '" id="c_id" /> ';
echo $output;
}
}
which is call from ajax.here two date button
<td><input type="text" id="txtFrom" /></td>
<td><input type="text" id="txtTo" /></td>
view page:
`<form name="registration1_form" id="registration1_form" method="POST" action="<?php echo MANAGE_TEAM . 'addcoursetousers' ?>"` enctype="multipart/form-data">
<div class="modal-body" id="coursedetails">
Table values Apprear here
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" name="submitabouc" id="i_submitdisc" class="btn btn-success">Submit</button>
script.js
$(function () {
$("#txtFrom").datepicker({
numberOfMonths: 2,
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() + 1);
$("#txtTo").datepicker("option", "minDate", dt);
}
});
$("#txtTo").datepicker({
numberOfMonths: 2,
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() - 1);
$("#txtFrom").datepicker("option", "maxDate", dt);
}
});
});
but date function is not working.jquery datepicker is not working text box is present in controller PHP.i dont know why this happens..ANy help would be appreciated..

Loop and auto submit HTML form within PHP

I am trying to send a couple of variables via HTML form to another PHP page,
I am no expert in PHP but know enough to get me by most days,
and have had this working with no issues in other situations,
But alas PHP is just not my thing so I am here to ask the Gurus of the coding world for a pearl of wisdom,
Ok so let me break it down for you,
I have a PHP IPN (PayPal) page that is executed when a customer makes a purchase, the original code just checks for successful sale and then sends out some email to myself and the user accordingly,
I also have a licensing script that auto-generates a license,
I use a HTML form within the page so that when the sale is marked as successful a license is generated and sent to the user at the same time the emails are sent,
All pretty basic stuff, and have had this working in 3 other scripts with no problems, but for some reason i just cant get my head around it this time, and cant seem to get this to work,
I contacted the author of my store script to make sure i was using the correct variables in the form, he said that the variables needed are :
$usr->username
$usr->email
$crow->title
Here is the IPN page :
<?php
define("_VALID_PHP", true);
define("_PIPN", true);
ini_set('log_errors', true);
ini_set('error_log', dirname(__file__) . '/ipn_errors.log');
if (isset($_POST['payment_status'])) {
require_once ("../../init.php");
include (BASEPATH . 'lib/class_pp.php');
$demo = getValue("demo", Content::gTable, "name = 'paypal'");
$listener = new IpnListener();
$listener->use_live = $demo;
$listener->use_ssl = false;
$listener->use_curl = true;
try {
$listener->requirePostMethod();
$ppver = $listener->processIpn();
}
catch (exception $e) {
error_log($e->getMessage());
exit(0);
}
$payment_status = $_POST['payment_status'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$payer_status = $_POST['payer_status'];
$mc_currency = $_POST['mc_currency'];
$mc_fee = isset($_POST['mc_fee']) ? floatval($_POST['mc_fee']) : 0.00;
list($user_id, $sesid) = explode('_', $_POST['custom']);
$mc_gross = $_POST['mc_gross'];
$txn_id = $_POST['txn_id'];
$getxn_id = $core->verifyTxnId($txn_id);
$cartrow = $content->getCartContent($sesid);
$totalrow = Content::getCart($sesid);
$v1 = compareFloatNumbers($mc_gross, $totalrow->totalprice, "=");
$items = array();
$pp_email = getValue("extra", Content::gTable, "name = 'paypal'");
if ($ppver) {
if ($_POST['payment_status'] == 'Completed') {
if ($receiver_email == $pp_email && $v1 == true && $getxn_id == true) {
if ($cartrow) {
foreach ($cartrow as $crow) {
$data = array(
'txn_id' => sanitize($txn_id),
'pid' => $crow->pid,
'uid' => intval($user_id),
'downloads' => 0,
'file_date' => time(),
'ip' => sanitize($_SERVER['REMOTE_ADDR']),
'created' => "NOW()",
'payer_email' => sanitize($payer_email),
'payer_status' => sanitize($payer_status),
'item_qty' => $crow->total,
'price' => $crow->total * $crow->price,
'coupon' => $totalrow->coupon,
'tax' => $totalrow->totaltax,
'mc_fee' => $mc_fee,
'currency' => sanitize($mc_currency),
'pp' => "PayPal",
'status' => 1,
'active' => 1);
$items[$crow->price] = $crow->title;
$db->insert(Products::tTable, $data);
}
unset($crow);
$xdata = array(
'invid' => date('Ymd').$db->insertid(),
'user_id' => intval($user_id),
'items' => serialize($items),
'coupon' => $totalrow->coupon,
'originalprice' => $totalrow->originalprice,
'tax' => $totalrow->tax,
'totaltax' => $totalrow->totaltax,
'total' => $totalrow->total,
'totalprice' => $totalrow->totalprice,
'currency' => sanitize($_POST['currency_code']),
'created' => "NOW()",
);
$db->insert(Content::inTable, $xdata); }
/* == Notify Administrator == */
require_once (BASEPATH . "lib/class_mailer.php");
$row2 = Core::getRowById(Content::eTable, 5);
$usr = Core::getRowById(Users::uTable, $user_id);
$body = str_replace(array(
'[USERNAME]',
'[STATUS]',
'[PRODUCT]',
'[TOTAL]',
'[PP]',
'[IP]'), array(
$usr->username,
"Completed",
$crow->title,
$totalrow->totalprice,
"PayPal",
$_SERVER['REMOTE_ADDR']), $row2->body);
$newbody = cleanOut($body);
$mailer = Mailer::sendMail();
$message = Swift_Message::newInstance()
->setSubject($row2->subject)
->setTo(array($core->site_email => $core->site_name))
->setFrom(array($core->site_email => $core->site_name))
->setBody($newbody, 'text/html');
$mailer->send($message);
/* == Notify User == */
$row3 = Core::getRowById(Content::eTable, 8);
$val = '
<table border="0" cellpadding="4" cellspacing="2">';
$val .= '
<thead>
<tr>
<td width="20"><strong>#</strong></td>
<td class="header">' . Lang::$word->PRD_NAME . '</td>
<td class="header">' . Lang::$word->PRD_PRICE . '</td>
<td class="header">' . Lang::$word->TXN_QTY . '</td>
<td class="header">' . Lang::$word->CKO_TPRICE . '</td>
</tr>
</thead>
<tbody>
';
$i = 0;
foreach ($cartrow as $ccrow) {
$i++;
$val .= '
<tr>
<td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $i . '.</td>
<td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . sanitize($ccrow->title, 30, false) .
'</td>
<td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $core->formatMoney($ccrow->price) .
'</td>
<td align="center" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $ccrow->total . '</td>
<td align="right" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $core->formatMoney($ccrow-
>total * $ccrow->price) . '</td>
</tr>
';
}
unset($ccrow);
$val .= '
<tr>
<td colspan="4" align="right" valign="top" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-
style:dashed"><strong>';
$val .= Lang::$word->CKO_SUBT . ':<br />';
$val .= Lang::$word->CKO_DISC . ':<br />';
$val .= Lang::$word->VAT . ':<br />
</strong></td>
<td align="right" valign="top" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed"><strong>';
$val .= $core->formatMoney($totalrow->originalprice) . '<br />';
$val .= '- ' . $core->formatMoney($totalrow->coupon) . '<br />';
$val .= '+ ' . $core->formatMoney($totalrow->total * $totalrow->tax) . '<br />
</strong>';
$val .= ' </td>
</tr>
<tr>
<td colspan="4" align="right" valign="top"><strong style="color:#F00">' . Lang::$word->CKO_GTOTAL . ':</strong></td>
<td align="right" valign="top"><strong style="color:#F00">' . $core->formatMoney($totalrow->tax * $totalrow->total + $totalrow->total)
. '</strong></td>
</tr>
</tbody>
</table>';
$body3 = str_replace(array(
'[USERNAME]',
'[ITEMS]',
'[SITE_NAME]',
'[URL]'), array(
$usr->username,
$val,
$core->site_name,
SITEURL), $row3->body);
$newbody2 = cleanOut($body3);
$mailer2 = Mailer::sendMail();
$message2 = Swift_Message::newInstance()
->setSubject($row3->subject)
->setTo(array($usr->email => $usr->username))
->setFrom(array($core->site_email => $core->site_name))
->setBody($newbody2, 'text/html');
$mailer2->send($message2);
$db->delete(Content::crTable, "user_id='" . $sesid . "'");
$db->delete(Content::exTable, "user_id='" . $sesid . "'");
$db->delete(Products::rTable, "user_id='" . $sesid . "'");
?>
<!doctype html>
<html>
<head></head>
<body onload="document.createElement('form').submit.call(document.getElementById('Form'))">
<form id='Form' name='form' action='http://www.****************.php' method='post'>
<input type='hidden' name='name' value='<?php echo $_POST['usr->username'];?>'>
<input type='hidden' name='email' value='<?php echo $_POST['usr->email'];?>'>
<input type='hidden' name='original_url' value='http://www.****************ipn.php'>
<input type='hidden' name='projname' value='<?php echo $_POST['crow->title'];?>'>
<input type=hidden name="submit" id="submit" value="Continue"/>
</form>
</body>
</html>
<?php
$sale_amount = '$totalrow->totalprice';
$product = '$crow->title';
include('/home/**********************************.php');
}
} else {
/* == Failed Transaction= = */
require_once (BASEPATH . "lib/class_mailer.php");
$row = Core::getRowById(Content::eTable, 6);
$usr = Core::getRowById(Users::uTable, $user_id);
$body = str_replace(array('[USERNAME]','[STATUS]','[TOTAL]','[PP]','[IP]'), array(
$usr->username,"Failed",$core->formatMoney($gross),"PayPal",$_SERVER['REMOTE_ADDR']), $row->body);
$newbody = cleanOut($body);
$mailer = Mailer::sendMail();
$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($core->site_email => $core->site_name))
->setFrom(array($core->site_email => $core->site_name))
->setBody($newbody, 'text/html');
$mailer->send($message);
}
}
}
?>
and here is the FORM code im using :
<!doctype html>
<html>
<head></head>
<body onload="document.createElement('form').submit.call(document.getElementById('Form'))">
<form id='Form' name='form' action='http://www.****************.php' method='post'>
<input type='hidden' name='name' value='<?php echo $_POST['usr->username'];?>'>
<input type='hidden' name='email' value='<?php echo $_POST['usr->email'];?>'>
<input type='hidden' name='original_url' value='http://www.****************ipn.php'>
<input type='hidden' name='projname' value='<?php echo $_POST['crow->title'];?>'>
<input type=hidden name="submit" id="submit" value="Continue"/>
</form>
</body>
</html>
I am also aware that I may need to use a foreach() loop but ill cross that bridge when i get there, I really need to figure this out first.
So there we are, i think i have left enough info, details and code,
If i have missed anything out that might help just let me know
When you use
<input type="hidden" name="name" value="<?php echo $_POST['usr->username'];?>">
you are calling a POST variable 'usr->username' which does not exist, as far as I see in your script. Instead, use this:
<input type="hidden" name="name" value="<?php echo $usr->username;?>">
That would set the value of the input to the property 'username' of the 'usr' object you define on the line:
$usr = Core::getRowById(Users::uTable, $user_id);
The same applies to the other fields.
Hope it helps :)
Regards

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>
";
}

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)."'";

Form loop db insertion + javascript altering

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.

Categories