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);
Related
I have a form with three fields that I want to read separately from the database
$_POST['wkNumer1'];
$_POST['wkNumer2'];
$_POST['wkNumer3'];
How can I read this data without repeating the same code 3 times? In this code, only the variable $wkNumer value will be change.
<?php
if (isset($_POST['show_diagram'])) {
$goodname = $_POST['htDriver'];
$wkNumer = $_POST['wkNumer1'];
// Table with data
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam("wknumer", $wkNumer);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {
if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}
if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}
?>
You can put the numbers inside an array and iterate through that array to execute the same code.
$goodname = $_POST['htDriver'];
// Add the numbers to an array which we can iterate
$numbers = [
$_POST['wkNumber1'],
$_POST['wkNumber2'],
$_POST['wkNumber3'],
];
// Prepare the statement only once before the loop and reuse it
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish";
$stmt = $conn->prepare($sql);
// Loop through the numbers
foreach ($numbers as $number) {
// Add the current number
$stmt->bindParam("wknumer", $number);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
// Now have everything as you had before
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {
if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}
if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}
How does this work for you?
$workNumbers = array($_POST['wkNumer1'],$_POST['wkNumer2'],$_POST['wkNumer3']);
foreach($workNumbers as $wkNumer){
//Your Code block here
}
I need to output the response from the database in XML. So far I have gotten it to output this:
The outermost tag needs to match the name of the action query, it'll either be <courses> or <students>.
Here is my code:
<?php
require_once('./database.php');
if (isset($_GET['format'])) {
$format = filter_var($_GET['format']);
}
if (isset($_GET['action'])) {
$action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
$tableName = "sk_$action";
}
$query = "SELECT * FROM $tableName";
if (isset($_GET['course'])) {
$course = filter_input(INPUT_GET, 'course');
$query .= " WHERE courseID = :course";
}
function arrayToXml($arr, $i = 1, $flag = false)
{
$sp = "";
for ($j = 0; $j <= $i; $j++) {
$sp .= " ";
}
foreach ($arr as $key => $val) {
echo "$sp<" . $key . ">";
if ($i == 1) echo "\n";
if (is_array($val)) {
if (!$flag) {
echo "\n";
}
arrayToXml($val, $i + 5);
echo "$sp</" . $key . ">\n";
} else {
echo "$val" . "</" . $key . ">\n";
}
}
}
$statement = $db->prepare($query);
$statement->bindValue(':course', $course);
$statement->execute();
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
if ($format == 'json') {
echo json_encode($response);
}
if ($format == 'xml') {
arrayToXml($response, 1, true);
}
I'm pretty new to PHP and have never worked with XML. All help is appreciated. Thanks.
function arrayToXml($arr, $collectionTag, $singleTag) {
$collection = new SimpleXMLElement("<$collectionTag/>");
foreach ($arr as $row) {
$element = $root->addChild($singleTag);
foreach ($row as $tag => $value) {
$element->addChild($tag, $value);
}
}
return $collection;
}
$courses = arrayToXml($response, 'courses', 'course');
echo $courses->asXML();
Tested with PHP 7.1.23. Output:
<?xml version="1.0"?>
<courses>
<course><courseID>cs601</courseID><courseName>Web Application Development</courseName></course>
<course><courseId>cs602</courseId><courseName>Server-Side Application Development</courseName></course>
<course><courseId>cs701</courseId><courseName>Rich Internet Application Development</courseName></course>
</courses>
(I added newlines because by default it doesn't add any.)
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.
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!
I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";