Nested if conditions doesn't work - php

I have nested if conditions on my project but i have a problem;
if(isset($_GET['q']) && isset($_GET['t'])) {
$query = $_GET['q'];
$type = $_GET['t'];
$none_key = FALSE;
if($type = 'singer') {
$singers = $connect->query("SELECT * FROM lyrica_singers WHERE singer_name LIKE '%$query%'");
$control = $singers->rowCount();
if($control > 0) {
$on_page = 24;
$number_singers = $singers->rowCount();
$number_page = ceil($number_singers/$on_page);
$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
if ($page < 1) $page = 1;
if ($page>$number_page) $page = $number_page;
$limit = ($page - 1) * $on_page;
$singers = $connect->query("SELECT * FROM lyrica_singers WHERE singer_name LIKE '%$query%' ORDER BY singer_name ASC LIMIT ".$limit.",".$on_page);
$singer_key = TRUE;
} else {
$none_key = TRUE;
}
}
if($type = 'song') {
$songs = $connect->query("SELECT * FROM lyrica_songs WHERE song_name LIKE '%$query%'");
$control = $songs->rowCount();
if($control > 0) {
$on_page = 24;
$number_songs = $songs->rowCount();
$number_page = ceil($number_songs/$on_page);
$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
if ($page < 1) $page = 1;
if ($page>$number_page) $page = $number_page;
$limit = ($page - 1) * $on_page;
$songs = $connect->query("SELECT * FROM lyrica_songs WHERE song_name LIKE '%$query%' ORDER BY song_name ASC LIMIT ".$limit.",".$on_page);
$song_key = TRUE;
} else {
$none_key = TRUE;
}
}
} else {
$key = TRUE;
}
When I run the code, I am expecting that if one of the'control' variables is bigger than 0 the 'none_key' variable must be equal to 0. When the 'type' varible is 'song' there is no problem but if the 'type' variable is 'singer' then 'none_key' variable printing 1, I think it is running the second if block and becomes 'none_key' 1 because of the second 'control' variable is not bigger than zero.

This is an assignment, it sets $type to the value singer:
if ($type = 'singer') {
You want a comparison, it checks to see if $type equals the value singer:
if ($type == 'singer') {
[Edit] Some people prefer to write this sort of statement with the variable last. This is commonly called a "Yoda condition":
if ('singer' == $type) {
This way, if you screw up and only use one =, you get an error.

Related

Notice: Undefined variable: data in while ($query->fetch_object()) {}

I need help on some codes. This isn't made by me, i just copy a source code to make a website from another developer. I still don't know what is the problem although I have searched all the solutions online, because I am still learning.
<?php
$limit = 5;
$pagination = isset($_GET['pagination']) ? $_GET['pagination'] : "";
if (empty($pagination)) {
$position = 0;
$pagination = 1;
} else {
$position = ($pagination - 1) * $limit;
}
$query = $connect->execute("SELECT pinjam.id_peminjaman, pinjam.id_user,
user.nama_user, pinjam.id_ruang, ruang.nama_ruang, pinjam.id_hari,
hari.nama_hari, pinjam.tgl_pinjam, pinjam.jam_awal,
pinjam.jam_akhir, pinjam.keterangan, pinjam.status
FROM tbl_peminjaman AS pinjam
LEFT JOIN tbl_user AS user ON pinjam.id_user = user.id_user
LEFT JOIN tbl_ruang AS ruang ON pinjam.id_ruang = ruang.id_ruang
LEFT JOIN tbl_hari AS hari ON pinjam.id_hari = hari.id_hari
ORDER BY pinjam.updated_at DESC LIMIT $position, $limit");
$no = 1 + $position;
$check_search = $query->num_rows;
while ($query->fetch_object()) {
if ($data->status == 'DITERIMA') {
$color = "green-text";
} elseif ($data->status == 'DITOLAK') {
$color = "red-text";
} elseif ($data->status == 'MENUNGGU') {
$color = "yellow-text";
} else {
$color = "grey-text";
}
?>
Sorry, i haven't know yet how to modify the undetected variable. So please, help me. Thanks :)
Change this line
while ($query->fetch_object()) {
to this
while ($data = $query->fetch_object()) {

How do I query incomplete input

I want to transform query string like pending, shipped or cancel to number status.
$q = strtolower($keyword);
if($q == 'pen' or $q == 'pend' or $q == 'pending' ) {
$d = 1;
} elseif($q == 'shi' or $q == 'ship' or $q == 'shipped') {
$d = 2;
} elseif($q == 'can' or $q == 'cancel' ) {
$d = 3;
} else {
$d = 4;
}
$query->whereStatus($d);
Current query working fine but too much or. It's possible to do in shorten way?
str_is(query, stringToSearch) will probably be enough:
if (str_is('pen*', $q)) {
$d = 1;
}
Else you could parse them from arrays:
$pendingArray = ['pen', 'pend', 'pending'];
if (in_array($q, $pendingArray)) {
$d = 1;
}
If these are all the conditions you need, you could always use a switch.
$q = strtolower($keyword);
$d = 4;
switch($q) {
case 'pen':
case 'pend':
case 'pending':
case 'pen':
$d = 1;
break;
case 'shi':
case 'ship':
case 'shipped':
$d = 2;
break;
case 'can':
case 'cancel':
$d = 3;
break;
}
$query->whereStatus($d);
If this needs to be called on a model, it could be saved to a Laravel scope function like so:
on Laravel model
public function scopeSearchStatus($query, $keyword) {
/** All the code above **/
}
Then it can be called cleanly anywhere you'd like:
SomeModel::searchStatus($keyword);
You could also try this:
<?php
$q = strtolower($keyword);
$d = (preg_match('/\b(pen|pend|pending)\b/', $q)) ? 1 : 4;
$d = (preg_match('/\b(shi|ship|shipped)\b/', $q)) ? 2 : 4;
$d = (preg_match('/\b(can|cancel|)\b/', $q)) ? 3 : 4;
$query->whereStatus($d);

Distribute array value in table column

I have three column having limit of certain percentage of total.i want to distribute an array of values to three columns in such a manner first check customer 1 then 2 then 3 and start from customer 3,2,1 and again from 1,2,3 etc. And also check each value not crossing column limit.Remaining array value should be distribute in column having large percentage assigned.
Array : $stone_doll_inner_arr = array(1=>'67212','37256','32909','29847','28529','27643','25356','25274','23604','23058','18581');
I tried like
Table
for($m=1;$m<=1;$m++){
for($n=1;$n<=count($stone_doll_inner_arr);$n++){
if ($n % 2 == 0) {
$asc_desc = 'asc';
}else{
$asc_desc = 'desc';
}
//Query
$sql_main_table = "select * from create_nemix_tbl where create_id = '".$getid."' order by percentage ".$asc_desc."";
$qry_main_table = $con->query($sql_main_table);
$num_main_table = $qry_main_table->num_rows;
if ($n % 2 == 0) {
$l = $num_main_table-1;
}else{
$l = 0;
}
while($row_main_table = $qry_main_table->fetch_array()){
$stone_doll_val = $stone_doll_arr[$m];
$stone_doll_val_perc = ($stone_doll_val * $row_main_table['percentage']) / 100;
$pre_existing = isset($customer[$l]) ? array_sum($customer[$l]) : 0;
$first_value = $pre_existing+$stone_doll_inner_arr[$n];
$var = 0;
if ($first_value <= $stone_doll_val_perc){
$customer[$l][] = $stone_doll_inner_arr[$n];
unset($stone_doll_inner_arr[$n]);
$var =1;
}
if($var == 1){
break;
}
}
if ($n % 2 == 0) {
$l--;
}else{
$l++;
}
}
}
echo "<pre>";
print_r($customer);
Table Structure and output of script i wanted

Sum values in each group with a loop

I have a while loop that gives this result:
Userid Point
1 10
1 15
2 5
2 10
3 8
3 2
How can I sum the userid points and output with highest number first, like this:
Userid Point
1 25
2 20
3 10
Is there any "foreach", "for" or any other method that can accomplish such result?
The code:
include ('variables.php');
//Fetch data from matchdata table
$q = "SELECT userid, matchid, homescore, awayscore FROM predictiondata ORDER BY userid ASC";
$r = mysqli_query($mysqli, $q);
while ($row = mysqli_fetch_array($r)) {
//Define predictions
$predhome = $row['homescore'];
$predaway = $row['awayscore'];
//Fetch gameresults
$qres = "SELECT id, homescore, awayscore, bonuspoints FROM matches WHERE id = ".$row['matchid']."";
$rres = mysqli_query($mysqli, $qres);
$result = mysqli_fetch_array($rres);
$homescore = $result['homescore'];
$awayscore = $result['awayscore'];
$bonus = $result['bonuspoints'];
$id = $result['id'];
//Calculate points
if ($homescore == $predhome && $awayscore == $predaway && $homescore != '') { $result_point = $correct_score + $correct_result + $correct_number + $correct_number; }
else if ($homescore == $predhome && $awayscore != $predaway OR $homescore != $predhome && $awayscore == $predaway) { $result_point = $correct_result + $correct_number; }
else if ($predhome > $predaway && $homescore > $awayscore OR $predhome < $predaway && $homescore < $awayscore) { $result_point = $correct_result; }
else if (is_null($predhome) OR $homescore == '') { $result_point = 0; }
else { $result_point = 0; }
if ($homescore == $predhome && $awayscore == $predaway && $homescore != '') { $bonus = $bonus; }
else if (is_null($predhome) OR $homescore == '') { $bonus = 0; }
else { $bonus = 0; }
if (is_null($predhome) OR $homescore == '') { $total_point = 0; }
else { $total_point = $result_point + $bonus; }
//Calculate total round sum
$total_roundsum = $result_point + $bonus;
//echo $username.' - '.$total_roundsum.'<br />';
if($total_roundsum != 0) {
echo $row['userid']. ' - ' .$total_roundsum.'<br />';
}
}
At the moment, the code only echo's the results.
The "variables.php" holds the $correct_score + $correct_result + $correct_number variables.
Assuming the two columns are an associated array -- $users_and_points.
$points_array = array();
foreach ( $users_and_points as $user_id => $point ) {
if( !isset( $points_array[$user_id] ) {
$points_array[$user_id] = 0;
}
$points_array[$user_id] += $point;
}
// newly associated array with calculated totals
$points_array;
Update
Based on your code above instead of echoing build an array of users and points.
echo $row['userid']. ' - ' .$total_roundsum.'<br />';
can be replaced with:
if( !isset( $points_array[$row['userid']] ) {
$points_array[$row['userid']] = 0;
}
$points_array[$row['userid']] += $total_roundsum;
That will give you an associated array of user ids and associated points.
print_r( $points_array );
Note: Set the variable before your loop. Example, $points_array = array();

How can I "limit" the page numbers of a forum/blog in PHP

I'm trying to fix something with which I'm not familiar with and don't know how to proceed. The forum on which I'm working is suppose to show under "TOP 50" only the most commented topics (2 pages by 25 topics) but it shows all topics (by 25) without any limitation of the pages. I need only the first 2 pages - but don't know how to get rid of the others?
I'm even not sure that the below code is the responsible one but please have a look and give me a hint if you see any solution.
This is the code:
{
public function __construct()
{
parent::__construct();
}
public function get_forum()
{
if ($_GET['l'] && ($_GET['l'] == 'leng' || $_GET['l'] == 'lrus' || $_GET['l'] == 'lde' || $_GET['l'] == 'ltr'))
$l = substr($_GET['l'], 1);
else
$l = 'eng';
(isset($_GET['num'])) ? $page = intval($_GET['num']) : $page = 1;
$id_user = intval($_SESSION['user_id']);
$lang = language::getLang();
if ($_GET['el']) {
switch ($_GET['el']) {
case 'categories':
return $this->getCategories($l);
break;
case 'top':
$top_lang = $_GET['ln'];
$c = $this->db->selectAssoc($this->db->Select('*', 'forum_categories ,forum_thems', "`forum_categories`.`lang` = '" . $l
. "' AND `forum_thems`.`id_categories` = `forum_categories`.`id`"));
$total_pages = count($c) / 25;
$p = "<div class=\"pageCounter_box\">Pages:";
if (empty($_GET['p'])) {
$_GET['p'] = 1;
}
for($i=1; $i<$total_pages+1; $i++){
if ($i == $_GET['p']) {
$class = 'class="active_page"';
}
$p .= "<a href=\"$top_lang/smoke/{$_GET['l']}/top?p=$i\" $class>$i</a>";
}
$p .= "</div>";
return $this->getTop($l) . $p;
break;
I think you could do a check in there of If ($total_pages > 2) { $total_pages = 2};
$c = $this->db->selectAssoc(
$this->db->Select('*', 'forum_categories ,forum_thems', "`forum_categories`.
`lang` = '" . $l. "' AND `forum_thems`.
`id_categories` = `forum_categories`.`id`"));
$total_pages = count($c) / 25;
if ($total_pages >2) { //limit to two pages
$total_pages = 2;
}
$p = "<div class=\"pageCounter_box\">Pages:";
if (empty($_GET['p'])) {
$_GET['p'] = 1;
}
"thanks a lot - great help! Do you further see why both pages might show active (page counter shows both active) when showing page 1? Page 2 is fine, there only Page 2 shows active..."
The $class variable is staying set, you need to have an else that sets the class to an empty string
for($i=1; $i<$total_pages+1; $i++){
if ($i == $_GET['p']) {
$class = 'class="active_page"';
} else {
$class = '';
}
$p .= "<a href=\"$top_lang/smoke/{$_GET['l']}/top?p=$i\" $class>$i</a>";
}

Categories