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";
Related
I'm continuing my previous question.
Now I need to insert the value to DB. But ID inserted is not correct as on my database master.
$qModel = oci_parse($c1, "SELECT MODELID, MODEL_NAME FROM WA_LFO_TBL_MODEL
WHERE ACTIVE = 'Y'");
oci_execute($qModel);
while($dModel = oci_fetch_array($qModel))
{
$qDtl2 = oci_parse($c1, "SELECT * FROM WA_LFO_TBL_MODEL_CONFIGURATION WHERE MODELID_FK = '" . $dModel['MODELID'] . "'");
oci_execute($qDtl2);
while($dDtl2 = oci_fetch_array($qDtl2))
{
$q = oci_parse($c1, "SELECT * FROM WA_LFO_TBL_REJECT_PROCESS WHERE MODELID_FK = '" . $dModel['MODELID'] . "' ORDER BY SORT_NO ASC");
oci_execute($q);
while($d = oci_fetch_array($q))
{
$idkeys[] = $d['RP_ID'];
$keys[] = $d['RP_NAME'];
}
$values = array_fill(0, count($keys), 0);
$values = array_combine($keys, $values);
for($i = $readRowAfter; $i < count($linesReject); $i++)
{
// if the fileReject is "Tue, Sep 18<tab>2018<tab>23:59:53<tab>"
$dateobjReject = DateTime::createFromFormat($createFromFormat, $linesReject[$i]);
// check if date is in your Timespan
if($dateobjReject < $toDateTime && $dateobjReject > $fromDateTime)
{
$rowsintimespanReject++; // count if in timespan
$lineContent = explode("\t", $linesReject[$i]);
// loop through line elements and count them
$x = 0;
for ($j = 0; $j < count($keys); $j++) {
if (!isset($lineContent[$j])) {
continue;
}
// remember position of last not empty column
if (trim($lineContent[$j]) != '') {
$x = $j;
}
}
if ($x > 0) {
$values[$keys[$x]]++;
}
}
}
$i = 0;
$sql = "";
foreach ($values as $value)
{
if($value != 0)
{
$sql = oci_parse($c1,"INSERT INTO WA_LFO_TBL_REJECT_OUTPUT(MODELID_FK, QUANTITY, RPID_FK, CONFIGURATIONID_FK)VALUES('" . $dModel['MODELID'] . "', '" . $value . "', '" . $idkeys[$i] . "', '" . $dDtl2['CONFIGURATIONID'] . "')");
oci_execute($sql);
}
$i++;
}
}
}
As you can see that I'm trying to insert the date on foreach function.
But inserted data for ID is not correct for RPID_FK.
I realize maybe something wrong with the code, tried to get the solution but still stuck on it.
Is something wrong on that code?
Hello I am trying to push in an array using array_push but I am getting the value of the first index then after that all I am getting a null response, I am not getting where I have done a mistake.I am getting the values properly but in array_push there is some mistake which is in for loop.
Here is my code :
function actioncouponcsv_download() {
$this->layout = false;
foreach (Yii::app()->log->routes as $route) {
if ($route instanceof CWebLogRoute || $route instanceof CFileLogRoute || $route instanceof YiiDebugToolbarRoute) {
$route->enabled = false;
}
}
$dateRange = json_decode($_POST['dateRange'], true);
$start = $dateRange['start'];
$end = $dateRange['end'];
$validity = $_POST['validity'];
$limit = isset($_REQUEST['limit']) && trim($_REQUEST['limit']) ? $_REQUEST['limit'] : 0;
$studio_id = Yii::app()->user->studio_id;
if (isset($_GET['type']) && intval($_GET['type']) ==2) {
$couponobj = new CouponSubscription();
$getcouponobj = $couponobj->getcoupon_data($studio_id,$start,$end,$validity);
$k = 0;
$title_addon = "\t" . "Discount Cycle" . "\t" . "Extend free trail";
$data_addon = "\t" . $getcouponobj[$k]['discount_multiple_cycle'] . "\t" . $getcouponobj[$k]['extend_free_trail'];
} else {
$title_addon = "";
$data_addon = "";
$couponobj = new Coupon();
$getcouponobj = $couponobj->getcoupon_data($studio_id,$limit,1);
}
//$Coupon = Coupon::model()->find('studio_id=:studio_id', array(':studio_id' => $studio_id));
$dataCsv = '';
if ($getcouponobj) {
$headings = "Sl no" . "\t" . "Coupon" . "\t" . "Coupon Type" . "\t" . "Used by a single user" . "\t" . "Valid" . "\t" . "Used" . "\t" . "User" .$title_addon. "\t" . "Used Date". "\t" . "Content Category". "\t" . "Content"."\n";
$i = 1;
$dataCSV[] = Array();
$j = 0;
for ($k = 0; $k < count($getcouponobj); $k++) {
$userList = '-';
if ($getcouponobj[$k]['used_by'] != '0') {
if ($getcouponobj[$k]['coupon_type'] == 1) {
$userList = '';
$userIdList = explode(",", $getcouponobj[$k]['used_by']);
foreach ($userIdList as $userIdListKey => $userIdListVal) {
if ($userIdListKey == 0) {
$userList .= Yii::app()->webCommon->getuseremail($userIdListVal);
} else {
$userList .= " | " . Yii::app()->webCommon->getuseremail($userIdListVal);
}
}
} else {
$userList = Yii::app()->webCommon->getuseremail($getcouponobj[$k]['used_by']);
}
}
if($getcouponobj[$k]['is_all']!=1){
if($getcouponobj[$k]['content_category']==1){
$cont_cat = "Digital";
$content_str = Coupon::model()->getContentInfo($getcouponobj[$k]['specific_content']);
$cont_str = $content_str;
}else if($getcouponobj[$k]['content_category']==2){
$cont_cat = "Physical";
$content_str = Coupon::model()->getContentInfoPhysical($getcouponobj[$k]['specific_content']);
$cont_str = $content_str;
}else{
$cont_cat = "All";
$cont_str = "All";
}
}else{
$cont_cat = "All";
$cont_str = "All";
}
#echo $getcouponobj[$k]['coupon_code'];
array_push($dataCSV[$j],$i);
array_push($dataCSV[$j],$getcouponobj[$k]['coupon_code']);
array_push($dataCSV[$j],(($getcouponobj[$k]['coupon_type'] == 1) ? 'Multi-use' : 'Once-use'));
array_push($dataCSV[$j],(($getcouponobj[$k]['user_can_use'] == 1) ? 'Multiple times' : 'Once'));
array_push($dataCSV[$j],(($getcouponobj[$k]['used_by'] == 0) ? 'Yes' : 'No'));
array_push($dataCSV[$j],(($getcouponobj[$k]['used_by'] == 0) ? '-' : 'Yes'));
array_push($dataCSV[$j],$userList);
array_push($dataCSV[$j],$getcouponobj[$k]['discount_multiple_cycle']);
array_push($dataCSV[$j],$getcouponobj[$k]['extend_free_trail']);
array_push($dataCSV[$j],(($getcouponobj[$k]['cused_date'] == 0) ? '-' : $getcouponobj[$k]['cused_date']));
array_push($dataCSV[$j],$cont_cat);
array_push($dataCSV[$j],$cont_str);
$j++;
//$dataCsv .= $i . "\t" . $getcouponobj[$k]['coupon_code'] . "\t" . (($getcouponobj[$k]['coupon_type'] == 1) ? 'Multi-use' : 'Once-use') . "\t" . (($getcouponobj[$k]['user_can_use'] == 1) ? 'Multiple times' : 'Once') . "\t" . (($getcouponobj[$k]['used_by'] == 0) ? 'Yes' : 'No') . "\t" . (($getcouponobj[$k]['used_by'] == 0) ? '-' : 'Yes') . "\t" . $userList .$data_addon. "\t" . (($getcouponobj[$k]['cused_date'] == 0) ? '-' : $getcouponobj[$k]['cused_date'])."\t" .$cont_cat ."\t".$cont_str."\n";
$i = $i+1;
}
}
print_r(json_encode($dataCSV));
}
PS: I am getting the values. Any help will be highly appreciated.
Well, first thing i see wrong is the way you declare your array:
$dataCSV[] = Array();
$array[] = Means that you are adding a new value to an existing array. To declare your array you should use
$dataCSV = array();
Also, this code:
array_push($dataCSV[$j],$i);
means that you are adding a new value to your $dataCSV[$j] array, but this is never declared as an array, so first thing would be to do
$dataCSV[$j] = new array();
Your code is really long and complicated, those are only examples of issues i see in there.
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 want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));
I'm trying to figure out how to write a statement in my first CI app (and only second PHP app ever) and I'm stuck.
I have a junction table that holds book_id and user_id from their respective tables. I want to find out who has read a book and echo that back out, but I need the formatting to make sense. Here is the query:
$readQuery = $this->db->get_where('books_users', array('book_id' => $isbn));
And here's my logic for one person
// Get my user info
$user = $this->ion_auth->get_user();
// Tell me who has read it.
$this->db->select('user_id');
$readQuery = $this->db->get_where('books_users', array('book_id' => $isbn));
// If only one person has read it
if ($readQuery->num_rows() == 1) {
$readResult = $readQuery->row();
// And if that person was me...
if ($readResult->user_id == $user->id) {
$message = 'You have read this.';
// If it was someone else...
} else {
$reader = $this->ion_auth->get_user($readResult->user_id);
$message = "$reader->first_name $reader->last_name has read this";
}
// If two people have read it
}
So I'm good if only one person has read it. But when two people have read it, I want it to say "Name One and Name Two have read this." if the logged in person hasn't read it. If they're one of the two people, it should say "You and Name Two have read this".
And so on for 3-5. If 3-5 people have read it, the options would be "Name One, Name Two, and Name Three have read this" or "You, Name Two, and Name Three have read this." up to five people
And if it's 6 or more, it should just say the names of two of them, IE "You, Name Two, and 5 other people have read this."
I considered doing a conditional for each instance and then pushing all of the users to an array. Then I could use in_array() to see if the logged-in user has read it and try to report back, but I'm just having some trouble working up the logic.
Is there an easier way?
Thanks much in advance,
Marcus
I'd say use a switch statement with ranges. You'll have to do a bit of acrobatics to handle the issue of including "You" or not. The code below is untested but give you the general idea.
$message = "";
$readers = array();
$me_included = 0; // Counter increment if you're included in the reader list
$this->db->select('user_id');
$readQuery = $this->db->get_where('books_users', array('book_id' => $isbn));
foreach ($readQuery->result() as $row) {
if ($row->user_id == $user->id) {
$message = "You";
$me_included = 1;
} else {
$readers[] = $this->ion_auth->get_user($row->user_id);
}
}
$reader_count = $sizeof($readers) + $me_included;
switch(TRUE)
{
// One reader, not you
case( ($reader_count == 1) && ($me_included == 0) ):
$message .= $readers[0]->first_name . " " . $readers[0]->last_name . " has read this.";
break;
// Only you
case( ($reader_count == 1) && ($me_included == 1) ):
$message .= " have read this.";
break;
// Two readers
case( ($reader_count == 2) ):
for ($i = 0; $i <= sizeof($readers); $i++) {
if ($i == sizeof($readers)) {
$message .= " and ";
}
$message .= $readers[i]->first_name . " " . $readers[i]->last_name;
}
$message .= " have read this.";
break;
case( ($reader_count > 3) && ($reader_count < 6) ):
if ($me_included) {
$message .= ", ";
}
for ($i = 0; $i <= sizeof($readers); $i++) {
if ($i == sizeof($readers)) {
$message .= " and ";
}
$message .= $readers[i]->first_name . " " . $readers[i]->last_name;
if ($i != sizeof($readers)) {
$message .= ", ";
} else {
$message .= " have read this.";
}
}
break;
case( ($reader_count > 6) ):
if ($me_included) {
$message .= ", " . $readers[0]->first_name . " " . $readers[0]->last_name . " and " . ($reader_count - 2) . " others have read this.";
} else {
for ($i = 0; $i <= 1; $i++) {
$message .= $readers[0]->first_name . " " . $readers[0]->last_name . ", " . $readers[1]->first_name . " " . $readers[1]->last_name . " and " . ($reader_count - 2) . " others have read this.";
}
break;
}
$users = array();
while($row)
{
if(currentuser)
{
array_unshift($users,'You')
}
else
{
$users[] = row[name]
}
}
$count = $max = count($users);
if($max >= 6)
{
$max = 2;
}
$str = '';
for($i=0;$i<$max;$i++)
{
$str .= ($str == '' ? '' : ($i == $count-1 && $count < 6 ? ' And ' : ', ') ) . $users[$i];
}
if($count >= 6)
{
$str .= ' and '.$count-2.' others'
}
This should help you along. It's pretty much pseudo-code but the logic is there to achieve what you want (I believe). You'd obviously want to not fetch all the rows if you are just showing a number of users but that can easily be accomplished.
There are actually a couple places we can optimize this.
1) In the initial query do a JOIN with the user table so we don't have to query again multiple times just for each name:
$readers = $this->db->select('id', 'first_name', 'last_name')->from('books_users')->join('users', 'books_users.id =users.id', 'left')->where('book_id' => $isbn);
2) Additionally, we can avoid iterating over the entire (potentially large) result set just to see if you read it, by doing a separate query:
$you_read = $this->db->get_where('books_users', array('book_id' => $isbn, 'user_id' => $user->id));
Just for the sake of completeness, here is the final code I used. Hopefully it will be of use to someone.
// Find out who has read this book
// Get the users
$current_user = $this->ion_auth->get_user();
$users = $this->ion_auth->get_users();
// Get the readers
$this->db->select('user_id');
$query = $this->db->get_where('books_users', array('book_id' => $isbn));
// If there were results
$readers = array();
if ($query->num_rows() > 0) {
foreach ($users as $user) {
if ($current_user->id == $user->id) {
array_unshift($readers, 'You');
} else {
$readers[] = $user->first_name . ' ' . $user->last_name;
}
$count = $max = count($readers);
if ($max >= 6) {
$max = 2;
}
$message = '';
for ($i = 0; $i < $max; $i++) {
$message .= ($message == '' ? '' : ($i == ($count - 1) && ($count < 6) ? ' and ' : ', ')) . $readers[$i];
}
if ($count >= 6) {
$message .= ' and ' . ($count - 2) . ' others';
}
$message .= ($count == 1 && !$current_user->id ? ' has ' : ' have ') . 'read this.';
}
} else {
$message = 'Be the first to read this.';
}