Input size value to database PHP - php

I have no idea where to get size value and input it to my database
this is my database table called transaksi with these column
idtransaksi, noinvoice, idproduk, size, jumlah
and here is my script
chart.php
<?php
if (!isset($_SESSION)) {
session_start();
}
cek_status_login($_SESSION['idpelanggan']);
include ('chart.inc.php');
// Process actions
$chart = isset ($_SESSION['chart']) ? $_SESSION['chart'] : '';
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'add' :
if ($chart) {
$chart .= ',' . $_GET['id'];
} else {
$chart = $_GET['id'];
}
break;
//
//B002,5,S,B003,10,M
case 'delete' :
if ($chart) {
$items = explode(',', $chart);
$newchart = '';
foreach ($items as $item) {
if ($_GET['id'] != $item) {
if ($newchart != '') {
$newchart .= ',' . $item;
} else {
$newchart = $item;
}
}
}
$chart = $newchart;
}
break;
case 'update' :
if ($chart) {
$newchart = '';
foreach ($_POST as $key => $value) {
if (stristr($key, 'qty')) {
$id = str_replace('qty', '', $key);
$items = ($newchart != '') ? explode(',', $newchart) : explode(',', $chart);
$newchart = '';
foreach ($items as $item) {
if ($id != $item) {
if ($newchart != '') {
$newchart .= ',' . $item;
} else {
$newchart = $item;
}
}
}
for ($i = 1; $i <= $value; $i++) {
if ($newchart != '') {
$newchart .= ',' . $id;
} else {
$newchart = $id;
}
}
}
}
}
$chart = $newchart;
break;
}
$_SESSION['chart'] = $chart;
?>
<section class="main-content">
<div class="row">
<div class="span9">
<?php echo writeShoppingchart();
echo showchart();
if (isset($_GET['s'])) {
if ($_GET['status'] == OK) {
echo "proses pembelian berhasil dilakukan sudah selesai";
} else {
echo "operasi gagal";
}
}
?>
</div>
<script type="text/javascript">
$('.input').on('input',function(e){
if($(this).data("lastval")!= $(this).val()){
$(this).data("lastval",$(this).val());
//change action
alert('Anda Mengubah Jumlah SubTotal barang, Silahkan Update Keranjang Belanja');
};
});
</script>
<?php
include ('inc/sidebar-front.php');
?>
</div>
</section>
chart.inc.php
<?php
function kd_transaksi() {
$kode_temp = fetch_row("SELECT noinvoice FROM invoice ORDER BY noinvoice DESC LIMIT 0,1");
if ($kode_temp == '')
$kode = "E00001";
else {
$jum = substr($kode_temp, 1, 6);
$jum++;
if ($jum <= 9)
$kode = "E0000" . $jum;
elseif ($jum <= 99)
$kode = "E000" . $jum;
elseif ($jum <= 999)
$kode = "E00" . $jum;
elseif ($jum <= 9999)
$kode = "E0" . $jum;
elseif ($jum <= 99999)
$kode = "E" . $jum;
else
die("Kode pemesanan melebihi batas");
}
return $kode;
}
function writeShoppingchart() {
$chart = $_SESSION['chart'];
if (!$chart) {
return '<h4 class="title"><span class="text pull-left"><strong>Keranjang Belanja Masih Kosong</strong></span></h4>';
} else {
// Parse the chart session variable
$items = explode(',', $chart);
$s = (count($items) > 1) ? 's' : '';
return '<h4 class="title"><span class="text pull-left"><strong>Periksa Jumlah Pesanan Anda Sebelum Check Out</strong></span></h4>';
}
}
function chartNotification() {
$chart = $_SESSION['chart'];
if (!$chart) {
return '0';
} else {
// Parse the chart session variable
$items = explode(',', $chart);
return count($items);
}
}
function getQty() {
$chart = $_SESSION['chart'];
if (!$chart) {
return 0;
} else {
// Parse the chart session variable
$items = explode(',', $chart);
$s = (count($items) > 1) ? 's' : '';
return count($items);
}
}
function showchart() {
$chart = $_SESSION['chart'];
// print_r($chart);
if ($chart) {
$items = explode(',', $chart);
$contents = array();
$total='';
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = "<table class=\"table table-striped \">";
$output[] = "<th><td>Nama</td><td>size</td><td> Harga</td><td>jumlah</td><td>diskon</td><td>subtotal</td><td>Aksi</td></th>";
$output[] = '<form action="index.php?mod=chart&pg=chart&action=update" method="post" id="chart">';
$no = 1;
foreach ($contents as $id => $qty) {
$sql = "SELECT produk.*, stok.harga_barang, stok.harga_jual, stok.jumlah, stok.ext_disc, stok.disc, stok.size FROM stok LEFT OUTER JOIN produk ON stok.idproduk = produk.idproduk WHERE produk.idproduk = '$id'";
$result = mysql_query($sql);
$row = mysql_fetch_object($result);
$size = explode(',', $row->size);
$quantity = ($row->jumlah);
$diskonext =(($row->harga_jual)*($row->ext_disc)/100);
$output[] = '<tr><td>' . $no . '</td>';
$output[] = '<td>'.$row ->nama_produk. '<br /><img src=\'upload/produk/' . $row ->foto .' \' width=\'100px\' height=\'100px\'></td>';
$output[] = '<td><select name="size" style="width:50px;">';
for ($i = 0; $i < count($size); $i++){
$output[] = '<option value="'. $size[$i] .'">'. $size[$i] .'</option>';
}
$output[] = '</select></td>';
$output[] = '<td>' . format_rupiah($row -> harga_barang) . '</td>';
if ($qty >= 10){
$total += (($row -> harga_jual) - $diskonext) * $qty;
}else {
$total += $row -> harga_jual * $qty;
}
if ($qty > $quantity){
$output[] = '<td><input type="text" class="input-mini" name="qty' . $id . '" value="'.$quantity.'"/><br /><span class="label label-warning pull-right">Stok hanya '.$quantity.'</span></td>';
} else {
$output[] = '<td><input type="text" onkeypress="alert(\'jumlah barang terganti, silahkan Update Keranjang belanja anda sebelum chekout\');" class="input-mini" name="qty' . $id . '" value="' . $qty . '"/></td>';
}
if ($qty >= 10){
$output[] = '<td>' . $row->disc . ' % + '. $row -> ext_disc .'% </td>';
} else {
$output[] = '<td>' . $row->disc . ' %</td>';
}
if ($qty >= 10){
if ($qty > $quantity){
$output[] = '<td>'.format_rupiah(($row->harga_jual - $diskonext)*$quantity).'</td>';
} else {
$output[] = '<td>'.format_rupiah(($row->harga_jual - $diskonext)*$qty).'</td>';
}
}else{
if ($qty >= $quantity){
$output[] = '<td>'.format_rupiah($row->harga_jual*$quantity).'</td>';
} else {
$output[] = '<td>'.format_rupiah($row->harga_jual*$qty).'</td>';
}
}
$output[] = '<td>Hapus</td></tr>';
$no++;
}
$output[] = '<tr><td colspan=\'6\' ><h4>Total Belanja Anda</h4></td><td colspan=\'2\'><h4>'. format_rupiah($total) .'</h4></td></tr>';
$output[] = "</table>";
$qty = getQty();
$_SESSION['totalbayar'] = $total;
$output[] = '<button type="submit" class=\'btn btn-primary\'>Update Keranjang Belanja</button>';
if ($qty >= ($row->jumlah)){
$output[] ='<button type="submit" class=\'btn btn-success pull-right\'>Update Keranjang Belanja Anda</button>';
} else {
$output[] ='<a href=\'chart/chart_action.php\' class=\'btn btn-success pull-right\'>Check out</a>';
}
$output[] = '</form>';
} else {
$output[] = '<p>Keranjang belanja masih kosong.</p>';
}
return join('', $output);
}
function insertToDB($kd_transaksi, $idpelanggan, $totalbayar, $sizes) {
$chart = isset($_SESSION['chart'])? $_SESSION['chart']: '';
if ($chart) {
$items = explode(',', $chart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$sql_transaksi = "insert into invoice (noinvoice,tanggal,totalbayar,idpelanggan)
values( '$kd_transaksi', now(),'$totalbayar','$idpelanggan')";
//echo "SQL transaksi:".$sql_transaksi;
mysql_query($sql_transaksi) or die(mysql_error());
foreach ($contents as $id => $qty) {
$sql = "insert into transaksi(noinvoice,idproduk,size,jumlah)
values('$kd_transaksi','$id','$sizes','$qty')";
// echo "SQL transaksi:".$sql;
$result = mysql_query($sql) or die(mysql_error());
}
} else {
$output[] = '<p>Keranjang belanja masih kosong.</p>';
}
}
?>
and chart.action.php
<?php
session_start();
require_once ('../inc/config.php');
require_once ('../inc/function.php');
require_once ('../chart/chart.inc.php');
$idpelanggan=$_SESSION['idpelanggan'];
/* menambahkan kode pesan dan detail pesan kedalam database*/
$kd_transaksi = kd_transaksi();
$total_bayar = $_SESSION['totalbayar'];
insertToDB($kd_transaksi,$idpelanggan,$total_bayar);
//check if query successful
$link="location:../index.php?mod=chart&pg=chart_ship&total_bayar=$total_bayar&kd_transaksi=$kd_transaksi";
header($link);
?>
Still get confused how to input size value to database. and if you need more information to help me just tell me what I have to do
Thanks

The function insertToDB is defined with 4 parameters in the code above:
function insertToDB($kd_transaksi, $idpelanggan, $totalbayar, $sizes) {
But it is called with only 3 values:
insertToDB($kd_transaksi,$idpelanggan,$total_bayar);
So I suggest passing the value posted for variable size when calling the function:
insertToDB($kd_transaksi,$idpelanggan,$total_bayar,$_POST["size"]);
Btw: commenter #giraff is absolutely right when meaning the SQL injection. Your scripts are vulnerable to it. You should definitely check and sanitize user-submitted data!

Related

PHP session variables not persisting on new page after form submission

I have a quiz site which randomly shuffles and puts together multiple choice questions. The correct answers (as well as some other data) are stored in session variables, and the students' answers are sent via POST. On the page that the quiz form submission links to, the correct answers in SESSION are compared to the POST data, and the results of the quiz are displayed. The site used to work just fine, so I have no idea what happened to make it suddenly stop working.
I have checked to see that the session_id is the same on both pages and it is. I have made sure that start_session() is placed appropriately above all the HTML (and have even confirmed it by calling var_dump($_SESSION) on the first and second page, user login variables are displayed, but nothing else).
Here is the code from "startquiz.php" which assembles the quiz form. The session variables in question are just after the end of the "DISPLAY A QUESTION LOOP"
<?php
require_once('appvars.php');
require_once('startsession.php');
require_once('generalauthorize.php');
$page_title = '10 Question Quiz';
require_once('header.php');
require_once('navbar.php');
require_once('connectvars.php');
//=================MySQL HANDLING====================
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$quizcount = count($_GET);
$content_array = [];
foreach($_GET as $quiz_content){
$quiz_content = $quiz_content . ' = 1';
array_push($content_array, $quiz_content);
}
$where_clause = implode(' OR ', $content_array);
$query = 'SELECT * FROM questionbank WHERE ' . $where_clause;
$data = mysqli_query($dbc, $query);
$questions_found = mysqli_num_rows($data);
mysqli_close($dbc);
//==================MySQL HANDLING=======================
if ($questions_found > 9) {
//==========MAKE A LIST OF POSSIBLE QUESTIONS==================
$possible_questions_array = [];
while ($row = mysqli_fetch_array($data)) {
array_push($possible_questions_array, $row);
}
//==========MAKE A LIST OF POSSIBLE QUESTIONS=================
// ============DECIDE WHICH 10 QUESTIONS TO USE=================
$quiz_array = [];
for($i = 0; $i < 10; $i++) {
$question_bank_count = count($possible_questions_array);
$random_question_number = rand(0, ($question_bank_count - 1));
array_push($quiz_array, $possible_questions_array[$random_question_number]);
array_splice($possible_questions_array, $random_question_number, 1);
}
// ============DECIDE WHICH 10 QUESTIONS TO USE=================
//============CREATE QUESTION META DATA ARRAY=================
$quiz_metadata_array = [];
for ($i = 0; $i < count($quiz_array); $i++) {
$question_holder = $quiz_array[$i];
$metadata_only = array_splice($question_holder, 12);
array_push($quiz_metadata_array, $metadata_only);
}
//============CREATE QUESTION META DATA ARRAY=================
echo '<div class="quiz-container">';
echo '<h2 class="mainpagetitles">Good Luck!</h2>';
echo '<br />';
echo '<form role="form" method="post" action="processquiz.php">';
//==============CREATE ARRAYS TO HOLD QUIZ DATA==========
$correct_answers = [];
$question_prompts = [];
//==============CREATE ARRAYS TO HOLD QUIZ DATA==========
//===============DISPLAY A QUESTION LOOP==================
for($i = 0; $i < (count($quiz_array)); $i++){
array_push($question_prompts, $quiz_array[$i]['question']);
//==================ISOLATE THE ANSWERS===============
$answers_array = [];
array_push($correct_answers, $quiz_array[$i]['answer']);
array_push($answers_array, $quiz_array[$i]['answer']);
array_push($answers_array, $quiz_array[$i]['distractor1']);
array_push($answers_array, $quiz_array[$i]['distractor2']);
array_push($answers_array, $quiz_array[$i]['distractor3']);
//==================ISOLATE THE ANSWERS===============
//=================SCRAMBLE THE ANSWERS==============
$scrambled_array = [];
$answer_count = count($answers_array);
for ($j = 0; $j < $answer_count; $j++) {
$random_answer_number = rand(0, (count($answers_array) - 1));
array_push($scrambled_array, $answers_array[$random_answer_number]);
array_splice($answers_array, $random_answer_number, 1);
}
//=================SCRAMBLE THE ANSWERS==============
//====================CREATE THE HTML=================
echo '<h3>Question ' . ($i + 1) . '.</h3>';
echo '<div class="question-container">';
echo '<p class="question">' . $quiz_array[$i]['question'] . '</p>';
//==============LOOP THROUGH THE SCRAMBLED ANSWERS===========
for($k = 0; $k < (count($scrambled_array)); $k++) {
echo '<label for="' . $i . $k . '" class="answer_choice">' . (chr((65 + $k))) . ': </label>';
echo '<input value="' . $scrambled_array[$k] . '" id="' . $i . $k . '" class="answer_choice" type="radio" name="' . $i . '" required><p class="answer_choice"> ' . $scrambled_array[$k] . '</p><br />';
}
//==============LOOP THROUGH THE SCRAMBLED ANSWERS===========
echo '</div>';
echo '<hr>';
//====================CREATE THE HTML=================
}
//===============DISPLAY A QUESTION LOOP==================
echo '<div class="center">';
$_SESSION['correct_answers'] = $correct_answers;
$_SESSION['question_prompts'] = $question_prompts;
$_SESSION['current_quiz'] = $_GET;
$_SESSION['current_quiz_meta'] = $quiz_metadata_array;
echo session_id();
echo '<button type="submit" class="centered-button">Finished!</button>';
echo '</div>';
echo '</form>';
echo '</div>';
} else {
echo '<div class="quiz-container">';
echo '<h2 class="center">Oh no!</h2>';
echo '<h4 class="center">It looks like there aren\'t enough questions in the database to take a quiz for this category yet!</h4>';
echo '<h4 class="center">Talk to your English teachers about adding some more.</h4>';
echo '<h4 class="center">Sorry about that!</h4><br />';
echo '<a class="main_menu_button" href="quizselect.php"> Okay </a>';
echo '</div>';
}
require_once('bootstrapfooter.php');
?>
And here is the code for the quiz processing page. When I insert a var_dump($_SESSION) on this page I get the login variables that are in session, but nothing else.
<?php
require_once('appvars.php');
require_once('startsession.php');
require_once('generalauthorize.php');
$page_title = 'Quiz Results';
require_once('header.php');
require_once('navbar.php');
require_once('connectvars.php');
//=====HAND OFF CURRENT QUIZ KEYWORDS TO LOCAL VARIABLE AND RESET GLOBAL====
$current_quiz = [];
foreach ($_SESSION['current_quiz'] as $key => $value) {
array_push($current_quiz, $value);
}
$_SESSION['current_quiz'] = "";
//=====HAND OFF CURRENT QUIZ KEYWORDS TO LOCAL VARIABLE AND RESET GLOBAL====
//=======UPDATE THE NUMBER OF THIS QUIZ TYPE TAKEN FOR THE USER ===========
$increment_these_quizzes = [];
for ($i = 0; $i < count($current_quiz); $i++) {
if ($current_quiz[$i] == "english_1_1" || $current_quiz[$i] == "english_1_2") {
if (!in_array('english_1_quiz_taken = english_1_quiz_taken + 1', $increment_these_quizzes)) {
$array_insert = 'english_1_quiz_taken = english_1_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
} elseif ($current_quiz[$i] == "english_2ot_1" || $current_quiz[$i] == "english_2ot_2") {
if (!in_array('english_2ot_quiz_taken = english_2ot_quiz_taken + 1', $increment_these_quizzes)) {
$array_insert = 'english_2ot_quiz_taken = english_2ot_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
} elseif ($current_quiz[$i] == "english_2pt_1" || $current_quiz[$i] == "english_2pt_2") {
if (!in_array('english_2pt_quiz_taken = english_2pt_quiz_taken + 1', $increment_these_quizzes)) {
$array_insert = 'english_2pt_quiz_taken = english_2pt_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
} elseif ($current_quiz[$i] == "english_2sw_1" || $current_quiz[$i] == "english_2sw_2") {
if (!in_array('english_2sw_quiz_taken = english_2sw_quiz_taken + 1', $increment_these_quizzes)) {
$array_insert = 'english_2sw_quiz_taken = english_2sw_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
} else {
$array_insert = $current_quiz[$i] . '_quiz_taken = ' . $current_quiz[$i] . '_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
}
$increment_this = implode(', ', $increment_these_quizzes);
$increase_quiz_count_query = "UPDATE memberinfo SET $increment_this WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $increase_quiz_count_query);
mysqli_close($dbc);
//=======UPDATE THE NUMBER OF THIS QUIZ TYPE TAKEN FOR THE USER ===========
//================GET QUESTION COUNT & SCORE QUIZ===========
$score = 0;
$question_count = count($_SESSION['correct_answers']);
for($i = 0; $i < $question_count; $i++) {
$switch = 0;
$keywords = [];
//==============CORRECT ANSWER HANDLING=====================
if ($_POST[$i] == $_SESSION['correct_answers'][$i]) {
$generic_array = [];
$correct_array = [];
$score++;
foreach ($_SESSION['current_quiz_meta'][$i] as $key => $value) {
if ($switch == 1) {
if ($value == 1) {
if ($key == "english_1_1" || $key == "english_1_2") {
if (!in_array('english_1_correct = english_1_correct + 1', $correct_array)) {
$key = 'english_1_correct = english_1_correct + 1';
array_push($correct_array, $key);
}
if (!in_array('english_1_answers = english_1_answers + 1', $generic_array)) {
$gkey = 'english_1_answers = english_1_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2ot_1" || $key == "english_2ot_2") {
if (!in_array('english_2ot_correct = english_2ot_correct + 1', $correct_array)) {
$key = 'english_2ot_correct = english_2ot_correct + 1';
array_push($correct_array, $key);
}
if (!in_array('english_2ot_answers = english_2ot_answers + 1', $generic_array)) {
$gkey = 'english_2ot_answers = english_2ot_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2pt_1" || $key == "english_2pt_2") {
if (!in_array('english_2pt_correct = english_2pt_correct + 1', $correct_array)) {
$key = 'english_2pt_correct = english_2pt_correct + 1';
array_push($correct_array, $key);
}
if (!in_array('english_2pt_answers = english_2pt_answers + 1', $generic_array)) {
$gkey = 'english_2pt_answers = english_2pt_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2sw_1" || $key == "english_2sw_2") {
if (!in_array('english_2sw_correct = english_2sw_correct + 1', $correct_array)) {
$key = 'english_2sw_correct = english_2sw_correct + 1';
array_push($correct_array, $key);
}
if (!in_array('english_2sw_answers = english_2sw_answers + 1', $generic_array)) {
$gkey = 'english_2sw_answers = english_2sw_answers + 1';
array_push($generic_array, $gkey);
}
} else {
$keyword_generic = $key . '_answers = ' . $key . '_answers + 1';
$keyword_correct = $key . '_correct = ' . $key . '_correct + 1';
array_push($generic_array, $keyword_generic);
array_push($correct_array, $keyword_correct);
}
}
$switch = 0;
} else {
$switch = 1;
}
}
$set_what_generic = implode(', ', $generic_array);
$set_what = implode(', ', $correct_array);
$update_query = "UPDATE memberinfo SET $set_what WHERE user_id = $_SESSION[user_id]";
$update_generic_query = "UPDATE memberinfo SET $set_what_generic WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $update_query);
mysqli_query($dbc, $update_generic_query);
mysqli_close($dbc);
//==============CORRECT ANSWER HANDLING=====================
//==============WRONG ANSWER HANDLING=====================
} else {
$generic_array = [];
foreach ($_SESSION['current_quiz_meta'][$i] as $key => $value) {
if ($switch == 1) {
if ($value == 1) {
if ($key == "english_1_1" || $key == "english_1_2") {
if (!in_array('english_1_answers = english_1_answers + 1', $generic_array)) {
$gkey = 'english_1_answers = english_1_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2ot_1" || $key == "english_2ot_2") {
if (!in_array('english_2ot_answers = english_2ot_answers + 1', $generic_array)) {
$gkey = 'english_2ot_answers = english_2ot_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2pt_1" || $key == "english_2pt_2") {
if (!in_array('english_2pt_answers = english_2pt_answers + 1', $generic_array)) {
$gkey = 'english_2pt_answers = english_2pt_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2sw_1" || $key == "english_2sw_2") {
if (!in_array('english_2sw_answers = english_2sw_answers + 1', $generic_array)) {
$gkey = 'english_2sw_answers = english_2sw_answers + 1';
array_push($generic_array, $gkey);
}
} else {
$keyword_generic = $key . '_answers = ' . $key . '_answers + 1';
array_push($generic_array, $keyword_generic);
}
}
$switch = 0;
} else {
$switch = 1;
}
}
$set_what_generic = implode(', ', $generic_array);
$update_generic_query = "UPDATE memberinfo SET $set_what_generic WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $update_generic_query);
mysqli_close($dbc);
}
//===============WRONG ANSWER HANDLING=====================
}
//================GET QUESTION COUNT & SCORE QUIZ===========
//============ADJUST OVERALL TOTALS AND SUCCESS RATES===================
$update_score_query = "UPDATE memberinfo SET score = total_answers * overall_success_rate WHERE user_id = $_SESSION[user_id]";
$increase_totals_query = "UPDATE memberinfo SET total_quizzes_taken = total_quizzes_taken + 1, total_answers = total_answers + $question_count, total_correct = total_correct + $score WHERE user_id = $_SESSION[user_id]";
$adjust_success_query = "UPDATE memberinfo SET overall_success_rate = (total_correct / total_answers) * 100, phys_con_success = (phys_con_correct / phys_con_answers) * 100, abbr_success = (abbr_correct / abbr_answers) * 100, anatomy_success = (anatomy_correct / anatomy_answers) * 100, society_success = (society_correct / society_answers) * 100, career_success = (career_correct / career_answers) * 100, ment_heal_success = (ment_heal_correct / ment_heal_answers) * 100, tools_success = (tools_correct / tools_answers) * 100, other_success = (other_correct / other_answers) * 100, english_1_success = (english_1_correct / english_1_answers) * 100, english_2ot_success = (english_2ot_correct / english_2ot_answers) * 100, english_2pt_success = (english_2pt_correct / english_2pt_answers) * 100, english_2sw_success = (english_2sw_correct / english_2sw_answers) * 100 WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $increase_totals_query);
mysqli_query($dbc, $adjust_success_query);
mysqli_query($dbc, $update_score_query);
//===============UPDATE THE RANKING CHARTS====================
//==========FIRS FLUSH ALL RANKINGS TO 0===================
$flush_rankings = "UPDATE memberinfo SET rank = 0";
mysqli_query($dbc, $flush_rankings);
//==========FIRS FLUSH ALL RANKINGS TO 0===================
//==========NEXT GET ELIGIBLE MEMBERS====================
$get_eligible_scores = "SELECT user_id FROM memberinfo WHERE total_quizzes_taken > 0 AND overall_success_rate >= 40 ORDER BY score DESC, overall_success_rate DESC, total_correct DESC";
$eligible_data = mysqli_query($dbc, $get_eligible_scores);
//==========NEXT GET ELIGIBLE MEMBERS====================
//==========LOOP THROUGH AND UPDATE THE DATABASE=================
$rank_number = 1;
while ($member_data = mysqli_fetch_array($eligible_data)) {
$rank_update_query = "UPDATE memberinfo SET rank = $rank_number WHERE user_id = $member_data[user_id]";
mysqli_query($dbc, $rank_update_query);
$rank_number++;
}
//==========LOOP THROUGH AND UPDATE THE DATABASE=================
//===============UPDATE THE RANKING CHARTS====================
mysqli_close($dbc);
//============ADJUST OVERALL TOTALS AND SUCCESS RATES===================
//=================DISPLAY SCORE & APPROPRIATE MESSAGE=========
echo '<div class="quiz_results">';
echo '<div class="container">';
if ($score == 10) {
echo '<h2 class="center">Perfect Score!!!</h2>';
} else if ($score > 7 && $score < 10) {
echo '<h2 class="center">Well Done!</h2>';
} else if ($score > 5 && $score < 8) {
echo '<h2 class="center">Good!</h2>';
} else if ($score > 3 && $score < 6) {
echo '<h2 class="center">Try a little harder!</h2>';
} else if ($score > 1 && $score < 4) {
echo '<h2 class="center">Oooh. Not good.</h2>';
} else if ($score <= 1) {
echo '<h2 class="center">Seriously? That bad?</h2>';
} else {
echo '<h2 class="center">How\'d you even get this score??</h2>';
}
echo '<h1 class="center">You scored ' . $score . '/' . $question_count . '</h1>';
//=================DISPLAY SCORE & APPROPRIATE MESSAGE=========
//================COMPARE AND DISPLAY ANSWERS=================
?>
<div id="quiz_table_headings" class="row">
<h2 class="col-xs-6">Correct Answer</h2>
<h2 class="col-xs-6">Your Answer</h2>
</div>
<?php
for ($i = 0; $i < $question_count; $i++) {
echo '<div id="quiz_table_question" class="row">';
echo '<p id="quiz_table_question_inner" class="col-xs-12">Question ' . ($i + 1) . ': ' . $_SESSION['question_prompts'][$i] . '</p>';
echo '</div>';
echo '<div id="quiz_table_data" class="row">';
echo '<p id="quiz_table_answer" class="col-xs-6">' . $_SESSION['correct_answers'][$i] . '</p>';
if ($_POST[$i] == $_SESSION['correct_answers'][$i]) {
echo '<p id="quiz_table_correct" class="col-xs-6">' . $_POST[$i] . '</p>';
} else {
echo '<p id="quiz_table_wrong" class="col-xs-6">' . $_POST[$i] . '</p>';
}
echo '</div>';
echo '<hr>';
}
echo '</div>';
//================COMPARE AND DISPLAY ANSWERS=================
//===========CREATE END OF QUIZ LINKS=====================
$replay_url = 'startquiz.php?';
$args_array = [];
for ($i = 0; $i < count($current_quiz); $i++) {
$arg = 'quiz' . $i . '=' . $current_quiz[$i];
array_push($args_array, $arg);
}
$link_args = "";
$link_args = implode('&', $args_array);
$replay_url .= $link_args;
//=============DISPLAY THE BUTTONS=====================
echo '<div class="container">';
echo '<div id="quiz_finish_buttons_row" class="row">';
echo '<div id="quiz_finish_buttons_col" class="col-xs-6">';
echo '<a class="centered-button" href="' . $replay_url . '">Take This Quiz Again</a>';
echo '</div>';
echo '<div id="quiz_finish_buttons_col" class="col-xs-6">';
echo '<a class="centered-button" href="quizselect.php">Back to Quiz Select</a><br />';
echo '</div>';
echo '</div></div>';
echo '</div>';
//=============DISPLAY THE BUTTONS=====================
//===========CREATE END OF QUIZ LINKS=====================
require_once('bootstrapfooter.php');
?>
I apologize for posting the entire code for each page, but I'm not a professional programmer and I'm not sure what is relevant and what isn't.
The problem has been resolved. It turns out the issue was with the php.ini file on the hosting site. They recently made some changes that I was unaware of and the temporary storage location for session files/variables became undefined. Once I edited that information in the .ini file, everything worked just fine.

Styling Dynamically created selection drop box using HTML and CSS. How?

This code is in php file. How I will style tag with "Select Size" and customize the drop down section. Below is one div which i want to style but ht class is created dynamically. And here div drop box are created dynamically and the data entered is also been done dynamically. HELP
$i = 0;
$attribArr = array();
$sizeArr = array();
$colorArr = array();
$colorStr = "color";
$sizeStr = "size";
$phpArray = array(
0 => 001 - 1234567,
1 => 1234567,
2 => 12345678,
3 => 12345678,
4 => 12345678
);
foreach ($order['cart_items'] as $item) {
$i++;
$cssNo = $i % 5;
if ($cssNo == 0) {
$cssNo = 5;
}
$giftcss = "gift-info gift" . $cssNo;
// Get products description
$presult = array();
$productId = $item['product_id'];
$reslt = getProductOptions($productId);
$values = $reslt['values'];
info('option type=' . $reslt['type'] . ' Name=' . $reslt['name']);
$sizeOptionValues = '<option>';
$colorOptionValues = '<option>';
if ($reslt['name'] == 'Size') {
foreach ($values as $value) {
info('vl=' . $value['options_value_name']);
$sizeOptionValues.= str_replace(' ', '', $value['options_value_name']) . '</option><option>';
}
}
if ($reslt['name'] == 'Color') {
foreach ($values as $value) {
info('vl=' . $value['options_value_name']);
$colorOptionValues.= $value['options_value_name'] . '</option><option>';
}
}
$pquery = "SELECT products_description, pr.products_image, products_name FROM "
. TABLE_PRODUCTS_DESCRIPTION . " AS pd JOIN " . TABLE_PRODUCTS . " as pr ON pr.products_id = pd.products_id WHERE pd.products_id=" . $productId;
$presult = $db->Execute($pquery);
$product_name = $presult->fields['products_name'];
$product_image = $presult->fields['products_image'];
$product_desc = $presult->fields['products_description'];
$prodImgs = explode(".", $product_image);
$prodImg0 = $prodImgs[0];
$prodImgExt = $prodImgs[1];
$prod_img_name = $prodImg0 . 'v.' . $prodImgExt;
info("getOrder", "Product Name=" . $product_name . " prod image=" . $prod_img_name);
$prod_desc_url = EL_PROD_DESC_PATH . $productId;
$prodAttrQry = "SELECT * FROM " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " WHERE products_prid = " . $productId . " AND orders_id = " . $orderId;
$attrReslt = $db->Execute($prodAttrQry);
$color = false;
$colorValue = '';
$size = false;
$sizeValue = '';
$personalised = false;
$attr = false;
$personalisedMsg = '';
if ($attrReslt->RecordCount() > 0) {
$attr = true;
$attrArr = array();
while (!$attrReslt->EOF) {
$optName = $attrReslt->fields['products_options'];
$optValue = $attrReslt->fields['products_options_values'];
if ($optName == 'Size') {
$size = true;
$sizeValue = $optValue;
} else if ($optName == 'Color') {
$color = true;
$colorValue = $optValue;
} else if ($optName == '') {
$personalised = true;
$rslt = explode(".", $optValue);
if ((isset($rslt[1]) && $rslt[1] == 'jpg') || (isset($rslt[1]) && $rslt[1] == 'png')) {
$personalisedMsg = "<b>Uploaded Image</b> " . "<br><img style = 'width:200px; height:200px;'src = '$optValue'/>";
} else {
$personalisedMsg = '<b>Personal Message</b><br>' . $optValue;
}
}
$sizeArr[$i] = $sizeValue;
$colorArr[$i] = $colorValue;
$attribArr['personalise_val' . $i] = $personalisedMsg;
$attrReslt->MoveNext();
}
}
$colorVisibility = 'none';
$sizeVisibility = 'none';
$personalisedVisib = 'none';
$headlineVisib = 'none';
if ($color) {
$colorVisibility = 'inline';
$headlineVisib = 'inline';
}
if ($size) {
$sizeVisibility = 'inline';
$headlineVisib = 'inline';
}
if ($personalised) {
$personalisedVisib = 'inline';
}
$secondScreen .= <<
<div class="{$giftcss}">
<input type="hidden" name= "product_id{$i}" value="{$productId}"/>
<div class="gift-img"><img src="http://{$domainName}/gifts/images/{$prod_img_name}" height="250"></div>
<div class="divider"></div><div class="gift-desc"><h3>{$product_name}</h3><span>{$product_desc}</span></div>
<div style="width:100%;"><h3 style="display:{$headlineVisib}">Customize your gift</h3><br>
<p style="display:{$sizeVisibility};">Select Size<select id = "prod_size{$i}" name="prod_size{$i}" >{$sizeOptionValues}</select></p>
<p style="display:{$colorVisibility};">Select Color<select id = "prod_color{$i}" name="prod_color{$i}" >{$colorOptionValues}</select></p>
<p style="display:{$personalisedVisib};">{$personalisedMsg}</p></div>
MARKUP;
$secondScreen .= <<<MARKUP
Im not entirely sure what you mean? But if it's what I think you mean. To print out your php values into the class='' attribute you would:
<div class="<?php echo $giftcss; ?>">
<input type="hidden" name= "product_id<?php echo $i; ?>" value="{$productId}"/>
<div class="gift-img">
<img src="http://<?php echo $domainName; ?>/gifts/images/<?php echo $prod_img_name; ?>" height="250"></div>
Simply <?php echo $variable; ?> into each html attribute.

Custom table sorting not working correct

I am creating a data table that has sortable links but when I click on the link say "username" if i click on that multiple times it makes the url have lots of asc example: http://localhost/riwakawebsitedesigns-website/admin/users/status/ascascascascascascasc it should just be
Sorting Asc http://localhost/riwakawebsitedesigns-website/admin/users/status/asc
And then if click again and so on.
Sorting Desc http://localhost/riwakawebsitedesigns-website/admin/users/status/desc
This here is how pagination looks in url http://localhost/riwakawebsitedesigns-website/admin/users/1
I cannot figure out why each time i click on table head link that it creates so many asc etc. How can I fix it.
What's wrong with sort code. The pagination works fine. Please note I have use codeigniter pagination but not to my liking.
<?php
class Users extends MX_Controller {
public function index() {
$this->getList();
}
public function getList() {
$this->load->library('paginations');
$sort_segment = $this->uri->segment(3);
if (isset($sort_segment)) {
$sort = $sort_segment;
} else {
$sort = 'username';
}
$order_segment = $this->uri->segment(3);
if (isset($order_segment)) {
$order = $order_segment;
} else {
$order = 'asc';
}
$page_segment = $this->uri->segment(4);
if (isset($page_segment)) {
$page = $page_segment;
} else {
$page = 1;
}
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['title'] = "Users";
$this->load->model('admin/user/model_user');
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'date_added' => $result['date_added'],
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'])
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = "1";
$paginations->url = site_url('admin/users' .'/'. $url .'/'. '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}
Thanks so much to #AdrienXL which gave me the idea what problem was.
I now have fixed it. I had doubled up on my page and sort and orders $_GET. So there for i have now just used uri segments and removed the doubled up code and change a couple of things in model
For people who do not want to use codeigniter pagination class.
You can use my example:
My Users:
<?php
class Users extends MX_Controller {
public function index() {
$this->load->library('paginations');
$this->load->model('admin/user/model_user');
// Sort
if (null !==($this->uri->segment(3))) {
$sort = $this->uri->segment(3);
} else {
$sort = 'username';
}
// Order
if (null !==($this->uri->segment(4))) {
$order = $this->uri->segment(4);
} else {
$order = 'asc';
}
// Page
if (null !==($this->uri->segment(3))) {
$page = $this->uri->segment(3);
} else {
$page = 1;
}
$url = '';
// Sort
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
// Order
if (null !==($this->uri->segment(4))) {
$url .= $this->uri->segment(4);
}
// Page Number
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'status' => ($result['status'] ? "Enabled" : "Disabled"),
'date_added' => date(strtotime($result['date_added'])),
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'] . $url)
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = $admin_limit;
$paginations->url = site_url('admin/users' .'/'. $url . '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My View
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?php if ($sort == 'username') { ?>
Username
<?php } else { ?>
Username
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'status') { ?>
Status
<?php } else { ?>
Status
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'date_added') { ?>
Date Added
<?php } else { ?>
Date Added
<?php } ?></td>
<td class="text-right">Action</td>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) { ?>
<tr>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['status'];?></td>
<td><?php echo $user['date_added'];?></td>
<td><a href="<?php echo $user['edit'];?>">Edit</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="row">
<div class="col-sm-6 text-left"><?php echo $pagination; ?></div>
<div class="col-sm-6 text-right"><?php echo $results; ?></div>
</div>
</div>
Model Function
public function getUsers($data = array()) {
$sql = "SELECT * FROM `" . $this->db->dbprefix . "user`";
$sort_data = array(
'username',
'status',
'date_added'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY username";
}
if (isset($data['order']) && ($data['order'] == 'desc')) {
$sql .= " desc";
} else {
$sql .= " asc";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->result_array();
}
Routes:
$route['admin/users'] = "admin/user/users/index";
$route['admin/users/edit/(:any)'] = "admin/user/users/edit/$1";
$route['admin/users/(:any)'] = "admin/user/users/index/$1";
$route['admin/users/(:any)/(:any)/(:any)'] = "admin/user/users/index/$1/$2/$3";
Custom Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}

Build one object from foreach loop

I want to take an array I build from a result set, encode it and then put it into a single object. My problem is I am making a lot of objects, but I want all my data to be in one object. The problem is that I echo out multiple objects from my json encode on my foreach loop. How would I take all that data I get out of that foreach loop and put it into one object? Any help is appreciated. Below is my code. Basically, what I need is this.
{"item1":"itemdata","category":"mycategory"}
but all in one object. I don't want multiple {} {} {}
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
Create an array to hold the smaller arrays before your loop.
$fullData = array();
Then, inside your loop after you finish your build array add the build array to the fullData array.
$fullData[] = $build;
remove your current json_encode() and then, outside the loop.
echo json_encode($fullData);
This is what it would be changed to:
<?php
$counter = 0;
$itemID = '';
$fullData = array();
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
$fullData[] = $build;
}
echo json_encode($fullData);
?>
Change this
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
To
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build[] = array('bid'=>$bid,'id'=>$ID,'item_desc'=>$description);
}
$itemID = $result['item_id'];
$counter++;
}
echo json_encode($build);

html as php variable not rendered properly

Having the following method
public function printDropdownTree($tree, $r = 0, $p = null) {
foreach ($tree as $i => $t) {
$dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) . ' ';
printf("\t<option value='%d'>%s%s</option>\n", $t['id'], $dash, $t['name']);
if ($t['parent'] == $p) {
// reset $r
$r = 0;
}
if (isset($t['_children'])) {
$this->printDropdownTree($t['_children'], ++$r, $t['parent']);
}
}
}
which prints out nested select options and which works fine. But I would like to return the result as variable and I was trying to achieve this like
public function printDropdownTree($tree, $r = 0, $p = null) {
$html = "";
foreach ($tree as $i => $t) {
$dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) . ' ';
$html .= '<option value="'.$t['id'].'">'.$dash.''.$t['name'].'</option>';
if ($t['parent'] == $p) {
// reset $r
$r = 0;
}
if (isset($t['_children'])) {
$this->printDropdownTree($t['_children'], ++$r, $t['parent']);
}
}
return $html;
}
but the $dash won't get rendered
The simple solution: You have to fetch the result of the recursive calls of the function!
public function printDropdownTree($tree, $r = 0, $p = null) {
$html = "";
foreach ($tree as $i => $t) {
$dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) . ' ';
$html .= '<option value="'.$t['id'].'">'.$dash.''.$t['name'].'</option>';
if ($t['parent'] == $p) {
// reset $r
$r = 0;
}
if (isset($t['_children'])) {
$html .= $this->printDropdownTree($t['_children'], ++$r, $t['parent']);
}
}
return $html;
}

Categories