I have a system for registering products, where the part of including photos is like this:
The code that on the part of the photos is like this:
$visualizar = '<table class="table table-bordered">
<tr>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">Tamanho <i class="fa fa-plus-circle" aria-hidden="true"></i></td>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">Quantidade</td>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">EAN</td>
</tr>';
$sql = mysqli_query($this->conexao,"SELECT * FROM loja_tamanho_grades WHERE IdGrades = '".$grades."';");
///$c = 0;
while($isfast = mysqli_fetch_assoc($sql))
{
$sqlTamanhos = mysqli_query($this->conexao,"SELECT * FROM loja_tamanhos WHERE IdTamanhos = '".$isfast["IdTamanhos"]."';");
$isfastTamanhos = mysqli_fetch_assoc($sqlTamanhos);
$visualizar .= '<tr>
<td style="font-weight: bold; text-align: center; font-size: 20px; font-style:Arial">
<input type="hidden" name="GradesEscolhidas[]" value="'.$grades.'">
<input type="text" name="TamanhosEscolhidos[]" style="border: 0px; width: 50px; text-align: center" readonly value="'.$isfastTamanhos["Tamanhos"].'">
</td>
<td>
<input type="number" name="QtdEscolhidos[]" class="form-control" min="0" oninput="this.value = Math.abs(this.value)" value="0">
</td>
<td>
<input type="text" name="EANEscolhidos[]" class="form-control" maxlength="17" style="width: 100%">
</td>
</tr>';
}
$visualizar .= '<tr>
<td colspan="3" class="text-left">
<label for="fotos" class="upload">Selecionar fotos <i class="fa fa-plus-circle fa-lg" aria-hidden="true"></i></label>
<input type="hidden" name="GradesFotos[]" value="'.$grades.'">
<input id="fotos" type="file" name="Fotos[]['.$grades.']" multiple>
</td>
</tr>';
//$c++;
$visualiza[] = $visualizar;
echo json_encode($visualiza);
When the user clicks sign up, it is directed to the method below:
if($_POST["Submit"] == "Cadastrar"){
$fotos = $_FILES["Fotos"];
$fotosTemp = $_FILES["Fotos"]["tmp_name"];
$dados = array_filter($_POST);
echo $metodos->cadastrarProdutos($dados,$fotos,$fotosTemp);
}
And the method cadastrarProdutos():
public function cadastrarProdutos(array $dados,$fotos,$fotosTemp)
{
...
$gradesEscolhidas = $dados["GradesEscolhidas"];
for($f = 0; $f < count($fotos['name']); $f++)
{
foreach($fotos['name'][$f] as $key => $value){
$fotosProd = $value;
$tempProd = $fotos['tmp_name'][$f];
$extensoesProd = array('png', 'jpg', 'jpeg','JPG');
$validarProd = pathinfo($fotosProd, PATHINFO_EXTENSION);
list($nomeFotoProd, $extensaoFotoProd) = explode($validarProd, $fotosProd);
$data = date("Y-m-d H:i");
$nomeFotoProd = md5($nomeFotoProd).".".$validarProd;
if($fotosProd == $fotoPrincipal[0])
{
$nomeFotoPrinc = $nomeFotoProd;
}
if(!in_array(strtolower($validarProd), $extensoesProd))
{
$_SESSION["ErroFoto"] = "Extensões permitidas: png e jpg";
$_SESSION["Erro"] = time() + 2;
}
else
{
move_uploaded_file($tempProd, '../../site/produtos/'.$nomeFotoProd);
$diretorioNormal = "../../site/produtos/";
$fotoDir = $diretorioNormal.$nomeFotoProd;
list($largura, $altura) = getimagesize($fotoDir);
if($validarProd == 'jpg' || $validarProd == 'jpeg' || $validarProd == 'JPG')
{
$imagem = imagecreatefromjpeg($fotoDir);
$x = 502;
$y = 529;
$origem_x = imagesx($imagem);
$origem_y = imagesy($imagem);
if($origem_x > $origem_y)
{
$final_x = $x;
$final_y = floor($x * $origem_y / $origem_x);
$f_x = 0;
$f_y = round(($y / 2) - ($final_y / 2));
}
else
{
$final_x = floor($y * $origem_x / $origem_y);
$final_y = $y;
$f_x = round(($x / 2) - ($final_x / 2));
$f_y = 0;
}
$miniatura = imagecreatetruecolor($x, $y);
imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $x, $y, $largura, $altura);
imagejpeg($miniatura,$fotoDir,9);
}
if($validarProd == 'png')
{
$imagem = imagecreatefrompng($fotoDir);
$x = 502;
$y = 529;
$origem_x = imagesx($imagem);
$origem_y = imagesy($imagem);
if($origem_x > $origem_y)
{
$final_x = $x;
$final_y = floor($x * $origem_y / $origem_x);
$f_x = 0;
$f_y = round(($y / 2) - ($final_y / 2));
}
else
{
$final_x = floor($y * $origem_x / $origem_y);
$final_y = $y;
$f_x = round(($x / 2) - ($final_x / 2));
$f_y = 0;
}
$miniatura = imagecreatetruecolor($x, $y);
imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $x, $y, $largura, $altura);
imagepng($miniatura,$fotoDir,9);
}
$query = "INSERT INTO loja_fotos_produtos(IdProdutos,IdGrades,Fotos) VALUES(?,?,?);";
$stmt = mysqli_prepare($this->conexao,$query);
mysqli_stmt_bind_param($stmt,"sss",$idProduto,$key,$value);
mysqli_stmt_execute($stmt);
if(mysqli_affected_rows($this->conexao) > 0)
{
$_SESSION["Sucesso"] = time() + 5;
}
}
}
}
}
Registration usually occurs, but the photos are as follows. How can I fix this?
Related
Basically it's supposed to get the user submitted value of the array size, and the method they want to calculate with the array from the drop down. the php successful gets the code from the array size but always sees the field with the dropdown as "mean" no matter which I select.
forms5.html:
`<html>
<head>
</head>
<body style="background-color: rgb(192, 192, 192);">
<div class="container" style="background-color: rgb(165, 165, 165); width: 575px; height: 250px; border: ridge; border-color: rgb(209, 209, 209);">
<form name = "form1" method = "get" action = "actions_5.php">
<div class = "form-group" style=" padding-left: 10px; padding-right: 10px; padding-top: 10px;">
<label><h2>Enter size of an array</h2></label> <br>
<input type = "number" name = "array_size" placeholder="Type in an integer">
</div>
<br>
<div style="padding-left: 10px; padding-right: 10px;">
<label><b>Select an option</b></label>
<select name = "option" class="form-control">
<option value="mean">Calculate Mean</option>
<option value="median">Calculate Median</option>
<option value="mode">Calculate Mode</option>
</select>
</div>
<div style="padding: 10px;">
<input type="submit" class="btn btn-primary">
</div>
</form>
</div>
</body>
</html>'
actions_5.php:
'<?php
session_start();
echo "<html>";
echo "<head>";
echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
';
echo "</head>";
echo "<body style='background-color: lightgray'>";
//store variables
$choice = $_GET['option'];
$size = $_GET['array_size'];
//create array
for($i = 0; $i < $size; $i++) {
$array[$i] = mt_rand(1,10);
}
echo "<div style = 'color: green; padding-top: 160px'><center><h3>Initialized array --><h3></center></div>";
echo "<br>";
echo"<center><div style = 'color: red; font-size: 35px; padding-top: 10px'>";
for($i = 0; $i < $size; $i++) {
echo"<b>$array[$i] </b>";
}
echo"</div></center>";
echo"<br>";
//if statements
echo"<center><div style = padding=top: 10px; front-size: 35px>";
if($choice = "mean") {
$mean = array_sum($array) / count($array);
echo"<p style = 'color:crimson'><b>Mean = $mean</b></p>";
} else if($choice = "mode") {
sort($array);
sort($array, $size);
$max = 1;
$mode = $array[0];
$current = 1;
for($i = 0; $i < $size; $i++){
if($array[$i] == $array[$i] - 1){
$current++;
}
else {
if($current > $max) {
$max = $current;
$mode = $array[$i - 1];
}
$current = 1;
}
}
if($current > $max) {
$max = $current;
$mode = $array[$size - 1];
}
if($max = 1) {
echo"<p style = 'color:teal'><b>There is no mode in the set.</b></p>";
} else{
echo"<p style = 'color:teal'><b>Mode = $mode</b></p>";
}
} else {
rsort($array);
$n = count($array) / 2;
$median = $array($n);
echo"<p style = 'color:blue'><b>Median = $median</b></p>";
}
echo"</div></center>";
echo "</body>";
echo "</html>";
?>'
Recently, I discovered that the exam scores of students are not displaying anymore in a particular class (PRE-NURSERY).
Going back to the form where results are added, I see that the results have been repopulated and are already stored in the database.
However, they are not been displayed in the view. I wonder what must be wrong.
model
public function getRecentmtGradesRN($id)
{
$this->db->select('*');
$this->db->where('student_id', $id);
return $this->db->get('mtscores_rn')->result();
}
controller
public function view($id)
{
if (!$this->rbac->hasPrivilege('student', 'can_view')) {
access_denied();
}
$data['title'] = 'Student Details';
$student = $this->student_model->get($id);
$gradeList = $this->grade_model->get();
if($class_id == 2 || $class_id == 3) //see here
{
$subjectmtScores = $this->student_model->getRecentmtGradesRN($id);
}
else
{
$subjectmtScores = $this->student_model->getRecentmtGrades($id);
}
$studentSession = $this->student_model->getStudentSession($id);
$timeline = $this->timeline_model->getStudentTimeline($id, $status = '');
$data["timeline_list"] = $timeline;
$student_session_id = $studentSession["student_session_id"];
$student_session = $studentSession["session"];
$data['sch_setting'] = $this->sch_setting_detail;
$data['adm_auto_insert'] = $this->sch_setting_detail->adm_auto_insert;
$current_student_session = $this->student_model->get_studentsession($student['student_session_id']);
$data["session"] = $current_student_session["session"];
$student_due_fee = $this->studentfeemaster_model->getStudentFees($student['student_session_id']);
$student_discount_fee = $this->feediscount_model->getStudentFeesDiscount($student['student_session_id']);
$data['student_discount_fee'] = $student_discount_fee;
$data['student_due_fee'] = $student_due_fee;
$siblings = $this->student_model->getMySiblings($student['parent_id'], $student['id']);
$student_doc = $this->student_model->getstudentdoc($id);
$data['student_doc'] = $student_doc;
$data['student_doc_id'] = $id;
$category_list = $this->category_model->get();
$data['category_list'] = $category_list;
$data['gradeList'] = $gradeList;
$data['subjectmtScores'] = $subjectmtScores; //see here
//var_dump($subjectmtScores); die();
$data['student'] = $student;
$data['siblings'] = $siblings;
$class_section = $this->student_model->getClassSection($student["class_id"]);
$data["class_section"] = $class_section;
$session = $this->setting_model->getCurrentSession();
$studentlistbysection = $this->student_model->getStudentClassSection($student["class_id"], $session);
$data["studentlistbysection"] = $studentlistbysection;
$data['guardian_credential'] = $this->student_model->guardian_credential($student['parent_id']);
$data['reason'] = $this->disable_reason_model->get();
if ($student['is_active'] = 'no') {
$data['reason_data'] = $this->disable_reason_model->get($student['dis_reason']);
}
// //var_dump($data['teacher_comment']);
$this->load->view('layout/header', $data);
$this->load->view('student/studentShow', $data);
$this->load->view('layout/footer', $data);
}
view
<table class="table table-bordered" style="border: 1px solid black;">
<caption class="text-center">ACADEMIC PERFORMANCE</caption>
<thead>
<tr style="border: 1px solid black;">
<th style="border: 1px solid black; font-size:11px;width:120px;text-align:center;">
SUBJECTS
</th>
<th style="border: 1px solid black; font-size:11px;text-align:center;">CLASS
EXPECTATION
</th>
<th style="border: 1px solid black;font-size:11px;text-align:center;">MILESTONE
ACHIEVED
</th>
<th style="border: 1px solid black;font-size:11px;text-align:center;">REMARKS</th>
</tr>
</thead>
<tbody>
<?php $i = 1;
$total = 0;
$count = count($subjectmtScores);
foreach ($subjectmtScores as $value) { ?>
<?php
$mt_tot_score = $value->mt_ca1 + $value->mt_ca2 + $value->mt_ca3 + $value->mt_ca4 + $value->mt_affective + $value->mt_psychomotor + $value->mt_exam;
if ($mt_tot_score >= 80) {
$grade = 'A';
$remark = 'EXCELLENT';
} elseif ($mt_tot_score >= 70 && $mt_tot_score <= 79.99) {
$grade = 'B';
$remark = 'VERY GOOD';
} elseif ($mt_tot_score >= 60 && $mt_tot_score <= 69.99) {
$grade = 'C';
$remark = 'GOOD';
} elseif ($mt_tot_score >= 50 && $mt_tot_score <= 59.99) {
$grade = 'E';
$remark = 'PASS';
} elseif ($mt_tot_score >= 40 && $mt_tot_score <= 49.99) {
$grade = 'F';
$remark = 'FAIR';
} elseif ($mt_tot_score >= 0 && $mt_tot_score<= 39.99) {
$grade = 'FL';
$remark = 'FINAL LETTER GRADE';
}
?>
<?php
$total += $mt_tot_score;
?>
<tr style="border: 1px solid black;">
<td style="border: 1px solid black;font-size:12px;text-align:left;height:30px;"><?php echo $CI->GetSubjectNameWithID($value->subject_id); ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:center;"><?php echo $value->mt_ca1; ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:center;"><?php echo $value->mt_ca2; ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:left;white-space:nowrap;"><?php echo $value->mt_ca3; ?></td>
</tr>
<?php $i++;
} ?>
</tbody style="
white-space: nowrap;
">
</table>
I am working on a PHP page that gets data from a MySQL table and one of the requirements is that the user can select how many items can appear at any given time (50,100,250,500, and All).
I am having a tough time getting all the items to appear on the site when the table has a little more than 5000 items. I tested the page on both Google Chrome and Microsoft Edge, on Chrome it crashes at around 3200 items and on Edge at around 4500.
This is driving me insane! Can you please tell me how to fix this? Thanks!
The site normally looks like so:
So far all I've tried is using flush() and set_time_limit(0), but the change is minimal.
Here's the section that deals with the table data:
$tablaO=listadoFaltantes($filProveedor, $filEstatus, $filMargin, $valor, $filGuia, $pais, $paisu, $registroPorPagina, $pagina);
if(mysqli_num_rows($tablaO)>0)
{
ob_start();
$i = 0;
$e = 1;
if($pagina > 1) $e = 1*($registroPorPagina*($pagina-1))+1;
$CantidadTres = 1;
while($registroO=mysqli_fetch_assoc($tablaO))
{
$fechaCambio = $registroO['art_fecha_cotizado'];
$entregado = false;
$estatusOrden = "Buenot2";
if(!$entregado)
{
$date = date("Y-m-d");
$diff = abs(strtotime($date) - strtotime($fechaCambio));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
if(ceil($days)>=3)
{
if(ceil($days) == 3){
if(isWeekend(date('Y-m-d',strtotime("-1 days"))) || isWeekend(date('Y-m-d',strtotime("-2 days"))))
{
if ($e%2!= 0)
{
$estatusOrden = "bueno";
}else{
$estatusOrden = "Buenot2";
}
}else{
if($registroO['art_id_proveedor'] == '?' OR $registroO['art_id_estatus'] == 'SC')
{
$estatusOrden = "tardio";
$CantidadTres = $CantidadTres + 1;
}elseif ($e%2!= 0){
$estatusOrden = "bueno";
}
}
}else{
if($registroO['art_id_proveedor'] == '?' OR $registroO['art_id_estatus'] == 'SC')
{
$estatusOrden = "tardio";
$CantidadTres = $CantidadTres + 1;
}else if ($e%2!= 1){
$estatusOrden = "Buenot2";
}
}
}else{
if ($e%2== 0)
{
$estatusOrden = "bueno";
}else{
$estatusOrden = "Buenot2";
}
}
}else{
if ($e%2== 0)
{
$estatusOrden = "bueno";
}else{
$estatusOrden = "Buenot2";
}
}
$estatus = $registroO['art_id_estatus'];
if($estatus != 'CF')
{
switch($estatus)
{
case 'EC':$color='ffffff';
break;
case 'SC':$color='ffffff';
break;
case 'CE':$color='ffffff';
break;
case 'AP':$color='ffffff';
break;
case 'PA':$color='ffffff';
break;
case 'PB':$color='ffffff';
break;
case 'RE':$color='ffffff';
break;
case 'ER':$color='ffffff';
break;
case 'RO':$color='background-color: #ff6699 !important;';
break;
case 'EO':$color='background-color: #67a22a !important;';
break;
case 'LE':$color='background-color: #92d050 !important;';
break;
}
if($registroO['art_id_proveedor'] == '?' and $registroO['art_id_estatus'] == 'ST')
{
$colorLetra = 'color: #212020;';
}else{
$colorLetra = 'color: #000;';
}
if($registroO['art_cortado'] != '0')
{
if($registroO['art_cortado'] == '1')
{
$VeriCortado = '';
$listaVeriCortado = listadoArticulosQueFueronCortadosDeEste($registroO['art_id_verificador']);
while($regVeriCortado = mysqli_fetch_assoc($listaVeriCortado)){
$VeriCortado .= $regVeriCortado['art_id_verificador']."\r\n";
}
$cortado = '<img src="images/cortar1.png" style=" width: 30px;height: auto;" class="icon" title = "Este registro fue cortado en partes. De clic para ver los artículos relacionados." />
<div id="corte'.$i.'" style="display:none;"><textarea readonly>'.$VeriCortado.'</textarea></div>';
}else{
$cortado = '<img src="images/cortar2.png" style=" width: 30px;height: auto;" class="icon" title = "Este registro es parte de otro que fue cortado. De clic aquí para ver el registro original." />
<div id="cortado'.$i.'" style="display:none;"><textarea readonly>'.$registroO['art_cortado_de'].'</textarea></div>';
}
}else{
$cortado = '';
}
$ordenart= $registroO["art_id_orden"];
$provedorart = $registroO["art_id_proveedor"];
$ISBNar = $registroO["art_ISBN"];
$SKU1 = $registroO["art_SKU"];
$letra3 = substr($ISBNart, 1, 6);
$letra4 = substr($SKU1, -5);
$letra5 = $ordenart.$provedorart.$letra4.$letra3;
//$sumF = listadoSumaFaltantes($provedorart);
$master = listadoMaster($ISBNart,$provedorart);
$mast = $master['mast_precio'];
$verificador = $registroO['art_id_verificador'];
$detalleDeposito = detalleDepositoArtProv($provedorart,$verificador);
$dep_id = $detalleDeposito['dep_id'];
$sumFCred = listadoSumaFaltantesDeposito2($provedorart, $dep_id);
$sumF = listadoSumaFaltantesDeposito($provedorart, $dep_id);
$TipoPago = $sumFCred['pro_id_tipoPago'];
$total = $registroO['art_cantidad'] * $registroO['art_cost'];
$nuevo_texto = wordwrap($registroO['art_titulo'], 22, "</br>");
if($registroO['est_descripcion'] == 'Recibido en oficina')
{
echo '<tr valign="top" class="registro" name="tr/'.$i.'" id="tr/'.$verificador.'" style="font-size: 12px; text-align: -webkit-center; '.$colorLetra.' '.$color.' background-color: #ff6699 !important; ">';
}else{
echo '<tr valign="top" class="registro '. $estatusOrden.'" name="tr/'.$i.'" id="tr/'.$verificador.'" style="font-size: 10px;text-align: -webkit-center; '.$colorLetra.'">';
}
echo '<td style="width: 2% !important;">'.$e.'</td>
<td style=" float: left; width: 2% !important;">
<input type="checkbox" name="chbArticulo[]" value="'.$verificador.'-'.$i.'" onChange="cambia(this)" onclick="habilitarContenido();"></input>
<input type="hidden" name="letra5[]" value="'.$letra5.'" readonly="readonly" style="border: 0px;background: none;" disabled></input>
'.$cortado.'
</td>
<td style="width: 4% !important;">'.$verificador.'</td>
<td style="width: 4% !important; height: 5px !important; /* float: left;*/ max-width: 50px !important; /*margin-left: -100%;*/" onclick="myFunction('.$i.');">
<div class="popup" style="height: 5px;" onclick = "return false;">
'.$registroO['ord_id'].'';
include('include/FaltantesPopUpOrden.php');
echo'</div>
</td>
<td style="width: 4% !important;">
<a href="#" onclick=window.open("EditarBook.php?ISBN='.$registroO['art_N13'].'","ventana","width=452,height=500,scrollbars=NO,menubar=NO,resizable=NO,titlebar=NO,status=NO"); style="color: #073169;" return false>
'.$registroO['art_N13'].'
</a>
</td>
<td style="width: 4% !important;">'.$registroO['art_ISBN'].'</td>
<td style="width: 20% !important;">'.$nuevo_texto.'</td>
<td style="width: 4% !important;">'.$registroO['art_SKU'].'</td>';
if($registroO['art_id_proveedor'] == '?')
{
echo'<td style="width: 4% !important;">
<input type="text" value="'.$registroO['art_cantidad'].'" name="txtCantidad[]" style="border: 0px; text-align: -webkit-center; '.$colorLetra.'" class="inputChico" readonly="readonly" disabled />
</td>';
}else{
echo'<td style="width: 4% !important;">
<input type="text" value="'.$registroO['art_cantidad_org'].'" name="txtCantidad[]" style="border: 0px; background: rgba(255, 255, 255, 0); text-align: -webkit-center; '.$colorLetra.'" class="inputChico" readonly="readonly" disabled />
</td>';
}
if($registroO['art_Confirmacion'] == '2' or $registroO['art_Confirmacion'] == '0')
{
if($registroO['art_id_proveedor'] != '?')
{
echo'<td style=" text-align: -webkit-center; width: 4% !important;">
<input type="text" value="'.($registroO['art_cantidad_org'] == $registroO['art_cantidad'] ? $registroO['art_cantidad_org'] : $registroO['art_cantidad']).'" name="txtCambiarProv[]" style="color: red;" class="inputChico" disabled />
</td>';
}else{
echo'<td style=" text-align: -webkit-center; width: 4% !important;">
<input type="hidden" name="txtCambiarProv[]" disabled />
</td>';
}
}else{
echo'<td style="text-align: -webkit-center;color:red;font-size: 13px; font-weight: bold; width: 4% !important;">
<input type="text" name="txtCambiarProv[]" class="inputChico" value="'.$registroO['art_cantidad'].'" style="color:red; text-align: -webkit-center; border: 0px solid; background-color: transparent;" readonly disabled />
</td>';
}
echo'<td style="width: 4% !important;">$'.number_format((float)$registroO['art_precio'],2,'.','').'</td>';
if($mast != null)
{
echo'<td style="width: 4% !important;">$'.$mast.'</td>';
}else{
echo'<td style="width: 4% !important;">$'.number_format((float)$registroO['art_master'],2,'.','').'</td>';
}
echo '<td style="width: 4% !important;">$'.number_format((float)$registroO['art_cost'],2,'.','').'</td>';
if($registroO['art_Confirmacion'] == '1' or $registroO['art_Confirmacion'] == '0')
{
if($registroO['art_id_proveedor'] != '?')
{
$CostoH = DetalleCostoSKU($SKU1);
if($CostoH['cost_costo'] != NULL)
{
echo '<td style="width: 4% !important;">
$<input type="text" value="'.$CostoH['cost_costo'].'" name="txtCost[]" style="width: 50px;" class="inputChico" disabled />
</td>';
}else{
echo '<td style="width: 4% !important;">
$<input type="text" value="'.$registroO['art_cost'].'" name="txtCost[]" style="width: 50px;" class="inputChico" disabled />
</td>';
}
}else{
echo'<td style=" text-align: -webkit-center; width: 4% !important;"><input type="hidden" name="txtCost[]" disabled /></td>';
}
}else{
echo'<td style=" text-align: -webkit-center; width: 4% !important;"><input type="hidden" name="txtCost[]" disabled /></td>';
}
echo '<td style="width: 4% !important;">$'.number_format((float)$total,2,'.','').'</td>';
if($estatus == 'CE' OR $estatus == 'PA')
{
if($estatus == 'CE')
{
echo '<td style="color:red; width: 4% !important;">$'.number_format((float)$sumF['cantindad'],2,'.','').'</td>';
}
if($estatus == 'PA')
{
if($TipoPago == 'TC' OR $TipoPago == 'CD')
{
echo '<td style="color:red; width: 4% !important;">$'.number_format((float)$sumFCred['cantindad'],2,'.','').'</td>';
}else{
echo '<td style="width: 4% !important;">$</td>';
}
}
}else{
echo '<td style="width: 4% !important;">$</td>';
}
$MarginPro1 = $registroO['art_MarginProf'];
//$MarginPro1 = number_format($MarginPro1, 10, '.', '');
$MarginPro = substr($MarginPro1, 0, 1);
if($MarginPro1 == '' OR $MarginPro1 == NULL)
{
echo'<td></td>';
}else{
if($MarginPro == '0')
{
//$calrCosto = explode(".",$MarginPro1);
//$cal1 = $calrCosto[1];
//$Calr = substr($cal1, 0, 2);
if($MarginPro1 <= .5)
{
echo'<td style="background: #42c517; width: 4% !important;">'.$MarginPro1.'</td>';
}
if($MarginPro1 > .5)
{
echo'<td style="background: #ffb100; width: 4% !important;">'.$MarginPro1.'</td>';
}
}else{
echo'<td style="background: #ff0000; width: 4% !important;">'.$MarginPro1.'</td>';
}
}
echo'<td>'.$registroO['est_descripcion'].'</td>
<td>'.$registroO['art_status_recoleccion'].'</td>
<td>'.$fechaCambio.'</td>';
if($registroO['est_id'] != 'EC' && $registroO['est_id'] != 'SC')
{
echo '<td style="width: 4% !important;">
<select name="selProveedor[]" class="selectChico" style="width: 93px;" disabled>';
llenarOpciones(listadoProveedor(),'pro_id_clave','pro_id_clave',$registroO['art_id_proveedor']);
echo '</select>
</td>';
}else{
echo '<td style="width: 4% !important;">
<select name="selProveedor[]" class="selectChico" style="width: 93px;" disabled>';
llenarOpciones(listadoProveedor(),'pro_id_clave','pro_id_clave',$registroO['art_id_proveedor']);
echo '</select>
</td>';
}
echo '<td style="width: 4% !important;">
<textarea type="text" name="txtNota[]" class="areaChico" style="max-width: 140px; margin: 0px; width: 130px; max-height: 60px; height: 60px;" disabled>'.$registroO['art_nota'].'</textarea>
</td>
</tr>';
$i++;
$e++;
usleep(1);
ob_flush();
flush();
}
}
ob_end_flush();
}
I hope I'm not asking a question already answered, I have searched extensively on the site for an answer to my problem but can not manage to find a solution.
I have the following problem.
I have a form in which is a shopping cart, it is supposed to apply a coupon and then save those values so they can be used later on different pages.
For some reason however, these session variables are not saved.
My form looks like this:
<?php
session_start();
$cart_custom = json_decode($_COOKIE['view_cart_custom_fab'],true);
//print_r($cart_custom);
include_once("inc/header.php");
//set_add_to_cart_cookie();
$fetch_user_info = mysqli_query($conn,"SELECT * FROM `st_customer` WHERE `email`= '{$_SESSION['USER_EMAIL']}'");
$fetch_info = mysqli_fetch_array($fetch_user_info);
$size_id = ($_REQUEST['id'] ? $_REQUEST['id'] : $_COOKIE['fabric_size_id']);
$fabric_id = $_COOKIE['fabric_id'];
$fabric_back = $_COOKIE['fabric_back'];
$shirts = $_COOKIE['shirts'];
$fabric_arms = $_COOKIE['fabric_arms'];
$fabric_pocket = $_COOKIE['fabric_pocket'];
$fabric_cuff = $_COOKIE['fabric_cuff'];
$fabric_boy_border = $_COOKIE['fabric_boy_border'];
$fabric = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_id'");
$fabric_record = mysqli_fetch_array($fabric);
$fabric_back_data = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_back'");
$fabric_back_record = mysqli_fetch_array($fabric_back_data);
$arms = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_arms'");
$arms_record = mysqli_fetch_array($arms);
$pocket = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_pocket'");
$pocket_record = mysqli_fetch_array($pocket);
$cuff = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_cuff'");
$cuff_record = mysqli_fetch_array($cuff);
$border = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_boy_border'");
$border_record = mysqli_fetch_array($border);
$select_size = mysqli_query($conn,"SELECT * FROM `st_sizes` where `size_id` = '$size_id'");
$user_select_size = mysqli_fetch_array($select_size);
$model_id = $user_select_size['size_model'];
$model = mysqli_query($conn,"SELECT * FROM `st_model` where `model_id` = '$model_id'");
$model_name = mysqli_fetch_array($model);
if($shirts=="half_shirt"){
$shirt = $user_select_size['half_sleeve'];
}
if($shirts=="full_tshirt"){
$shirt = $user_select_size['full_sleeve'];
}
$cm1 = $fabric_record['fabric_price']/10;
$cm2 = $arms_record['fabric_price']/10;
$cm3 = $fabric_back_record['fabric_price']/10;
$front_size = ($cm1*$user_select_size['front']*100);
$back_size = ($cm3*$user_select_size['size_back']*100);
$arms_size = ($cm2*$shirt*100);
$front_back_total = $user_select_size['front']+$user_select_size['size_back'];
$custom_total = ($front_size+$back_size+$arms_size);
if(isset($_POST['apply_coupon_btn'])){
$query_coupon = mysqli_query($conn,"SELECT * FROM `st_coupon` WHERE `coupon_code`='{$_POST['coupon_apply']}' AND `status`='1'");
$fetch_coupon = mysqli_fetch_array($query_coupon);
$message = "tmp2";
if(isset($fetch_coupon)){
$_SESSION['coupon_data'] = $fetch_coupon;
$check_user_id = mysqli_query($conn,"SELECT * FROM `st_order` as so JOIN `st_coupon` as sc on so.`coupon_id`=sc.`coupon_id` WHERE sc.`coupon_code`='{$_POST['coupon_apply']}' AND so.`user_id`={$_SESSION['user_id']}");
$message = "tmp3";
if(mysqli_num_rows($check_user_id)){
$message = "U hebt deze kortingscode reeds gebruikt";
}else{
if($fetch_coupon['coupon_type'] == "price"){
$_SESSION['price_coupon_price'] = $fetch_coupon['coupon_value'];
unset($_SESSION['price_coupon_percent']);
}elseif($fetch_coupon['coupon_type'] == "percent"){
$_SESSION['price_coupon_percent'] = $fetch_coupon['coupon_value'];
unset($_SESSION['price_coupon_price']);
}
}
}else{
$message = "Foute kortingscode";
}
}
if(isset($_POST['remove_coupon_btn'])){
unset($_SESSION['price_coupon_percent']);
unset($_SESSION['price_coupon_price']);
unset($_SESSION['coupon_data']);
unset($_SESSION['price_coupon_value']);
header("location: winkelwagen.php");
}
if(isset($_POST['update_cart']))
{
echo "update cart";
foreach($_POST['custom_qty_cart'] as $key=>$qtys){
$cart_custom[$key]['price']['qty'] = $qtys;
}
setcookie('view_cart_custom_fab', json_encode($cart_custom), time() + (86400 * 2), "/");
setcookie('custom_qty', $_POST['custom_qty'], time() + (86400 * 2), "/");
$custom_total = $custom_total*$_POST['custom_qty'];
setcookie('custom', $custom_total, time() + (86400 * 2), "/");
foreach($_POST["qty"] as $key => $qty) { //Print each item, quantity and price.
$id = $_POST["product_id"][$key];
$_SESSION["products"][$id]["fabric_qty"] = $qty;
}
header("location: winkelwagen.php");
}
if(isset($_POST['checkout_btn'])){
if($_SESSION['USER_EMAIL']){
header("location: afrekenen.php");
}else{
header("location: winkelwagen.php#login-modelbox");
}
}
?>
<div class="container">
<h4><?php echo $_SESSION['price_coupon_value']; ?></h4>
<h4><?php echo $_SESSION['coupon_data']; ?></h4>
<div class="main_content fabric-content margin_top">
<?php
?>
<?php if (!empty($_SESSION["products"]) || count($cart_custom) > 0) { ?>
<form method="POST" action="winkelwagen.php" style="width:60%; float:left; position:relative; left: 50%;">
<table class="margin_top" style="float: left; position: relative; left: -50%;">
<tr>
<th data-field="id" colspan="1" style="width: 15%;"></th>
<th data-field="id" colspan="1" style="width: 35%;">Naam</th>
<th data-field="id" colspan="1" style="width: 35%;">Aantal</th>
<th data-field="id" colspan="1" style="width: 15%;">Prijs</th>
</tr>
<?php if(count($cart_custom) > 0){ ?>
<?php
$total_price = 0;
foreach($cart_custom as $key=>$val){
$cookie_model = $cart_custom[$key]['model'];
$cookie_price = $cart_custom[$key]['price'];
$model_name = $cookie_model['model'];
if($model_name == "wranglan_model"){
$model_img = "image/t-shirt.png";
}elseif($model_name == "round_model"){
$model_img = "image/t-shirt.png";
}
$model_qty = str_replace(",",".",$cookie_price['qty']);
$model_price = $model_qty * $cookie_price['ttl_price'];
$total_price = $model_qty * $cookie_price['ttl_price'] + $total_price;
if(isset($_GET['remove_id'])){
unset($cart_custom[$_GET['remove_id']]);
setcookie('view_cart_custom_fab', json_encode($cart_custom), time() + (86400 * 2), "/");
header("location: winkelwagen.php");
}
?>
<tr>
<td colspan='1' style="width: 15%;">
<img src='<?php echo $model_img; ?>' alt='' class='img_table responsive_img' />
</td>
<td colspan='1' style="width: 35%;">
T-shirt op smaak
</td>
<td colspan='1' style="width: 35%;">
<input id='update_cart' name='update_cart' type='hidden' value='' />
<input class="qty" type="text" name="custom_qty_cart[<?php echo $key; ?>]" value="<?php echo $model_qty; ?>" style="width: 20%; text-align:right;"/>
<input name='Update' style="width: 18px; vertical-align:bottom" type='image' value='update_cart' src='/image/update.jpg' alt='Update' onclick = "return setHidden('update_cart');" />
<img src="/image/recycle.jpg" style="width: 18px; vertical-align:bottom">
</td>
<td colspan='1' style="width: 15%;">
<?php echo price_format($model_price); ?>
</td>
</tr>
<?php
}
?>
<?php } ?>
<?php if(!empty($_SESSION["products"])){?>
<?php
if (isset($_SESSION["products"]) && count($_SESSION["products"]) > 0) {
$total = 0;
$list_tax = '';
foreach ($_SESSION["products"] as $product) { //Print each item, quantity and price.
//print_r($_SESSION["products"]);
$product_name = $product["fabric_name"];
$product_id = $product["id"];
//$product_qty = ($product["fabric_qty"] > 1 ? $product["fabric_qty"]:1);
$product_qty = str_replace(",",".",$product["fabric_qty"]);
//$product_price = ($product_qty>1 ? $product["fabric_price"] * $product_qty : $product["fabric_price"]);
$product_price = ($product["fabric_price"] * $product_qty);
$product_code = $product["product_code"];
$product_color = $product["product_color"];
$product_size = $product["product_size"];
$item_price = $product_price;
$total_cost_price = $total_cost_price + $item_price;
//$item_price = sprintf("%01.2f",($product_price * $product_qty)); // price x qty = total item price
if(isset($_GET['removeid'])){
unset($_SESSION["products"][$_GET['removeid']]);
header("location: winkelwagen.php");
}
$cart_box .=
"<tr><td colspan='1' style='width: 15%'><img src='admin/images/fabric/" . $product['fabric_texture'] . "' alt='' class='img_table responsive_img' /></td>
<td colspan='1' style='width: 35%'>$product_name</td>
<td colspan='1' style='width: 35%'>
<input id='update_cart' name='update_cart' type='hidden' value='' />
<input type='text' name='qty[]' class='qty' min='1' max='100' value='".$product_qty."' style='width: 20%; text-align:right;'/>
<input name='Update' style='width: 18px; vertical-align:bottom' type='image' value='update_cart' src='/image/update.jpg' alt='Update' onclick = 'return setHidden('update_cart');' />
<a href='?removeid=$product_id' style='width: 18px; vertical-align:bottom'><img src='/image/recycle.jpg' style='width: 18px; vertical-align:bottom'></a>
<input type='hidden' name='product_id[]' value='".$product_id."' /></td>
<td colspan='1' style='width: 15%'>".price_format($item_price)."</td>";
$subtotal = ($product_price * $product_qty); //Multiply item quantity * price
$total = ($total + $subtotal); //Add up to total price
}
$grand_total = $total + $shipping_cost; //grand total
foreach ($taxes as $key => $value) { //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount;
}
foreach ($tax_item as $key => $value) { //taxes List
$list_tax .= $key . ' ' . $currency . sprintf("%01.2f", $value) . '<br />';
}
$shipping_cost = ($shipping_cost) ? 'Shipping Cost : ' . $currency . sprintf("%01.2f", $shipping_cost) . '<br />' : '';
echo $cart_box;
}
?>
<?php } ?>
<?php
$fetch_shipping_price = mysqli_query($conn,"SELECT * FROM `st_custom_price` WHERE `meta_key`='shipping'");
$fetch_price = mysqli_fetch_array($fetch_shipping_price);
$shipping_price = $fetch_price['meta_price'];
$product_total = $total_price + $total_cost_price + ($price_detail['ttl_price']*$price_detail['qty']);
if($_SESSION['price_coupon_price']){
$total_amount = $total_price + $total_cost_price + ($price_detail['ttl_price']*$price_detail['qty']) - $_SESSION['price_coupon_price'];
$_SESSION['price_coupon_value'] = $_SESSION['price_coupon_price'];
}elseif($_SESSION['price_coupon_percent']){
$total_amount = $total_price + $total_cost_price + ($price_detail['ttl_price']*$price_detail['qty']);
$percent_total = ($_SESSION['price_coupon_percent'] / 100) * $total_amount;
$_SESSION['price_coupon_value'] = $percent_total;
$total_amount = $total_amount - $percent_total;
}else{
$total_amount = $total_price + $total_cost_price + ($price_detail['ttl_price']*$price_detail['qty']);
}
$ttl_ship = $total_amount + $shipping_price;
setcookie('total_cost', $ttl_ship, time() + (86400 * 2), "/");
setcookie('total_cost', $ttl_ship, time() + (86400 * 2), "/");
?>
<?php if(!empty($total_amount) || count($cart_custom) > 0){ ?>
<tr>
<th data-field="id" colspan="3" style="width: 85%;">Totaal</th>
<th data-field="id" colspan="1" style="width: 15%;"> <?php echo price_format($product_total); ?></th>
</tr>
<?php if($_SESSION['price_coupon_price'] || $_SESSION['price_coupon_percent']){
$discount_type = ($_SESSION['coupon_data']['coupon_type'] == "price" ? " €" : " percent ");
?>
<tr>
<th data-field="id" colspan="3" style="width: 85%;">
<input id='remove_coupon_btn' name='remove_coupon_btn' type='hidden' value='' />
Kortingscode <?php echo $_SESSION['coupon_data']['coupon_name']; ?><input name='remove_coupon_btn' style="width: 18px; vertical-align:bottom" type='image' value='remove_coupon_btn' src='/image/recycle.jpg' alt='Remove coupon' onclick = "return setHidden('remove_coupon_btn');" />
</th>
<th style="width: 15%;"><?php echo price_format($total_amount-$product_total); ?></th>
</tr>
<?php } ?>
<tr>
<th data-field="id" colspan="3" style="width: 85%;">Verzendingskosten</th>
<th data-field="id" colspan="1" style="width: 15%;"> <?php echo price_format($shipping_price); ?></th>
</tr>
<tr>
<th data-field="id" colspan="3" style="width: 85%;">Te betalen</th>
<th data-field="id" colspan="1" style="width: 15%;"> <?php echo price_format($ttl_ship); ?></th>
</tr>
</table>
<?php echo $message; ?>
<div class="more-products-pagination" style="float: left; position: relative; left: -50%;">
<div class="coupon_row" style="margin:5px 20px">
<?php if($_SESSION['price_coupon_price'] || $_SESSION['price_coupon_percent']){ ?>
<?php } else { ?>
<ul>
<li>Kortingscode</li>
<li><input type="text" name="coupon_apply" value=""><input type="submit" name="apply_coupon_btn" value="Toepassen" class="add_to_cart_btn" style="border: 1px solid #fff; display: inline-block;float: right;"></li>
</ul>
<?php } ?>
</div>
<div class="pagination_btn pagination_btn_right">
<input type="submit" class="add_to_cart_btn" value="Afrekenen" name="checkout_btn">
</div>
</div>
<?php } ?>
</form>
<?php }else {
echo "Geen producten in uw winkelwagen.";
}?>
</div>
</div>
<script language="javascript">
function setHidden(whichButton)
{
var element = document.getElementById(whichButton);
element.value = whichButton;
return true;
}
</script>
<?php
include_once("inc/footer.php");
?>
<style>
table {
border-collapse: collapse;
width: 100%;
background: rgba(253, 245, 208,0.6);
box-shadow: 0px 0px 2px #C1C1C1;
}
th, td {
text-align: left;
padding: 8px;
color:#444;
}
td{
}
th {
background-color: #BD3F6F;
color: white;
font-weight: 400;
font-size: 16px;
}
</style>
When I then try to access the variable $_SESSION['coupon_data'] on a different page this does not work, it is empty.
I set the variable here in this code:
if(isset($_POST['apply_coupon_btn'])){
$query_coupon = mysqli_query($conn,"SELECT * FROM `st_coupon` WHERE `coupon_code`='{$_POST['coupon_apply']}' AND `status`='1'");
$fetch_coupon = mysqli_fetch_array($query_coupon);
$message = "tmp2";
if(isset($fetch_coupon)){
$_SESSION['coupon_data'] = $fetch_coupon;
..
}
And then I call the next page here:
if(isset($_POST['checkout_btn'])){
if($_SESSION['USER_EMAIL']){
header("location: afrekenen.php");
}else{
header("location: winkelwagen.php#login-modelbox");
}
}
Even if I call the update of the cart items in this same page, the session variables disapear for some reason which I do not understand:
if(isset($_POST['update_cart']))
{
echo "update cart";
foreach($_POST['custom_qty_cart'] as $key=>$qtys){
$cart_custom[$key]['price']['qty'] = $qtys;
}
setcookie('view_cart_custom_fab', json_encode($cart_custom), time() + (86400 * 2), "/");
setcookie('custom_qty', $_POST['custom_qty'], time() + (86400 * 2), "/");
$custom_total = $custom_total*$_POST['custom_qty'];
setcookie('custom', $custom_total, time() + (86400 * 2), "/");
foreach($_POST["qty"] as $key => $qty) { //Print each item, quantity and price.
$id = $_POST["product_id"][$key];
$_SESSION["products"][$id]["fabric_qty"] = $qty;
}
header("location: winkelwagen.php");
}
I am utterly baffled and hope someone can help me out.
issue resolved, turns out there was another call to session_start in one of the includes which was creating a separate session and hence not allowing the correct globalisation.
I have a widget that has a form in it. my goal is that when the submit button is pressed some data gets send to php which will run a function to get data form db. I need the data in the js file so right now i jsonify the data en put it in a file called data.json. from that file i get the data with jquery.ajax().
My question is: How can i make this more efficiant?
.php
<?php
chdir('/var/www/html/vtigercrm');
require_once('include/utils/utils.php');
if(isset($_POST['id']) && !empty($_POST['id'])){
$filterdData = getChartData($_POST['id'], $_POST['maxAmount'], $_POST['minAmount']);
$file = fopen("/var/www/html/vtigercrm/include/data.json", "w");
fwrite($file, json_encode($filterdData));
fclose($file);
}
function getChartData($product_id, $maxAmount=NULL, $minAmount=NULL){
global $adb;
$maxAmountQuery = "";
$minAmountQuery = "";
if(!is_null($maxAmount) && $maxAmount != ""){
$maxAmountQuery = " AND i.quantity <= " . $maxAmount;
}
if(!is_null($minAmount) && $minAmount != ""){
$minAmountQuery = " AND i.quantity >= " . $minAmount;
}
$sales = $adb->run_query_allrecords("SELECT c.modifiedtime, i.quantity, i.listprice, i.discount_percent, i.discount_amount, CONCAT(q.quote_no, ' ', q.subject) AS quotename " .
"FROM vtiger_inventoryproductrel i " .
"INNER JOIN vtiger_crmentity c ON c.crmid = i.id " .
"INNER JOIN vtiger_quotes q ON q.quoteid = i.id " .
"WHERE q.quotestage = 'Delivered' AND i.productid = " . $product_id .
$maxAmountQuery . $minAmountQuery .
" ORDER BY c.modifiedtime ASC");
//Calculate price after discount
$salesCalculated = [];
for($i = 0; $i < count($sales); $i++){
$tmpdate = explode(" ", $sales[$i][0]);
$salesCalculated[$i][0] = $tmpdate[0];
$salesCalculated[$i][1] = $sales[$i][1];
if($sales[$i][3] == "" && $sales[$i][4] == ""){
$salesCalculated[$i][2] = $sales[$i][2] * 1;
}elseif($sales[$i][3] == ""){
$salesCalculated[$i][2] = $sales[$i][2] - ($sales[$i][4] / $sales[$i][1]);
}elseif($sales[$i][4] == ""){
$salesCalculated[$i][2] = $sales[$i][2] - ($sales[$i][2] / 100 * $sales[$i][3]);
}
$salesCalculated[$i][3] = $sales[$i][5];
}
//Add element for every item
$count = 0;
$salesScatter = [];
for($i = 0; $i < count($salesCalculated); $i++){
for($j = 0; $j < $salesCalculated[$i][1]; $j++){
$salesScatter[$count] = [];
$salesScatter[$count][0] = $salesCalculated[$i][0];
$salesScatter[$count][1] = $salesCalculated[$i][2];
$salesScatter[$count][2] = $salesCalculated[$i][3];
$count++;
}
}
//Get average and split date
$count = 0;
$mydata = [];
for($i = 0; $i < count($salesScatter); $i++){
$sum = 0;
$num = 0;
for($j = 0; $j < count($salesScatter); $j++){
if($salesScatter[$i][0] == $salesScatter[$j][0]){
$sum += $salesScatter[$j][1];
$num++;
}
}
$mydata[$count] = [];
$mydata[$count][0] = explode("-", $salesScatter[$i][0]);
$mydata[$count][1] = $salesScatter[$i][1];
$mydata[$count][2] = $sum / $num;
$mydata[$count][3] = $salesScatter[$i][2];
$count++;
}
return $mydata;
}
function getProductSales($product_id){
global $adb;
$mydata = getChartData($product_id);
$file = fopen("/var/www/html/vtigercrm/include/data.json", "w");
fwrite($file, json_encode($mydata));
fclose($file);
//Data to send to Smarty
$highest = 0;
$average = 0;
$lowest = $mydata[0][1];
for($i = 0; $i < count($mydata); $i++){
if($mydata[$i][1] > $highest){
$highest = $mydata[$i][1];
}
$average += $mydata[$i][1];
if($mydata[$i][1] < $lowest){
$lowest = $mydata[$i][1];
}
}
$average /= count($mydata);
$product = $adb->run_query_record("SELECT CONCAT(product_no, ' (', productname, ')'), unit_price " .
"FROM vtiger_products WHERE productid = " . $product_id);
$product_details = [ 'name'=>$product[0], 'unit'=>$product[1], 'highest'=>$highest, 'average'=>$average, 'lowest'=>$lowest];
return $product_details;
}
?>
.tpl
{strip}
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'include/getProductSales.php',
data: { id: {php}echo $_GET['record'];{/php} ,
maxAmount:$("#maxAmount").val(),
minAmount:$("#minAmount").val()
},
complete: function(){
drawChart();
}
});
});
});
</script>
<script src="resources/priceChart.js"></script>
<form>
<table class="table table-bordered equalSplit detailview-table">
<thead>
<tr>
<th class="blockHeader" colspan="4">
<img class="cursorPointer alignMiddle blockToggle hide" src="layouts/vlayout/skins/alphagrey/images/arrowRight.png" data-mode="hide" data-id="31">
<img style="display: inline;" class="cursorPointer alignMiddle blockToggle" src="layouts/vlayout/skins/alphagrey/images/arrowDown.png" data-mode="show" data-id="31">
Details
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Product</label>
</td>
<td class="fieldValue medium">{$PRODUCT['name']}</td>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">List Price</label>
</td>
<td class="fieldValue medium">{$PRODUCT['unit']}</td>
</tr>
<tr>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Highest Price</label>
</td>
<td class="fieldValue medium">{$PRODUCT['highest']}</td>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Max. Amount</label>
</td>
<td class="fieldValue medium"><input type="text" name="maxAmount" id="maxAmount"></td>
</tr>
<tr>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Average Price</label>
</td>
<td class="fieldValue medium">{$PRODUCT['average']}</td>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Min. Amount</label>
</td>
<td class="fieldValue medium"><input type="text" name="minAmount" id="minAmount"></td>
</tr>
<tr>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Lowest Price</label>
</td>
<td class="fieldValue medium">{$PRODUCT['lowest']}</td>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px"></label>
</td>
<td class="fieldValue medium"><input name="submit" type="submit" value="Filter"></td>
</tr>
</tbody>
</table>
</form>
<style>
#chart_div{
margin: 20px 0px;
background-color: white;
min-height: 450px;
-webkit-box-shadow: 4px 4px 15px 0px rgba(50, 50, 50, 0.3);
-moz-box-shadow: 4px 4px 15px 0px rgba(50, 50, 50, 0.3);
box-shadow: 4px 4px 15px 0px rgba(50, 50, 50, 0.3);
}
</style>
<div id="chart_div" ></div>
{/strip}
.js
google.charts.setOnLoadCallback(drawChart);
//check window size
if (document.addEventListener)
{
window.addEventListener("resize", drawChart);
}
else if (document.attachEvent)
{
window.attachEvent("onresize", drawChart);
}
else
{
window.resize = drawChart;
}
function drawChart() {
var jsonData = $.ajax({
url: "include/getChartdata.php",
dataType: "json",
async: false
}).responseText;
var mydata = $.parseJSON(jsonData);
console.log(mydata);
var data = new google.visualization.DataTable();
data.addColumn("datetime", "Date");
data.addColumn("number", "Price");
data.addColumn({type : "string", role : "tooltip"});
data.addColumn("number", "Price (Average)");
data.addColumn({type : "string", role : "tooltip"});
var s = mydata.length;
if(s == 0){
alert("There is no data in the range you selected. Please select another range.");
}
for(var i = 0; i < s; i++ ){
data.addRow([new Date(mydata[i][0][0], mydata[i][0][1]-1, mydata[i][0][2]), mydata[i][1], mydata[i][3] + " " + mydata[i][1], mydata[i][2], 'Average of : ' + mydata[i][2]]);
}
var min = new Date(mydata[0][0][0], mydata[0][0][1]-1, mydata[0][0][2]);
min.setDate(min.getDate() - 7);
var max = new Date(mydata[s-1][0][0], mydata[s-1][0][1]-1, mydata[s-1][0][2]);
max.setDate(max.getDate() + 7);
var options = {
chartArea:{width:"80%",height:"70%"},
hAxis: {
title: "Date",
viewWindow: {
min: min,
max: max
},
gridlines: {
count: -1,
units: {
days: {
format: ["MMM dd"]
},
}
},
},
vAxis: {
title: "Price",
minValue: 0
},
legend: "none",
series: {
0: {
pointSize: 10,
dataOpacity: 0.6,
pointShape: "diamond"
},
1: {
lineWidth: 2,
color: "#509C49",
pointSize: 2
}
}
};
var chart = new google.visualization.ScatterChart(document.getElementById("chart_div"));
chart.draw(data, options);
}
Why are you saving this file? Change $_POST to $_GET and make your urls and user input send parameters to the PHP. Then PHP runs the query to get the data from the DB, encodes it through JSON and returns to user, no saving into file needed. I see you're using jQuery, so $.getJSON should work for you just fine. You're writing stuff you don't need. I'm in a hurry i will explain better if needed when tonight.