Get a string out of an array - php

Good day! I've created a file send.php to send an info about orders to my gmail. Almost everything is ok, but I can't send names of products from cart. I have to send just a string(title) from the DB on mail. How can I get a title from $g which is a row?
<?php
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';
require 'phpmailer/Exception.php';
$g = $_SESSION['cart_list'];
$name = $_POST['name'];
$tel = $_POST['tel'];
$c = $single["title"];
$title = "";
$body = "
<h2></h2>
<b></b> $name<br>
<b></b> $tel<br><br>
<b></b>$c<br>
";
$mail = new PHPMailer\PHPMailer\PHPMailer();
try {
$mail->isSMTP();
$mail->CharSet = "UTF-8";
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Debugoutput = function($str, $level) {$GLOBALS['status'][] = $str;};
$mail->Host = 'smtp.gmail.com';
$mail->Username = '';
$mail->Password = '';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('');
$mail->addAddress('');
$mail->isHTML(true);
$mail->Subject = $title;
$mail->Body = $body;
if ($mail->send()) {$result = "success";}
else {$result = "error";}
}
catch (Exception $e) {
$result = "error";
$status = "{$mail->ErrorInfo}";
}
echo json_encode(["result" => $result, "resultfile" => $rfile, "status" => $status]);
order.php(With products, sum, inlines, submit)
<?php
require_once "db.php";
require_once "header.php";
?> <br>
<div class="text-center">
</div><br>
<main>
<div class="container">
<section class='text-center mb-4'>
<div class='row'>
<?php $s = 0; ?>
<?php foreach( $_SESSION['cart_list'] as $single ) : ?>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-4 col-xl-4 col-md-offset-1
mb-5">
<div class='card'>
<div class='view overlay'>
<div class='qwe'>
<img class='card-img-top' src='/img/products/<?php echo $single['img'];?
>.jpg'>
</div>
<div class='mask rgba-white-slight'></div>
</div>
<div class='card-body text-center'>
<div class="grey-text">
<div class='title'><h5><?php echo $single['title'];?></h5></div>
</div>
<br>
<h5>
<strong><?php echo $single['brand'];?>
<span class='badge red mr-1'>
<?php echo $single['category'];?>
</span>
</strong>
</h5>
<h4 class='font-weight-bold blue-text'>
<strong><?php echo $single['price'];?>$</strong>
</h4>
</div>
</div>
</div>
<?php $s += $single['price']; ?>
<?php $g = $_SESSION['cart_list'] ?>
<?php endforeach; ?>
</div>
</section>
<hr><section class='text-center mb-4 font-weight-bold display-4'>
<label class="count" id="summ"><?php echo $s; ?>$</label>
</section>
<p>
<a href="cart.php"><button type="button" class="btn btn-primary">
</button></a> <br> <br>
</p>
<form action="send.php" method="post">
<div class="text-center">
<input type="name" name="name" placeholder="Ваше " aria-label="" required>
<input type="tel" name="tel" placeholder="" aria-label="" required>
<input class="btn btn-primary" type="submit" value="" required>
</div>
</form>
</div>
</main>
</div>
<?php require_once "footer.php"; ?>

Getting the names is as simple as the following:
$titles = implode(', ', array_column($g, 'title'));
Assuming a dummy cart like this (I included a cyrillic value since you mentioned that in your follow up question):
$g = [
['title' => 'This is a title', 'something' => 'else'],
['title' => 'Some things', 'something' => 'else'],
['title' => 'Word', 'something' => 'else'],
['title' => 'Владимир', 'something' => 'else'],
];
the result will be a string:
This is a title, Some things, Word, Владимир
How it works
First we extract just the titles; array_column($g, 'title') will produce an array like this:
array(
0 => 'This is a title',
1 => 'Some things',
2 => 'Word',
3 => 'Владимир',
)
After that, all that is left is to implode all those array elements into a single string. I used a comma as the glue delimiter, but you could use whatever you need.

Related

How do i post a $_GET variable value using a REQUEST METHOD

I am trying to post a $_GET value so it cant insert the variable value into the database using $_SERVER["REQUEST_METHOD"].
<?php require_once("../includes/initialize.php"); ?>
<?php include("../includes/form_validation_card.php"); ?>
<?php $username = $_SESSION['username']; ?>
<?php
if(!isset($_GET['total']) && !isset($_GET['order_id'])){
redirect_to('order_summary.php');
}
$total = $_GET['total'];
$order = $_GET['order_id'];
?>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
?>
<?php include_layout_template('header2.php'); ?>
<div class="container">
<div class="row">
<br/><br/><?php echo output_message($message); ?>
</div>
<div class="row ">
<div class="jumbo jumbotron-fluid mx-auto d-block" style="height: 500px; width: 440px; background-color:#DCDCDC; border-radius: 5px;" >
<div class="text-center" style="margin: 3px;"><img src="logo/eden_petshop_logo.png" width="32" height="32"/><?php echo $found_user['first_name']; ?> <?php echo $found_user['last_name']; ?></div>
<p class="text-center">order id: #<?php echo $order; ?></p>
<h4 class="display-4 lead text-center">N<?php echo $total; ?></h4>
<div class="col-sm-6 col-sm-offset-3 mx-auto d-block">
<?php echo output_message($message); ?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post" class="form-horizontal">
<div class="form-group">
<div class="col">
<input type="text" name="card_number" onchange="trim(this)" placeholder="Card Number" class="form-control" id="card_number"/>
<span style="color: #EA4335"><?= $card_number_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<input type="text" name="mm_yy" class="form-control" onchange="trim(this)" placeholder="MM/YY">
<span style="color: #EA4335"><?= $mm_yy_error; ?></span>
</div>
<div class="col">
<input type="password" name="cvv" class="form-control" onchange="trim(this)" placeholder="CVV">
<span style="color: #EA4335"><?= $cvv_error; ?></span>
</div>
</div>
</div>
<div class="col-sm-12 col-sm-push-3">
<button type="submit" name="submit" value="Pay" class="btn bg-info btn-sm btn-block" onClick="return confirm('Are you sure your details are correct?');">Pay</button>
</div>
</form>
</div>
</div>
</div>
<?php include_layout_template('footer2.php'); ?>
This is the input display page but i am trying to the $total and $order $_GET variables insert into the database... Please note that every other part of the code assignment is working fine.
<?php
//define variables and set them to empty values
$total_error = $order_error = $card_number_error = $mm_yy_error = $cvv_error = "";
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
//form is submitted with post method
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["card_number"])){
$card_number_error = "<div class=''>Card number is required</div>";
}else{
$card_number = test_input($_POST["card_number"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{16,}$/",$card_number)){
$card_number_error = "<div>Only 16 numbers allowed</div>";
}
}
if(empty($_POST["mm_yy"])){
$mm_yy_error = "<div class=''>Card expiry is required</div>";
}else{
$mm_yy = test_input($_POST["mm_yy"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$mm_yy)){
$mm_yy_error = "<div class=''>Only numbers allowed</div>";
}
}
if(empty($_POST["cvv"])){
$cvv_error = "<div class=''>Card verification is required</div>";
}else {
$cvv = test_input($_POST["cvv"]);
//check if username is atleast 7 characters
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$cvv)){
$cvv_error = "<div class=''>Card verification must not be more than 3 numbers</div>";
}
}
if($card_number_error == "" && $mm_yy_error == "" && $cvv_error == ""){
$token = 'vfjhvbkebecbjDRCWVJEcbkrvlnke24tir7c_zdvbejw968350124';
$token = str_shuffle($token);
$token = substr($token, 0, 15);
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
$email = $found_user['email_address'];
$pay = new Payment();
$pay->username = $username;
$pay->order_id = $order;
$pay->total = $total;
$pay->card_number = $card_number;
$pay->expiry = $mm_yy;
$pay->cvv = $cvv;
$pay->transaction_id = $token;
$pay->status = 0;
$pay->created_at = $timestamp;
if($pay->save()){
//$mail = new Mail();
//$mail->email_address = $email_address;
//$mail->send_transaction_confirmation();
unset($_SESSION['shopping_cart']);
$session->message('<div class="btn bg-success">Congratulations!!! Your order has been processed.</div>');
redirect_to('photos.php');
}
}
if(empty($_POST["message"])){
$message = "";
} else{
$message = test_input($_POST["message"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
?>
Please note that my $order and total are not getting inserted into my database... Any assistance on my preg_match would be appreciated... Thanks in advance.
You need to use $_POST in your broken code instead of $_GET. Notice your working code used $_POST instead, which is why it works.

How to validate checkbox in a for loop

I am creating a seat reservation system. In my system, the code check number of seats a bus contains then pass it inside a for loop. When a user pick 2 passengers, it means two seats will be booked. How can I validate the checkbox in the for loop depending on the number of passenger(s) selected.
Using the GUI for more explanation.
on the main page, 2 there indicates number of passenger(s) selected.
When you come to the second page where the values are passed to, you can see 2 Adults as the selected number of passengers. When you click on Submit Button it does not validate the checkbox based on the number of passenger(s) selected. And if I should put required in the checkbox it validates the whole checkbox since it is in a loop
$_SESSION['seat_no'] is the number of seat(s) a bus contains. Let assume a user that want to book a seat selected two passengers which means two seats is booked, how can I validate the checkbox based on the number of seat(s) selected?
Here is my code:
<?php
for ($i = 1; $i <= $_SESSION['seat_no']; $i++) {
if(in_array($i,$mseat)){
echo "<div class='checkbox_wrapper_pick'>
<label>".$i."</label>
</div>";
}else{
echo "<div class='checkbox_wrapper'>
<input type='checkbox' value=".$i." name='seat_book[]' />
<label>".$i."</label>
</div>";
}
}
?>
The full source code:
<?php include("header.php"); error_reporting(0); ?>
<?php
if(isset($_POST['submit'])){
$from = $_POST['from'];
$to = $_POST['to'];
$date = $_POST['d_date'];
$nop = $_POST['nop'];
$_SESSION['from'] = $from;
$_SESSION['to'] = $to;
$_SESSION['date'] = $date;
$_SESSION['nop'] = $nop;
$get = mysqli_query($mysqli,"SELECT * FROM routes WHERE present_loc = '$from' and destination = '$to' ");
while($roys = mysqli_fetch_array($get)){
//get bus details
$bno = $roys['bus_no'];
$ploc = $roys['present_loc'];
$des = $roys['destination'];
$time = $roys['dept_time'];
$_SESSION['time'] = $time;
$amt = $roys['amount'];
$_SESSION['amt'] = $amt;
$b = str_replace( ',', '',$_SESSION['amt'] );
if( is_numeric($b) ) {
$a = $b;
}
$bus = mysqli_query($mysqli,"select * from bus where bus_no = '$bno'");
while($bu = mysqli_fetch_array($bus)){
$_SESSION['model'] = $bu['model'];
$_SESSION['seat_no'] = $bu['seat_no'];
$_SESSION['ac'] = $bu['bus_type'];
$_SESSION['excess_luggage'] = $bu['excess_luggage'];
$_SESSION['more_legs'] = $bu['more_legs'];
$_SESSION['id'] = $bu['id'];
}
$coun = mysqli_query($mysqli, "select count(booking_id) as seat, seats from booking where bus_no = '$bno' and seats !='' GROUP by booking_id" );
$mseat = array();
while($e = mysqli_fetch_array($coun)){
$bseat = $e['seat'];
$mseat[] = $e['seats'];
}
//$seatss = array();
$seat_string = implode(",",$mseat);
//get seats
$couns = mysqli_query($mysqli, "select sum(counter) as seat from booking where bus_no = '$bno' and seats !='' GROUP by bus_no" );
$rseats = mysqli_fetch_array($couns);
$lseat = $rseats['seat'];
if($_SESSION['seat_no'] == $lseat){
$tell = " No more seat(s) available.";
}else{
$tell = $_SESSION['seat_no'] - $lseat. " Seat(s) remaining.";
}
}
}
?>
<!--Main layout-->
<main class="mt-5">
<!--Main container-->
<form action="details" method="POST">
<!--Grid row-->
<div class="row">
<div class="col-lg-12 title-header mb-3 mx-auto z-depth-1">
<div class="row">
<div class="col-lg-8">
<?php echo '<h2> '.$_SESSION['from']. ' to '. $_SESSION['to']. '</h2>'; ?><br/>
<b><?php echo $_SESSION['date']; ?> :: <?php if($_SESSION['nop'] < '2') { echo $_SESSION['nop'] . ' Adult'; }
elseif($_SESSION['nop'] > 1) { echo $_SESSION['nop'] . ' Adults'; }
?></b>
</div>
</div>
</div>
<div class="col-lg-12 mbody"> <label style="margin-left: 4%; font-weight:bolder; font-size:20px; color:#000;">Details </label> </div>
<div class="col-lg-12 mbody bg-white ">
<table class="table table_view" style = "width: 100%; margin-left: 4%; margin-right:4%;">
<tbody>
<tr>
<td><b><?php echo $_SESSION['model']; ?></b><br/><?php echo $_SESSION['from']. ' to '. $_SESSION['to']; ?>
<br/><?php if($_SESSION['ac'] == 'AC') { echo '<span class="alert-info ac">'. $_SESSION['ac'] .'</span>'; }
else{ echo '<span class="alert-warning">No AC</pan>'; } ?>
<?php if($_SESSION['more_legs'] == 'Yes') { echo '<span class="alert-info ac">More Leg Room</span>'; }
else{ echo '<span class="alert-warning no">More Leg Not Available</pan>'; } ?>
</td>
<td><b>Departing Time</b><br/><i class="fa fa-clock-o" aria-hidden="true"></i> <?php echo $_SESSION['time']; ?></td>
<td> <img id = "seatimg" src="../images/seatsLayout/av.gif" class="img-responsive"> <?php echo $tell; ?></td>
<td>Adult <b>₦<?php echo $_SESSION['amt']; ?></b></td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-12">
<div class="col-lg-12 mbody"> <label style="margin-left: 3%; font-weight:bolder; font-size:20px; color:#000;"><img id = "seatimg" src="../images/seatsLayout/av.gif" class="img-responsive"> Select Seat</label> </div>
<div class="row detail">
<!--Grid column-->
<div class="col-lg-7 animation slideUp" >
<div class="well" id="bus_seats_layout" >
<table class="table table-bordered" cellspacing = "1" id="seatstable">
<tr>
<td><img id = "driverimg" src="../images/seatsLayout/steering.png" class="img-responsive" width="25" height="25"></td>
<td colspan="2" rowspan="3">
<?php
for ($i = 1; $i <= $_SESSION['seat_no']; $i++) {
if(in_array($i,$mseat)){
echo "
<div class='checkbox_wrapper_pick'>
<label>".$i."</label>
</div>
";
}else{
echo "
<div class='checkbox_wrapper'>
<input type='checkbox' value=".$i." name='seat_book[]' />
<label>".$i."</label>
</div>
";
}
}
?>
</td>
</tr>
</table>
</div>
</div>
<div class="col-lg-5">
<ul class="bt">
<li><img src="../images/seatsLayout/seat_available.png" class="img-responsive"> Available</li>
<li><img src="../images/seatsLayout/picked.png" class="img-responsive"> Selected</li>
<li><img src="../images/seatsLayout/seat_booked.png" class="img-responsive"> Booked</li>
</ul>
</div>
</div>
<div class="col-lg-12">
<input type="hidden" name="bus_no" value="<?php echo $bno; ?>">
<input type="hidden" name="to" value="<?php echo $to; ?>">
<input type="hidden" name="from" value="<?php echo $from; ?>">
<input type="hidden" name="amt" value="<?php echo $nop*$a; ?>">
<input type="hidden" name="nop" value="<?php echo $nop; ?>">
<div class="form-group">
<div align="right">
<input type="submit" name="submit" class="bme" value="Continue">
</div>
</div>
</div>
</div>
</div>
</form>
</main>
<?php include("footer.php"); ?>

unable to submit the php form

i have three files
leaveform.php
leavefrom.tpl
leaveform.class.php
i will send the codings below. olease find and solve this issue.
leaveform.php
<?php
include_once 'init.php';
include CLASS_DIR."leaveform.class.php";
$leaveformObj = new leaveform;
$email = '';
$password = '';
$err_msg = '';
$s_msg = '';
$verfication_code = '';
if(isset($_POST['leaveSubmit'])){
$branch = $_POST['branch'];
$date = $_POST['date'];
$name = $_POST['name'];
$designation = $_POST['designation'];
$employeeid = $_POST['employeeid'];
$noofdays = $_POST['noofdays'];
$from = $_POST['from'];
$to = $_POST['to'];
$reasonforleave = $_POST['reasonforleave'];
$address = $_POST['address'];
$contactno = $_POST['contactno'];
$approvedby = $_POST['approvedby'];
if(empty($branch)){
$err_msg = "Please select your branch";
}elseif(empty($date)){
$err_msg = "Please select The Date";}
else {
$leaveformObj->branch = $branch;
$leaveformObj->date = $date;
$leaveformObj->name = $name;
$leaveformObj->designation = $designation;
$leaveformObj->employeeid = $employeeid;
$leaveformObj->noofdays = $noofdays;
$leaveformObj->from = $from;
$leaveformObj->to = $to;
$leaveformObj->reasonforleave = $reasonforleave;
$leaveformObj->address = $address;
$leaveformObj->contactno = $contactno;
$leaveformObj->approvedby = $approvedby;
$addleave = $leaveformObj->addleave(); //Login as Church Admin
if($addleave){
$leaveformObj->ticket_no = "Ticket#".$addleave;
$leaveformObj->leave_id = $addleave;
$Ticket = $leaveformObj->updateTicket();
if ($Ticket) {
$s_msg = "Successfully Submitted<br>";
$s_msg .= "Your Ticket No : Ticket#".$addleave;
}
}else{
$err_msg = "Invalid leaveform details";
}
}
}
$smarty->assign('s_msg', $s_msg);
$smarty->assign('err_msg', $err_msg);
$smarty->display('leaveform.tpl');
?>
leaveform.tpl
{include file="inc/main_header.tpl"}
<style type="text/css">
option {
text-transform: capitalize;
}
.nopadding div{
padding: 0px !important;
}
form[role="login"] input.inputText{
padding: 0;
border: 0;
background: none;
border-bottom: 1px dotted;
box-shadow: none;
border-radius: initial;
width: 85%;
}
form[role="login"] .threeCol input.inputText{
width: 68%;
}
</style>
<div class="wrapper">
<!-- Left side column. contains the logo and sidebar -->
<div class="container">
<div class="col-md-12">
<!--breadcrumbs start -->
<!--<ul class="breadcrumb front">
<li><i class="fa fa-home"></i> Home</li>
<li class="active">Admin Login</li>
</ul>-->
<!--breadcrumbs end -->
</div>
<section class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form method="post" action="" role="login" id="FormValidate">
<div class="col-md-3">
<img src="images/krishnasweet.png" alt="Krishna Sweet" class="" width='180'>
</div>
<div class="col-md-6">
<h3 style="text-align: center;color: blue;font-style: italic;">Leave Application Form<br></h3>
</div>
{if $s_msg}
<p style="text-align: center; color:green;">{$s_msg}</p>
{elseif $err_msg}
<p style="text-align: center; color:red;">{$err_msg}</p>
{/if}
<div class="col-md-12" style="min-height:30px;"></div>
<div class="col-md-3"> </div>
<div class="col-md-15" >
<div class="col-md-12 nopadding">
<div class="col-md-6"><label style="display: inline-block;">Branch :</label><input type="text" class="inputText" name="branch"></div>
<div class="col-md-6"><label style="display: inline-block;">Date :</label><input type="date" class="inputText" name="date"></div>
</div>
<div class="col-md--1"> </div>
</div>
<div class="col-md--1"> </div>
<div class="col-md--1" >
<div class="col-md--1">
</div>
</div>
<div class="col-md--1"> </div>
<div class="col-md-2" >
</div>
<div class="col-md-12 nopadding">
<div class="col-md-8"><label style="display: inline-block;">Name :</label><input type="text" class="inputText" name="name"></div>
<div class="col-md-8"><label style="display: inline-block;">Designation:</label><input type="text" class="inputText" name="designation"></div>
</div><div class="col-md-12 nopadding">
<div class="col-md-7"><label style="display: inline-block;">Employee ID :</label><input type="text" class="inputText" name="employeeid"></div>
</div>
<div class="col-md-12 threeCol nopadding">
<div class="col-md-4"><label style="display: inline-block;">No.Of.Days:</label><input type="text" class="inputText" name="noofdays"></div>
</div><div class="col-md-12 threeCol nopadding">
<div class="col-md-4"><label style="display: inline-block;">From:</label><input type="date" class="inputText" name="from" ></div>
<div class="col-md-4"><label style="display: inline-block;">To:</label><input type="date" class="inputText" name="to" ></div>
</div>
<div class="col-md-12 nopadding">
<div class="col-md-12"><label style="display: inline-block;">Reason For Leave:</label><input type="text" class="inputText" name="reasonforleave" "></div>
<div class="col-md-12"><label style="display: inline-block;">Address:</label><input type="text" class="inputText" name="address" "></div>
</div>
<div class="col-md-9"><label style="display: inline-block;">Contact No:</label><input type="text" class="inputText" name="contactno"></div>
<div class="col-md-9"><label style="display: inline-block;">Approved By:</label><input type="text" class="inputText" name="approvedby"></div>
</div>
<button type="submit" name="leaveSubmit" class="btn btn-block btn-info">Submit</button>
</form>
</div>
</div>
</section>
</div>
</div>
{include file="inc/main_footer.tpl"}
<script>
$(document).ready(function(){
$(document).on("change","#categorySection",function(event) {
var _val = $(this).val();
if(_val != ""){
$("#subCategorySection option").hide();
$("#subCategorySection option[data-cat="+_val+"]").show();
$("#subCategorySection").removeAttr("disabled");
}
});
});
</script>
leaveform.class.php
<?php
class leaveform
{
var $leave_id;
var $branch;
var $date;
var $name;
var $designation;
var $employeeid;
var $noofdays;
var $from;
var $to;
var $reasonforleave;
var $address;
var $contactno;
var $approvedby;
function complaints($leave_id = '')
{
global $db,$smarty;
if ( $leave_id )
{
$this->leave_id = $leave_id;
$sql = "SELECT * FROM leaveform WHERE leave_id=$this->leave_id";
$leaveform = $db->getRow($sql);
if($leaveform != null)
{
$this->leave_id = trim(stripslashes($leaveform['leave_id']));
$this->branch = trim(stripslashes($complaints['branch']));
$this->date = trim(stripslashes($complaints['date']));
$this->name = trim(stripslashes($complaints['name']));
$this->designation = trim(stripslashes($complaints['designation']));
$this->employeeid = trim(stripslashes($complaints['employeeid']));
$this->noofdays = trim(stripslashes($complaints['noofdays']));
$this->from = trim(stripslashes($complaints['from']));
$this->to = trim(stripslashes($complaints['to']));
$this->reasonforleave = trim(stripslashes($complaints['reasonforleave']));
$this->address = trim(stripslashes($complaints['address']));
$this->contactno = trim(stripslashes($complaints['contactno']));
$this->approvedby = trim(stripslashes($complaints['approvedby']));
}
}else {
$this->leave_id = "";
$this->branch = "";
$this->date = "";
$this->name = "";
$this->designation = "";
$this->employeeid = "";
$this->noofdays = "";
$this->from = "";
$this->to = "";
$this->reasonforleave = "";
$this->address = "";
$this->contactno = "";
$this->approvedby = "";
}
}
/***
Add Church Admin
Used Php Files : Index.php
***/
function addleave()
{
global $db, $smarty;
$sql = "INSERT INTO leaveform(branch,date,name,designation,employeeid,noofdays,from,to,reasonforleave,address,contactno,approvedby) VALUES
('$this->branch','$this->date', '$this->name','$this->designation','$this->employeeid','$this->noofdays','$this->from','$this->to','$this->reasonforleave','$this->address',
'$this->contactno','$this->approvedby')";
$result = $db->Execute($sql);
$leave_id = $db->insert_ID();
if($result)
{
return $leave_id;
}else{
return 0;
}
}
function updateTicket()
{
global $db, $smarty;
$sql = " UPDATE leaveform SET ticket_no = '$this->ticket_no' WHERE leave_id = '$this->leave_id' ";
$leave_id = $db->Execute($sql);
if($leave_id){
return true;
}else{
return false;
}
}
}
?>
i am using three php codes. i have a error with invalid details in php form.
kindly help me to solve this issue..and i am new to php
The failure is because of the below piece of Code. You are basically not setting the parameters correctly.
$sql = "INSERT INTO leaveform(branch,date,name,designation,employeeid,noofdays,from,to,reasonforleave,address,contactno,approvedby) VALUES
('$this->branch','$this->date', '$this->name','$this->designation','$this->employeeid','$this->noofdays','$this->from','$this->to','$this->reasonforleave','$this->address',
'$this->contactno','$this->approvedby')";
$result = $db->Execute($sql);
$leave_id = $db->insert_ID();
No one would go around debugging it for you. Turn on the "Show errors" options in your php.ini. The below link will help you.
https://www.inmotionhosting.com/support/website/php-troubleshooting/troubleshoot-php-errors
This will start showing the errors in the page itself and you should be able to debug.
Advice: Use PDO objects and bind every parameter to execute script in a cleaner way.

Answering To Telegram Users Separately

I'm working on a Content Management System using PHP for controlling over my Telegram Bot. Basically what I have done till now is that I can read the messages that people has sent to my Telegram Bot and answer to them.
In order to do that, I coded this:
<?php
$botToken = '423495534:asdsadsadasdsadsa';
$website = 'https://api.telegram.org/bot'.$botToken;
$update = file_get_contents($website."/getUpdates");
$updateArray = json_decode($update, TRUE);
$info = file_get_contents($website."/getme");
$infoArray = json_decode($info, TRUE);
$num = count($updateArray["result"]);
$sender_ids = array();
$sender_infos = array();
for($i=0;$i<$num;$i++){
$sender_id = $updateArray["result"][$i]["message"]["from"]["id"];
$sender_isbot = $updateArray["result"][$i]["message"]["from"]["is_bot"];
$sender_fname = $updateArray["result"][$i]["message"]["from"]["first_name"];
$sender_lname = $updateArray["result"][$i]["message"]["from"]["last_name"];
$sender_uname = $updateArray["result"][$i]["message"]["from"]["username"];
$sender_type = $updateArray["result"][$i]["message"]["chat"]["type"];
$sender_msg = $updateArray["result"][$i]["message"]["text"];
$sender_date = $updateArray["result"][$i]["message"]["date"];
if(false === $key = array_search($sender_id, $sender_ids)){
$sender_ids[] = $sender_id;
$sender_infos[] = [
'sender_id' => $sender_id,
'sender_isbot' => $sender_isbot,
'sender_fname' => $sender_fname,
'sender_lname' => $sender_lname,
'sender_uname' => $sender_uname,
'sender_type' => $sender_type,
'sender_msg' => [$sender_msg],
'sender_date' => [$sender_date]
];
}else{
$sender_infos[$key]['sender_msg'][] = $sender_msg;
$sender_infos[$key]['sender_date'][] = $sender_date;
}
}
$num2 = count($sender_ids);
for($j=0;$j<$num2;$j++){
$id = $sender_infos[$j]["sender_id"];
$first_name = $sender_infos[$j]["sender_fname"];
$last_name = $sender_infos[$j]["sender_lname"];
$username = $sender_infos[$j]["sender_uname"];
$messages = $sender_infos[$j]["sender_msg"];
$acc_type = $sender_infos[$j]["sender_type"];
$isbot = $sender_infos[$j]["sender_isbot"];
$num1 = count($messages);
echo '
<div class="col-md-3">
<div class="box box-danger direct-chat direct-chat-danger">
<div class="box-header with-border">
<h3 class="box-title">'.$first_name.'</h3>
<sup>'.$acc_type.' - '.$isbot.'</sup>
<div class="box-tools pull-right">
<span data-toggle="tooltip" title="'.$num1.' New Messages" class="badge bg-red">'.$num1.'</span>
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="Contacts" data-widget="chat-pane-toggle">
<i class="fa fa-comments"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
<div class="direct-chat-messages">
<div class="direct-chat-msg">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-left">';
echo '<strong>'.$first_name.'</strong>';
echo '
</span>
</div>';
for($i=0;$i<$num1;$i++){
echo '<div class="direct-chat-text">';
$text = $sender_infos[$j]["sender_msg"][$i];
if($text[0] === '/') {
echo ''.$text.'';
}else{
echo $text;
}
echo '<span class="direct-chat-timestamp pull-right">';
// echo date('l', $sender_infos[$j]["sender_date"][$i]);
echo '</span>';
echo '</div>';
}
echo '
</div>
<div class="direct-chat-msg right">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-right">'.$bot_fname.'</span>
</div>
<img class="direct-chat-img" src="
';
if ($dataSet->GetAvatar() != NULL){
echo $dataSet->GetAvatar();
}else{
echo "img/noprofilepic.jpg";
}
echo '
" alt="Message User Image">
';
$num3 = count($request_params["text"]);
foreach($_SESSION['messages'] as $reply){
echo '<div class="direct-chat-text">';
echo $reply;
echo '</div>';
}
echo '
</div>
</div>
<div class="direct-chat-contacts">
<ul class="contacts-list">
<li>
<a href="#">
<div class="contacts-list-info">
<span class="contacts-list-name">
';
echo $first_name = $sender_infos[$j]["sender_fname"];
echo ' </br> ';
echo $last_name = $sender_infos[$j]["sender_lname"];
echo ' </br> ';
echo ' <a target="_blank" href="http://www.t.me/'.$username.'">'.$username.'</a>';
echo ' </br> ';
echo ' <small class="contacts-list-date pull-right">'.$id.'</small>
</span>
<span class="contacts-list-msg">QUOTE</span>
</div>
</a>
</li>
</ul>
</div>
</div>';
if (isset($_POST['send'])){
$pm = $_POST['message'];
array_push($_SESSION['messages'], $pm);
$request_params = [
'chat_id' => $id,
'text' => $pm
];
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=telegrambots.php?user_name=".$user_name."'>";
$request_url = 'https://api.telegram.org/bot' . $botToken . '/sendMessage?' . http_build_query($request_params);
$response = file_get_contents($request_url);
}
echo '
<div class="box-footer">
<form action="" method="post">
<div class="input-group">
<input type="text" name="message" placeholder="Write your direct message" class="form-control">
<span class="input-group-btn">
<input name="send" type="submit" class="btn btn-danger btn-flat"/>
</span>
</div>
</form>
</div>
</div>
</div>
';
}
?>
Basically what it does is that it grabs the latest updates of my Bot and count the number of results and save it in $num. Then with a for loop I tried to divide every information about the user who has sent message. After that I store all the required information of sender in a separated array called $sender_infos. And the next for loop shows a basic Chat Box depending on the number of users.
This whole thing makes this:
So it works fine and perfect but the problem is that, whenever I try answering to one conversation, it sends the message to all the available users. This issue comes from the for loop which divides every users by the Chat Box.
However what I want to do is to send a SINGLE DIRECT MESSAGE to a CUSTOM user and NOT ALL OF THEM.
I hope I have explained my problem well, so you could understand. If not, please comment me for more information and additional updates.
NOTE: I don't want a quick answer to this question. Because I'm facing this for several days and I don't know how to solve it. Please make sure you understand what I'm asking for and then add your suggest.
Thanks in advance...

Contact.PHP Form Internal Server error

I am trying to send form data from my contact.php page using PHPMailer. But it is not working properly. It is showing internal server error.
This is my contact.php form code. Can you see what is wrong with this code.
<?PHP
session_start();
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
require_once("/home/leasingexpertzz/public_html/helpers/security.php");
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Contact</title>
<?PHP include "header.php"; ?>
</head>
<body class="size-1140">
<!-- TOP NAV WITH LOGO -->
<header>
<?PHP include "nav.php"; ?>
</header>
<section>
<div id="head">
<div class="line">
<h1>Leasing Expertz</h1>
</div>
</div>
<div id="content" class="left-align contact-page">
<h1 class="sub-title">Reach us</h1>
<div class="line">
<div class="margin">
<div class="s-12 l-6">
<h2>Leasing Expertz</h2>
<address>
<p><i class="icon-home icon"></i> Plot no. P-25 1st floor, Uppal South End, Near Eldico Mentions.</p>
<p><i class="icon-globe_black icon"></i> Sohna Road, Gurugram, Haryana, India</p>
<p><i class="icon-mail icon"></i> leasingexpertzz#gmail.com</p>
</address>
<br />
<h2>Social</h2>
<p class="fb"><i class="icon-facebook icon"></i>Leasing Expertz</p>
<p class="linkedin"><i class="icon-linked_in icon"></i>Linked In</p>
<p class="twitter"><i class="icon-twitter icon"></i>Tweeter</p>
</div>
<div class="s-12 l-6">
<h2>Write to us</h2>
<form class="customform" method="post" action="email.php">
<div class="s-12 l-7"><input name="senderEmail" placeholder="Your e-mail" title="Your e-mail" type="text" <?PHP echo isset($fields['email']) ? 'value="' . e($fields['email']) . '"' : '' ?> />
<?PHP if(!empty($errors)) : ?>
<p> <?PHP echo implode('', $errors); ?></p>
<?PHP endif;?>
</div>
<div class="s-12 l-7"><input name="sender" placeholder="Your name" title="Your name" type="text" <?PHP echo isset($fields['name']) ? 'value="' . e($fields['name']) . '"' : '' ?>/>
<?PHP if(!empty($errors)) : ?>
<p> <?PHP echo implode('', $errors); ?></p>
<?PHP endif;?>
</div>
<div class="s-12 l-7"><input name="senderPhone" placeholder="Your phone number" title="Your Phone" type="text" <?PHP echo isset($fields['phone']) ? 'value="' . e($fields['phone']) . '"' : '' ?>/>
<?PHP if(!empty($errors)) : ?>
<p> <?PHP echo implode('', $errors); ?></p>
<?PHP endif;?>
</div>
<div class="s-12"><textarea placeholder="Your massage" name="message" rows="5" <?PHP echo isset($fields['message']) ? e($fields['message']) : '' ?>></textarea>
<?PHP if(!empty($errors)) : ?>
<p> <?PHP echo implode('', $errors); ?></p>
<?PHP endif;?>
</div>
<div class="s-12 m-6 l-4"><button type="submit">Submit Button</button></div>
</form>
</div>
</div>
</div>
</div>
<!-- MAP -->
<div id="map-block">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3508.9917339135745!2d77.03635061456353!3d28.419506282502333!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x390d229e71ef44dd%3A0x9931b80f30d32dd3!2sJMD+Megapolis!5e0!3m2!1sen!2sin!4v1492751226145" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</section>
<!-- FOOTER -->
<footer>
<?PHP include "footer.php"; ?>
</footer>
<script type="text/javascript" src="owl-carousel/owl.carousel.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#owl-demo").owlCarousel({
slideSpeed : 300,
autoPlay : true,
navigation : false,
pagination : false,
singleItem:true
});
$("#owl-demo2").owlCarousel({
slideSpeed : 300,
autoPlay : true,
navigation : false,
pagination : true,
singleItem:true
});
});
</script>
</body>
</html>
<?PHP
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>
Below is my email.php for PHPMailer.
<?php
session_start();
require_once("/home/leasingexpertzz/public_html/PHPMailer_5.2.0/PHPMailerAutoload.php");
$errors =[];
if(isset($_POST["senderEmail"], $_POST["sender"], $_POST["senderPhone"], $_POST["message"])){
$fields = [
'email'=> $_POST["senderEmail"],
'name' => $_POST["sender"],
'phone' => $_POST["senderPhone"],
'message' => $_POST["message"]
];
foreach ($fields as $field => $data) {
if(empty($data)){
$errors[] = 'The' . $field . 'is required.';
}
}
if(empty($errors)){
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "localhost"; // specify main and backup server
$mail->Port = 25;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "admin#leasingexpert.co.in"; // SMTP username
$mail->Password = "xxxxxxxxxxx"; // SMTP password
$mail->From = "admin#leasingexpert.co.in";
$mail->FromName = "Leasing Expert";
$mail->AddAddress("admin#leasingexpert.co.in"); // name is optional
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(); // set email format to HTML
$mail->Subject = "Here is the subject";
$mail->Body = 'From: ' . $fields['name'] . '(' . $fields['email'] . ')' . $fields['phone'] . '<p>' . $fields['message'] .. '</p>';
if($mail->Send())
{
header("Location: http://leasingexpert.co.in/confirmation.php");
die();
}
else{
$errors[] = 'Message could not be sent.';
}
header("Location: http://leasingexpert.co.in/confirmation.php");
}
}else{
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
?>
You should try reading the logs, which can be in different places depending on your OS and the server you're using (apache, nginx...).
You could also use xdebug
Internal Server Error messages indicate that something, in general, is wrong in programming.
While developing you have to enable to error log in PHP.ini file.
Then you can easily find out the errorenter link description here

Categories