unable to submit the php form - php

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.

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"); ?>

Is my If condition correct or not about the SESSION

When I open WAMP, it opens the index.php file which redirects me to layout.php, which is the first page. I created an if condition on it to check if someone logged in, so that it displays the name of the user instead of the connexion/inscription text. Aside from that, nothing else changes.
Layout.php
<div class="header">
<div class="header-left">
<?php
if (!isset($_SESSION['login'])) {?>
<ul>
<li>Inscription</li>
<li class="login">
<div id="loginContainer"><a id="loginButton"><span>Se Connecter</span></a>
<div id="loginBox" style="display: none;">
<form id="loginForm" method="POST" action="?controller=user&action=authentification">
<fieldset id="body">
<fieldset>
<label>Login</label>
<input type="text" name="login" id="email" >
</fieldset>
<fieldset>
<label for="password">Mot de passe</label>
<input type="password" name="password" id="password">
</fieldset>
<input type="submit" id="login" value="Connexion" name="xxl1">
<label for="checkbox"><input type="checkbox" id="checkbox"> <i>Rester Connecté</i></label>
</fieldset>
<span>Mot de passe oublié?</span>
</form>
</div>
</div>
</li>
</ul>
<?php } else { $name = $_SESSION['login'] ?>
<h1 style="
font-size: 19px;
font-family: inherit;
margin-right: -11px;
margin-top: -22px;
"> Bonjour <?php echo $name?> </h1>
<a href="?controller=login&action=profil" style="
font-size: 12px;
font-family: inherit;
margin-right: -11px;
margin-top: 1px;
"> Editer mon profil </a>
<?php } ?>
</div>
Index.php
<?php
require_once('connection.php');
if (isset($_GET['controller']) && isset($_GET['action'])) {
$controller = $_GET['controller'];
$action = $_GET['action'];
} else {
$controller = 'accueil';
$action = 'home';
}
require_once('views/layout.php');
?>
Here is my Model with the Connexion function
Users.php
public static function Connex()
{
if(isset($_POST['xxl1']))
{
$db = Db::getInstance();
$login=$_POST['login'];
$password=$_POST['password'];
$requser = $db->prepare("SELECT * FROM users WHERE login = ? AND motdepasse = ?");
$requser->execute(array($login,$password));
$userexist = $requser->rowCount();
if($userexist == 1)
{
session_start();
$userinfo = $requser->fetch();
$_SESSION['login'] = $userinfo['login'];
$_SESSION['id_user'] = $userinfo['id_user'];
$_SESSION['motdepasse'] = $userinfo['motdepasse'];
if($userinfo['role']=="admin")
{
echo "TEST 1 ";
}
else if($userinfo['role']=="client")
{
echo "TEST 2";
}
}
}
}
User_controller.php
<?php
Class UserController
{
public function inscription()
{
$client = User::ajoutClient();
require_once('views/users/inscription.php');
}
public function authentification()
{
$client = User::Connex();
require_once('views/layout.php');
}
}
?>

Yahoo Weather API Working over HTTP but not HTTPS?

So I have a website where I want to display the weather. The code I have (shown below) works just fine when I have the $base_url variable set as the following:
$base_url = "http://query.yahooapis.com/v1/public/yql";
But whenever I switch it over to https (shown below) I suddenly get the following error:
Notice: Trying to get property of non-object in C:\xampp\htdocs\scheduling.r60\reports\include\weather.php on line 18
To clarify, I am using XAMPP to test this, but when I test this on a live website, it also doesn't work (the live site does have a valid SSL certificate and HTTPS is enforced).
<?php
$base_url = "https://query.yahooapis.com/v1/public/yql";
$yql_query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='mundelein, il')";
$yql_query_url = $base_url . "?q=" . urlencode($yql_query) . "&format=json";
// Making call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
// Convert JSON to PHP Object
$phpObj = json_decode($json);
print_r($phpObj);
// Getting necessary content
$cityInfo = $phpObj->query->results->channel->location->city . ", " . $phpObj->query->results->channel->location->region;
$currentDate = $phpObj->query->results->channel->item->condition->date;
$currentTemperature = $phpObj->query->results->channel->item->condition->temp;
$currentText = $phpObj->query->results->channel->item->condition->text;
$currentHigh = $phpObj->query->results->channel->item->forecast[0]->high;
$currentLow = $phpObj->query->results->channel->item->forecast[0]->low;
$dayOneDay = $phpObj->query->results->channel->item->forecast[1]->day;
$dayOneHigh = $phpObj->query->results->channel->item->forecast[1]->high;
$dayOneLow = $phpObj->query->results->channel->item->forecast[1]->low;
$dayTwoDay = $phpObj->query->results->channel->item->forecast[2]->day;
$dayTwoHigh = $phpObj->query->results->channel->item->forecast[2]->high;
$dayTwoLow = $phpObj->query->results->channel->item->forecast[2]->low;
$dayThreeDay = $phpObj->query->results->channel->item->forecast[3]->day;
$dayThreeHigh = $phpObj->query->results->channel->item->forecast[3]->high;
$dayThreeLow = $phpObj->query->results->channel->item->forecast[3]->low;
$dayFourDay = $phpObj->query->results->channel->item->forecast[4]->day;
$dayFourHigh = $phpObj->query->results->channel->item->forecast[4]->high;
$dayFourLow = $phpObj->query->results->channel->item->forecast[4]->low;
if($currentText == "Partly Cloudy") {
$picture = "../reports/assets/imgs/weather/partly-cloudy_png.png";
}elseif($currentText == "Fog") {
$picture = "/reports/assets/imgs/weather/fog_png.png";
}elseif($currentText == "Cloudy") {
$picture = "/reports/assets/imgs/weather/partly-cloudy_png.png";
}elseif($currentText == "Mostly Cloudy") {
$picture = "/reports/assets/imgs/weather/mostly-cloudy_png.png";
}elseif($currentText == "Rain"){
$picture = "/reports/assets/imgs/weather/rain_png.png";
}elseif($currentText == "Sleet and Freezing Rain"){
$picture = "/reports/assets/imgs/weather/sleet-freezing-rain_png.png";
}elseif($currentText == "Freezing Rain"){
$picture = "/reports/assets/imgs/weather/sleet-freezing-rain_png.png";
}elseif($currentText == "Sleet"){
$picture = "/reports/assets/imgs/weather/sleet-freezing-rain_png.png";
}elseif($currentText == "Light Rain") {
$picture = "/reports/assets/imgs/weather/light-rain_png.png";
}elseif($currentText == "Fair") {
$picture = "/reports/assets/imgs/weather/fair_png.png";
}else{
$picture = "../reports/assets/imgs/weather/sunny_png.png";
}
?>
<div class="card">
<div class="card-title">Weather for <?php echo $cityInfo; ?></div>
<div class="card-content">
<center><?php echo $currentDate; ?></center>
<br />
<div class="row">
<div class="col-xs-6 col-sm-6" style="text-align: center; padding-top: 5%;">
<h1 style="margin: 0px; padding: 0px; font-size: 25pt;"><?php echo $currentTemperature; ?>°F</h1>
<h2 style="margin: 0px; padding: 0px; font-size: 20pt; font-weight: 400;"><?php echo $currentText; ?></h2>
<b><h3 style="margin: 0px; padding: 0px; font-size: 10pt; font-weight: 400;">High: <?php echo $currentHigh; ?>°F / Low: <?php echo $currentLow; ?>°F</h3></b>
</div>
<div class="col-xs-6 col-sm-6">
<center><img src="<?php echo $picture; ?>" style="width: 100%;" /></center>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<?php echo $dayOneDay; ?>
<span style="float: right;">
High: <?php echo $dayOneHigh; ?>°F
/
Low: <?php echo $dayOneLow; ?>°F
</span>
</div>
<div class="col-md-12">
<?php echo $dayTwoDay; ?>
<span style="float: right;">
High: <?php echo $dayTwoHigh; ?>°F
/
Low: <?php echo $dayTwoLow; ?>°F
</span>
</div>
<div class="col-md-12">
<?php echo $dayThreeDay; ?>
<span style="float: right;">
High: <?php echo $dayThreeHigh; ?>°F
/
Low: <?php echo $dayThreeLow; ?>°F
</span>
</div>
<div class="col-md-12">
<?php echo $dayFourDay; ?>
<span style="float: right;">
High: <?php echo $dayFourHigh; ?>°F
/
Low: <?php echo $dayFourLow; ?>°F
</span>
</div>
</div>
</div>
<div class="card-footer">
Full Report
<div class="clear"></div>
</div>
</div>

PHP performance drops when adding while output string to variable

First some general information.
My PHP runs approx 1000-1500 while loops depending on what the database returns.
Normal execution time is approx 0.3 sec. That's great :)
Now I need to load the PHP output on another page using AJAX and therefore I start adding the output to a $html variable in stead of just doing echo on it, so that it can be encoded to JSON format and send over AJAX.
I use the $html .= some_output for this. (this task must be done as many times as the while loop runs).
However after adding the $html .= in stead of echo the script is now taking +9 sec's to finish!!
That's clearly not optimal to the end user who is waiting for the AJAX call to return with some results.
I did some microtime on the code to be sure where the problem origins from - and no doubt it is the .= operator.
Any suggestions on how to minimize this?
EDIT: Here comes the code blocks.
First the one that loads flawlessly.
<?php
$time_start = microtime(true);
session_start();
include "../functions/sqlsrv_connect.php";
$skid_id = $_GET['skid_id'];
$vendor_id = $_GET['vendor_id'];
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="stylesheet" type="text/css" href="../stylesheets/fonts.css">
<link rel="stylesheet" type="text/css" href="../stylesheets/linkcontainer.css">
<script src="/js/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="parent" style="display: none;">
<?php
$sql_get_vdm_sections = "
SELECT
ml2.level2_descr,
ml2.level2_id
FROM
main_vdm_level2 AS ml2
JOIN
vdm_index AS vdm_i
ON
vdm_i.level2_id = ml2.level2_id
WHERE
vdm_i.skid_id = $skid_id
AND
vdm_i.vendor_id = $vendor_id
GROUP BY
ml2.level2_descr,
ml2.level2_id
ORDER BY
ml2.level2_id
";
$get_vdm_sections = sqlsrv_query($sqlsrv, $sql_get_vdm_sections);
while($vdm_section = sqlsrv_fetch_array($get_vdm_sections,SQLSRV_FETCH_ASSOC)){
$level2_id = $vdm_section['level2_id'];
$level2_descr = $vdm_section['level2_descr'];
?>
<div id="S<?php echo $level2_id;?>" class="section">
<div class="sectionhead">
<?php echo $level2_descr;?>
</div>
<div class="container_holder">
<div id="O<?php echo $level2_id;?>" class="obsolete_section">
<div class="obsolete_lineholder">
<div class="obsolete_header">
<div class="clmn_header">
<p class="small bold">Obsolete Documentation</p>
</div>
</div>
</div>
<div class="obsolete_lineholder">
<div class="obsolete_linkholder">
<a href="#" class="div" target="_blank">
<div class="obsolete_text">
</div>
</a>
</div>
</div>
<div class="obsolete_lineholder">
<div class="obsolete_linkholder">
<a href="#" class="div" target="_blank">
<div class="obsolete_text">
</div>
</a>
</div>
</div>
<div class="obsolete_lineholder">
<div class="obsolete_linkholder">
<a href="#" class="div" target="_blank">
<div class="obsolete_text">
</div>
</a>
</div>
</div>
</div>
<div class="active_cnt">
<div class="button_holder">
<div class="active_btn">
<p class="small">Active Documentation</p>
</div>
<div class="obsolete_btn">
<p class="small">View Obsolete Documentation</p>
</div>
</div>
<div class="lineholder">
<div class="linkholder">
<div class="clmn_header">
<p class="small bold">Chapters</p>
</div>
</div>
</div>
<div class="linkholder_cnt">
<?php
$file_verification = true;
$sql_get_section_content = "
SELECT
file_verification,
level3_head,
level3_descr,
level4_descr,
doc_no,
doc_place,
doc_denominator,
doc_type
FROM
vdm_index
WHERE
skid_id = $skid_id
AND
vendor_id = $vendor_id
AND
level2_id = $level2_id
AND
level4_descr IS NULL
";
$get_section_content = sqlsrv_query($sqlsrv, $sql_get_section_content);
$row_number = 1;
while ($section_content = sqlsrv_fetch_array($get_section_content,SQLSRV_FETCH_ASSOC)){
$level3_file_verification = $section_content['file_verification'];
$level3_head = $section_content['level3_head'];
$level3_descr = $section_content['level3_descr'];
$level3_doc_no = $section_content['doc_no'];
$level3_doc_place = $section_content['doc_place'];
$level3_doc_denominator = $section_content['doc_denominator'];
$level3_doc_type = $section_content['doc_type'];
$level3_width = 100;
$row_id = 'S'.$level2_id.'_R'.$row_number;
$sql_get_level4 = "
SELECT
file_verification,
level4_descr,
doc_no,
doc_place,
doc_denominator,
doc_type
FROM
vdm_index
WHERE
skid_id = $skid_id
AND
vendor_id = $vendor_id
AND
level2_id = $level2_id
AND
level3_descr = '$level3_descr'
AND
level4_descr IS NOT NULL
";
$get_level4 = sqlsrv_query($sqlsrv, $sql_get_level4);
$level4_array = array();
while ($level4 = sqlsrv_fetch_array($get_level4,SQLSRV_FETCH_ASSOC)){
array_push($level4_array, $level4);
}
if (!empty($level4_array)){
$level3_width -= 10;
$level4_active = true;
}
else {
$level4_active = false;
}
if ($file_verification != true){
$level3_width -= 10;
$level3_flag = true;
}
else {
$level3_flag = false;
}
?>
<div class="lineholder">
<a href="../proj_hist.pdf" class="div" target="_blank">
<div class="project">
<?php
if ($level3_doc_denominator != NULL){
?>
<svg x="0px" y="0px" width="45px" height="100%" viewBox="0 0 45 25" preserveAspectRatio="none">
<rect fill="#66FECB" width="27.1" height="25"></rect>
<polygon fill="#66FECB" points="45,12.5 27,0.000 27,25.000 "></polygon>
</svg>
<?php
}
?>
</div>
<div class="project_name">
<div class="project_text">
<?php echo $level3_doc_denominator;?>
</div>
</div>
</a>
<div class="linkholder" >
<div id="<?php echo $row_id;?>" class="top_row" >
<div class="projectstatus" style="background: #ffffff; width: 100%;">
</div>
<?php
if(!(empty($level3_head))&&empty($level3_descr)){
?>
<div class="link_text level3_head" style="float: left; width: 100%; white-space: nowrap;">
<?php echo $level3_head;?>
</div>
<?php
}
else {
?>
<a href="../functions/load_doc.php?doc_no=<?php echo $level3_doc_no.'&doc_place='.$level3_doc_place.'&doc_type='.$level3_doc_type.'&doc_denominator='.$level3_doc_denominator;?>" class="div" target="_blank">
<div class="link_text" style="float: left; width: <?php echo $level3_width;?>%; white-space: nowrap; overflow: hidden;">
<?php echo $level3_descr;?>
</div>
</a>
<?php
if($level3_flag == true){
?>
<div class="flag_this">
</div>
<?php
}
if ($level4_active == true){
?>
<div id="<?php echo $row_id;?>_EXPAND" class="expand">
<div class="expand_icon <?php echo $row_id;?>_EXPAND_icon">
</div>
</div>
<?php }
}
?>
</div>
<div class="clear">
</div>
<?php
if ($level4_active == true) {
?>
<div class="<?php echo $row_id;?>_level4">
<?php
foreach ($level4_array as $level4){
$level4_doc_no = $level4['doc_no'];
$level4_doc_place = $level4['doc_place'];
$level4_doc_type = $level4['doc_type'];
?>
<div id="<?php echo $row_id;?>_SL1" class="sub_row <?php echo $row_id;?>_EXPAND_sub">
<div class="projectstatus" style="background: #ffffff; width: 50%;">
</div>
<a href="../functions/load_doc.php?doc_no=<?php echo $level4_doc_no.'&doc_place='.$level4_doc_place.'&doc_type='.$level4_doc_type;?>" class="div" target="_blank">
<div class="sub_link_text">
<?php echo $level4['level4_descr'];?>
</div>
</a>
</div>
<div class="clear">
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
<?php
$row_number++;
}
?>
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
<div id="additional_box">
<div id="additional_info">
I hold additional information about this document!
</div>
<div id="close_additional" onclick="close_additional()">
</div>
</div>
<script>
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
function additional() {
mouseY -= 5;
mouseX += 20;
$('#additional_box').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
};
function close_additional() {
$('#additional_box').hide();
};
function reset_expansion_icon(){
var index;
var i = document.getElementsByClassName('expand_icon');
for (index =0; index < i.length; ++index) {
i[index].style.backgroundImage = "url('../img/expand.png')";
}
}
function reset_this_expansion_icon(me){
var index;
var e = $(me).children('.expand_icon')
for (index =0; index < e.length; ++index) {
e[index].style.backgroundImage = "url('../img/expand.png')";
}
}
$('.flag_this').click(function(){
additional();
});
$('.obsolete_btn').click(function() {
$('.section').hide();
var section = $(this).closest('.section');
$(section).show();
//var btn_parent = $(this).parent();
var container = $(this).closest('.container_holder');
var obsolete = $(container).children('.obsolete_section');
$(obsolete).fadeIn(500);
$('.sub_row').hide();
reset_expansion_icon();
});
$('.active_btn').click(function() {
$('.section').fadeIn(500);
$('.obsolete_section').hide();
$('.sub_row').hide();
reset_expansion_icon();
});
$('.expand').click(function() {
var parent = $(this).parent('.top_row');
var level4_class = $(parent).attr('id') + '_level4';
var sub_row_class = $(parent).attr('id') + '_EXPAND_sub';
var index;
var e = document.getElementsByClassName(sub_row_class);
var d = document.getElementsByClassName(level4_class);
for (index = 0; index < e.length; ++index) {
if(e[index].style.display == 'block'){
$(d[0]).slideUp('slow');
e[index].style.display = 'none';
}
else{
d[0].style.display = 'block';
$(e[index]).fadeIn('slow');
}
}
var expand_icon_class = $(parent).attr('id') + '_EXPAND_icon';
var i = document.getElementsByClassName(expand_icon_class);
if (e[0].style.display == 'block')
i[0].style.backgroundImage = "url('../img/condense.png')";
else
var me = $(this);
reset_this_expansion_icon(me);
});
$(window).load(function(){
$('#parent').fadeIn(300);
});
</script>
</body>
</html>
<?php
echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);
?>
And the the .= version (html, head and body is removed as it will load on another page)
<?php
$time_start = microtime(true);
session_start();
include "sqlsrv_connect.php";
$skid_id = $_POST['skid_id'];
$vendor_id = $_POST['vendor_id'];
$html = "
<div id='parent'>
";
$sql_get_vdm_sections = "
SELECT
ml2.level2_descr,
ml2.level2_id
FROM
main_vdm_level2 AS ml2
JOIN
vdm_index AS vdm_i
ON
vdm_i.level2_id = ml2.level2_id
WHERE
vdm_i.skid_id = $skid_id
AND
vdm_i.vendor_id = $vendor_id
GROUP BY
ml2.level2_descr,
ml2.level2_id
ORDER BY
ml2.level2_id
";
$get_vdm_sections = sqlsrv_query($sqlsrv, $sql_get_vdm_sections);
while($vdm_section = sqlsrv_fetch_array($get_vdm_sections,SQLSRV_FETCH_ASSOC)){
$level2_id = $vdm_section['level2_id'];
$level2_descr = $vdm_section['level2_descr'];
$html .= "
<div id='S$level2' class='section'>
<div class='sectionhead'>
$level2_descr
</div>
<div class='container_holder'>
<div id='O$level2_id' class='obsolete_section'>
<div class='obsolete_lineholder'>
<div class='obsolete_header'>
<div class='clmn_header'>
<p class='small bold'>Obsolete Documentation</p>
</div>
</div>
</div>
<div class='obsolete_lineholder'>
<div class='obsolete_linkholder'>
<a href='#' class='div' target='_blank'>
<div class='obsolete_text'>
</div>
</a>
</div>
</div>
<div class='obsolete_lineholder'>
<div class='obsolete_linkholder'>
<a href='#' class='div' target='_blank'>
<div class='obsolete_text'>
</div>
</a>
</div>
</div>
<div class='obsolete_lineholder'>
<div class='obsolete_linkholder'>
<a href='#' class='div' target='_blank'>
<div class='obsolete_text'>
</div>
</a>
</div>
</div>
</div>
<div class='active_cnt'>
<div class='button_holder'>
<div class='active_btn'>
<p class='small'>Active Documentation</p>
</div>
<div class='obsolete_btn'>
<p class='small'>View Obsolete Documentation</p>
</div>
</div>
<div class='lineholder'>
<div class='linkholder'>
<div class='clmn_header'>
<p class='small bold'>Chapters</p>
</div>
</div>
</div>
<div class='linkholder_cnt'>
";
$file_verification = true;
$sql_get_section_content = "
SELECT
file_verification,
level3_head,
level3_descr,
level4_descr,
doc_no,
doc_place,
doc_denominator,
doc_type
FROM
vdm_index
WHERE
skid_id = $skid_id
AND
vendor_id = $vendor_id
AND
level2_id = $level2_id
AND
level4_descr IS NULL
";
$get_section_content = sqlsrv_query($sqlsrv, $sql_get_section_content);
$row_number = 1;
while ($section_content = sqlsrv_fetch_array($get_section_content,SQLSRV_FETCH_ASSOC)){
$level3_file_verification = $section_content['file_verification'];
$level3_head = $section_content['level3_head'];
$level3_descr = $section_content['level3_descr'];
$level3_doc_no = $section_content['doc_no'];
$level3_doc_place = $section_content['doc_place'];
$level3_doc_denominator = $section_content['doc_denominator'];
$level3_doc_type = $section_content['doc_type'];
$level3_width = 100;
$row_id = 'S'.$level2_id.'_R'.$row_number;
$sql_get_level4 = "
SELECT
file_verification,
level4_descr,
doc_no,
doc_place,
doc_denominator,
doc_type
FROM
vdm_index
WHERE
skid_id = $skid_id
AND
vendor_id = $vendor_id
AND
level2_id = $level2_id
AND
level3_descr = '$level3_descr'
AND
level4_descr IS NOT NULL
";
$get_level4 = sqlsrv_query($sqlsrv, $sql_get_level4);
$level4_array = array();
while ($level4 = sqlsrv_fetch_array($get_level4,SQLSRV_FETCH_ASSOC)){
array_push($level4_array, $level4);
}
if (!empty($level4_array)){
$level3_width -= 10;
$level4_active = true;
}
else {
$level4_active = false;
}
if ($file_verification != true){
$level3_width -= 10;
$level3_flag = true;
}
else {
$level3_flag = false;
}
$html .= "
<div class='lineholder'>
<a href='../proj_hist.pdf' class='div' target='_blank'>
<div class='project'>
";
if ($level3_doc_denominator != NULL){
$html .= "
<svg x='0px' y='0px' width='45px' height='100%' viewBox='0 0 45 25' preserveAspectRatio='none'>
<rect fill='#66FECB' width='27.1' height='25'></rect>
<polygon fill='#66FECB' points='45,12.5 27,0.000 27,25.000 '></polygon>
</svg>
";
}
$html .= "
</div>
<div class='project_name'>
<div class='project_text'>
$level3_doc_denominator
</div>
</div>
</a>
<div class='linkholder' >
<div id='$row_id' class='top_row' >
<div class='projectstatus' style='background: #ffffff; width: 100%;'>
</div>
";
if(!(empty($level3_head))&&empty($level3_descr)){
$html .= "
<div class='link_text level3_head' style='float: left; width: 100%; white-space: nowrap;'>
$level3_head
</div>
";
}
else {
$html .= "
<a href='../functions/load_doc.php?doc_no=$level3_doc_no&doc_place=$level3_doc_place&doc_type=$level3_doc_type&doc_denominator=$level3_doc_denominator' class='div' target='_blank'>
<div class='link_text' style='float: left; width: $level3_width%; white-space: nowrap; overflow: hidden;'>
$level3_descr
</div>
</a>
";
if($level3_flag == true){
$html .= "
<div class='flag_this'>
</div>
";
}
if ($level4_active == true){
$html .= "
<div id='$row_id_EXPAND' class='expand'>
<div class='expand_icon $row_id_EXPAND_icon'>
</div>
</div>
";
}
}
$html .= "
</div>
<div class='clear'>
</div>
";
if ($level4_active == true) {
$html .= "
<div class='$row_id_level4'>
";
foreach ($level4_array as $level4){
$level4_doc_no = $level4['doc_no'];
$level4_doc_place = $level4['doc_place'];
$level4_doc_type = $level4['doc_type'];
$level4_descr = $level4['level4_desr'];
$html .= "
<div id='$row_id_SL1' class='sub_row $row_id_EXPAND_sub'>
<div class='projectstatus' style='background: #ffffff; width: 50%;'>
</div>
<a href='../functions/load_doc.php?doc_no=$level4_doc_no&doc_place=$level4_doc_place&doc_type=$level4_doc_type' class='div' target='_blank'>
<div class='sub_link_text'>
$level4_descr
</div>
</a>
</div>
<div class='clear'>
</div>
";
}
$html .= "
</div>
";
}
$html .= "
</div>
</div>
";
$row_number++;
}
$html .= "
</div>
</div>
</div>
</div>
";
$time_end = microtime(true);
$total_time = $time_end - $time_start;
$html .= 'Total execution time in seconds: ' . $total_time;
}
$html .= "
</div>
<div id='additional_box'>
<div id='additional_info'>
I hold additional information about this document!
</div>
<div id='close_additional' onclick='close_additional()'>
</div>
</div>
";
$script = "
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
function additional() {
mouseY -= 5;
mouseX += 20;
$('#additional_box').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
};
function close_additional() {
$('#additional_box').hide();
};
function reset_expansion_icon(){
var index;
var i = document.getElementsByClassName('expand_icon');
for (index =0; index < i.length; ++index) {
i[index].style.backgroundImage = 'url('../img/expand.png')';
}
}
function reset_this_expansion_icon(me){
var index;
var e = $(me).children('.expand_icon')
for (index =0; index < e.length; ++index) {
e[index].style.backgroundImage = 'url('../img/expand.png')';
}
}
$('.flag_this').click(function(){
additional();
});
$('.obsolete_btn').click(function() {
$('.section').hide();
var section = $(this).closest('.section');
$(section).show();
//var btn_parent = $(this).parent();
var container = $(this).closest('.container_holder');
var obsolete = $(container).children('.obsolete_section');
$(obsolete).fadeIn(500);
$('.sub_row').hide();
reset_expansion_icon();
});
$('.active_btn').click(function() {
$('.section').fadeIn(500);
$('.obsolete_section').hide();
$('.sub_row').hide();
reset_expansion_icon();
});
$('.expand').click(function() {
var parent = $(this).parent('.top_row');
var level4_class = $(parent).attr('id') + '_level4';
var sub_row_class = $(parent).attr('id') + '_EXPAND_sub';
var index;
var e = document.getElementsByClassName(sub_row_class);
var d = document.getElementsByClassName(level4_class);
for (index = 0; index < e.length; ++index) {
if(e[index].style.display == 'block'){
$(d[0]).slideUp('slow');
e[index].style.display = 'none';
}
else{
d[0].style.display = 'block';
$(e[index]).fadeIn('slow');
}
}
var expand_icon_class = $(parent).attr('id') + '_EXPAND_icon';
var i = document.getElementsByClassName(expand_icon_class);
if (e[0].style.display == 'block')
i[0].style.backgroundImage = 'url('../img/condense.png')';
else
var me = $(this);
reset_this_expansion_icon(me);
});
$(window).load(function(){
$('#parent').fadeIn(300);
});
";
$json = array();
$json['html'] = $html;
$json['script'] = $script;
header('Content-Type: application/json');
echo json_encode( $json );
?>
First some basic benchmarking
Actually... looking a bit more into it, the concat operator should be faster than the (often more convenient) array method...
<?php
ini_set('memory_limit', '256M');
$start = microtime(true);
$html = array();
for ($i=0; $i < 900000; $i++) {
$html[] = "Line number $i\n";
}
$html_out = implode('', $html);
$time_spent = microtime(true) - $start;
printf("Array method: %ss\n", number_format($time_spent, 5));
printf("Array method md5: %s\n", md5($html_out));
unset($start);unset($html);unset($html_out);
$start = microtime(true);
$html = '';
for ($i=0; $i < 900000; $i++) {
$html .= "Line number $i\n";
}
$time_spent = microtime(true) - $start;
printf("Concat method: %ss\n", number_format($time_spent, 5));
printf("Concat method md5: %s\n", md5($html));
unset($start);unset($html);unset($html_out);
$start = microtime(true);
ob_start();
for ($i=0; $i < 900000; $i++) {
echo "Line number $i\n";
}
$html = ob_get_clean();
$time_spent = microtime(true) - $start;
printf("Output buffering method: %ss\n", number_format($time_spent, 5));
printf("Output buffering method md5: %s\n", md5($html));
Output:
Array method: 0.43333s
Array method md5: d3700cc66c04760d857e8bc9a986399c
Concat method: 0.21945s
Concat method md5: d3700cc66c04760d857e8bc9a986399c
Output buffering method: 0.22360s
Output buffering method md5: d3700cc66c04760d857e8bc9a986399c
...then trying to answer the question
Possible cause #1
I think the only reasonable explanation to your problem is lack of physical memory - when you do a plain echo (without output buffering), you don't keep much in memory - but if the strings you are concatenating are relatively long, then you may reach the limit of your physical memory when you store them in memory (no matter which method you use to do so)... so swapping could occur...?
Possible cause #2
On line 237 in the old code you have
<div id="<?php echo $row_id;?>_EXPAND" class="expand">
In the new code (on line 250) that becomes
echo "[...]<div id='$row_id_EXPAND' class='expand'>[...]"
Which means you are looking up a variable called $row_id_EXPAND - which I'm guessing doesn't exist, and therefore could cause a write operation to one or more error-logs for each iteration of the loop (and you have several of the same mistake elsewhere) This could potentially mean tens or even hundreds of thousands of lines in the error log per request === a lot of time spent writing all that data.
To avoid this kind of problem always encapsulate variables in {}, ie. make it:
echo "[...]<div id='{$row_id}_EXPAND' class='expand'>[...]"
Try ob_start() maybe.
Not actually verfied to be faster by myself but allows you to collect the results of echo from the buffer.
Example of using ob_start():
ob_start();
echo("Hello there!"); //would normally get printed to the screen/output to browser
$output = ob_get_clean();
None of the echo's will work as PHP will use a different string buffer whose results can be loaded into an array at the end. The ob_get_clean() will allow echo to start working again.
Hope this helps.

Categories