How I can simplify this PHP code? too many switch() function - php

I made listview in jQuery Mobile and I used PHP to feed its contents. It works properly, but the code is too long and most part of it are very similar to each other. Is there any way to simplify the code? Please have a look at the code, then I'll explain what I really need to do:
<ol data-role="listview">
<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
switch ($row[1]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
}
// second column check
switch ($row[2]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// third column check
switch ($row[3]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// fourth column check
switch ($row[4]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// fifth column check
switch ($row[5]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// sixth column check
switch ($row[6]) {
case "Behnam":
echo " B ";
break;
case "Tarin":
echo " T ";
break;
default:
echo " N ";
}
echo "</li></a>";
}
?>
</a></li>
</ol>
and the result is:
By using while ($row = mysql_fetch_array($result)){ I can fetch each row of the sql table one by one. But I also need to check the value of each cell(column) as well.

Group the code in a 2 parameter function:
function checkRowValue($row, $checkDefault) {
switch ($row) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
if ($checkDefault)
echo " N . ";
}
}
Invoke as:
<ol data-role="listview">
<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
for ($i = 0; $i < 7; $i++)
checkRowValue($row[i], $i > 0);
}

This generalizes it by applying a function over all the columns in your row (skipping first) and then string them together with " . ".
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<li><a href=\"#\">";
echo join(' . ', array_map(function($v) {
if ($v == 'Behnam') {
return 'B';
elseif ($v == 'Tarin') {
return 'T';
else {
return 'N';
}
}, array_slice($row, 1));
echo "</li></a>";
}

Try This
if(in_array("Behnam",$row) {
echo " B . ";
}
else if(in_array("Train",$row) {
echo " T . ";
}
else {
echo " N . ";
}

This is the final result:
<ul id="competition_list" data-role="listview" data-inset="true" data-theme="a">
<?php
// using the returned value from database to feed the list.
// showing the competiton rounds' outcome.
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
echo $row[0] . "."; //this is the id column in the table and will give me the number of the row
for($i = 1; $i <= 5; $i++){
switch ($row[$i]) {
case "Behnam":
echo " B ";
break;
case "Tarin":
echo " T ";
break;
}
} // end for()
echo "</a></li>";
} // end while()
?>
</ul>

<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
foreach($row as r)
{
switch (r) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
}
}
?>

Related

how to make static index of array in php

I am trying to store values from form radio to array. But problem which i am facing is that every time array 1st index is replaced with new value. I believe this is scope problem. I also tried to declare global array but no success.
Here is the code:
<?php
include_once("connection.php");
$c = new DBcon();
$c->startcon();
global $array; // not effecive
// $q = $_POST['t'];
// echo 'fff', $q;
$page = $_GET['page'];
echo 'pagesss', $page, 'ppp';
if ($page == "") {
$page = "1";
} else {
// If page is set, let's get it
$page = $_GET['page'];
}
// Now lets get all messages from your database
$sql = "SELECT * FROM quizes";
$query = mysql_query($sql);
// Lets count all messages
$num = mysql_num_rows($query);
// Lets set how many messages we want to display
$per_page = "2";
// Now we must calculate the last page
$last_page = $num;
echo 's', $num;
// And set the first page
$first_page = "1";
// Here we are making the "First page" link
echo "<a href='?page=" . $first_page . "'>First page</a> ";
// If page is 1 then remove link from "Previous" word
if ($page == $first_page) {
echo "Previous ";
} else {
if (!isset($page)) {
echo "Previous ";
} else {
// But if page is set and it's not 1.. Lets add link to previous word to take us back by one page
$previous = $page - 1;
echo "<a href='?page=" . $previous . "'>Previous</a> ";
}
}
// If the page is last page.. lets remove "Next" link
if ($page == $last_page) {
echo "Next ";
} else {
// If page is not set or it is set and it's not the last page.. lets add link to this word so we can go to the next page
if (!isset($page)) {
$next = $first_page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
} else {
$next = $page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
}
}
// And now lets add the "Last page" link
echo "<a href='?page=" . $last_page . "'>Last page</a>";
// Math.. It gets us the start number of message that will be displayed
$start = ($page * ($page - 1)) / $page;
echo 'start', $start;
echo 'page', $page;
// Now lets set the limit for our query
$limit = "LIMIT $start, $per_page";
// It's time for getting our messages
$sql = "SELECT * FROM quizes $limit";
$query = mysql_query($sql);
echo "<br /><br />";
// And lets display our messages
$i = 0;
$l = 0;
while ($row = mysql_fetch_array($query) or die(mysql_error())) {
$a = $row['A'];
echo '<form method="get" action="?page=".$next."">';
while ($row = mysql_fetch_array($query)) {
echo '<div class="boxed" >';
echo "\t" . '<tr><th>' .
$row['question'] . "<br>" .
'</th><th>' . "<input type='radio' name= 't[]' value='{$row['A']}'>" . $row['A'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['B']}'>" . $row['B'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['C']}'>" . $row['C'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['D']}'>" . $row['D'] . '</th>
</tr>';
echo '<input type="hidden" name="page" value="' . $next . '">';
echo '<input type="submit" name="submit"/>';
$i++;
echo '</div>';
echo '</div>';
}
echo '</form>';
if (isset($_GET['submit'])) {
$example = $_GET['t'];
foreach ($example as $value) {
$array[$i++] = ($value);
echo "$array[0] <br>"; // printing correct statement but replacing old values with new value everytime.
echo "$array[1] <br>"; // 0 values
echo "$array[2] <br>"; // 0 values
}
}
}
?>
I have seen these posts: PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"] , PHP - define static array of objects but no help. Kindly help what should i do?
You cannot do
$array[$i++]
this will always be $array[1]
instead do
$i++;
$array[$i]= $value;
P.S. $array is a terrible name for a variable...
if (isset($_GET['submit'])) {
$example = $_GET['t'];
$i=0;
$arrayA = array();
foreach ($example as $value) {
$arrayA[$i] = ($value);
$i++;
}
print_r($arrayA);
}
if you do
$array[$i++] ;
it wont work , just try this and it wont replace your old value
$array[$i] = $value;
$i++;
You must increment your variable first, then use the variable as the array key.
Edit: this is what you're looking for:
$i = 0;
foreach ($example as $value) {
$array[$i] = $value;
$i++;
}

Improving if statements in sql query

I've written some code that works fine, but is extremely verbose and would like a pointer on how to make it more efficient. I'm running different SQL queries because a single one returns too many results;
$sql1 = "select blah blah blah";
$sql2 = "select blah blah blah";
$sql3 = "select blah blah blah";
$response1 = $client->executeSQLQuery(array("sql"=>$sql1));
$response2 = $client->executeSQLQuery(array("sql"=>$sql2));
$response3 = $client->executeSQLQuery(array("sql"=>$sql3));
if( is_array($response1->return->row) )
{
foreach($response1->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response1->return->row->dnorpattern . "<br>";
$count++;
}
if( is_array($response2->return->row) )
{
foreach($response2->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response2->return->row->dnorpattern . "<br>";
$count++;
}
if( is_array($response3->return->row) )
{
foreach($response3->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response3->return->row->dnorpattern . "<br>";
$count++;
}
So, I would like to change the if statements to be a single if statement like this;
if( is_array($response1->return->row) )
{
foreach($response1->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response1->return->row->dnorpattern . "<br>";
$count++;
}
The integer for $sql and $response is predictable, so I should be able to use a for statement
for($x=1, $x<=3, $x++)
{
if( is_array($response[$x]->return->row) )
{
foreach($response[$x]->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response[$x]->return->row->dnorpattern . "<br>";
$count++;
}
}
But this does not work, can someone explain how I can increment the integer properly?
You can use curly braces syntax:
for($x=1; $x<=3; $x++)
{
if( is_array(${'response' .$x}->return->row) )
{
foreach(${'response' .$x}->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo ${'response' .$x}->return->row->dnorpattern . "<br>";
$count++;
}
}
OR save your three response objects in an array, and use your original syntax:
$response = [];
$response[1] = $client->executeSQLQuery(array("sql"=>$sql1));
$response[2] = $client->executeSQLQuery(array("sql"=>$sql2));
$response[3] = $client->executeSQLQuery(array("sql"=>$sql3));
Though you could probably just write a better SQL query and vastly simplify things

PHP Ranking function with TIES

So I have a function that takes a number and outputs it as a placement. How do I go about making the function take in consideration ties. I have a ranking database and this php code echos out rankings on a table. right now it ranks but it doesn't consider ties. How do i go about doing this
<?php
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
?>
<?php
$link = mysqli_connect("localhost", "citricide", "321213123Lol", "juneausmashbros");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM rankings ORDER BY points DESC";
$result = mysqli_query($link, $query);
echo '<article class="content grid_6 push_3">';
echo '<h1>';
echo 'Project M Summer Ranbat Rankings';
echo '</h1>';
echo '<section>';
echo '<center>';
echo '<table style="width:400px" class="rankslist">';
echo '<tr>';
echo '<th width="15%"><b>Rank</b></th>';
echo '<th width="45%"><b>Name</b></th>';
echo '<th width="45%"><b>Alias</b></th>';
echo '<th width="15%"><b>Points</b></th>';
echo '</tr>';
$ass = 0;
while($row = $result->fetch_array()) {
$ass++;
echo '<tr>';
if ($ass == 1) {
echo ' <center><td><B><font color=#FFD700>';
} else if ($ass == 2) {
echo ' <center><td><B><font color=#CCCCCC>';
} else if ($ass == 3) {
echo ' <center><td><B><font color=#cd7f32>';
} else {
echo '<td>';
}
echo addOrdinalNumberSuffix($ass);
echo ' </font></B</td></center>';
echo ' <td>'.$row['name'].'</td>';
echo '<td>'.$row['alias'].'</td>' ;
echo '<td>'.$row['points'].'</td>';
echo '</tr>';
}
echo '</table>';
echo '</center>';
echo '</section>';
echo '</article>';
?>
It seems like you need additional variables to track the rank and the previous value. By doing so, you can handle ties.
For example:
$ass = 0; // current record count
$rank = 0; // rank
$last_points = NULL; // variable to store last ranked value
while($row = $result->fetch_array()) {
$ass++;
// check if value changes and reset rank if it does
if ($row['points'] !== $last_points) {
$rank = $ass;
$last_points = $row['points'];
}
echo '<tr>';
if ($rank == 1) {
echo ' <center><td><B><font color=#FFD700>';
} else if ($rank == 2) {
echo ' <center><td><B><font color=#CCCCCC>';
} else if ($rank == 3) {
echo ' <center><td><B><font color=#cd7f32>';
} else {
echo '<td>';
}
echo addOrdinalNumberSuffix($rank);
echo ' </font></B</td></center>';
echo ' <td>'.$row['name'].'</td>';
echo '<td>'.$row['alias'].'</td>' ;
echo '<td>'.$row['points'].'</td>';
echo '</tr>';
}
So say your points looked like this:
100
100
90
80
The $rank value would be:
1
1
3
4

If statement with 2 conditions

I was practising statements and ran into a problem. I'm trying to make it so that if $child3 is available, then it will echo all three children, like how when $child2 is available, it echos Kim & Pom. What did I do wrong?
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child2) {
echo $child; echo " "; echo $child2;
} elseif($child3) {
echo $child; echo " "; echo $child2; echo " "; echo $child3;
} else {
echo $child;
}
Try reversing the conditions:
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child3){
echo $child . " " . $child2 . " " . $child3;
}else if($child2){
echo $child . " " . $child2;
}else{
echo $child;
}
You might also like the wonderful string concatenation operator ..
elseif only executes if none of the preceding ifs or elseifs executed. So you'll want to move it above the other if:
if($child3) {
echo $child; echo " "; echo $child2; echo " "; echo $child3;
} elseif($child2) {
echo $child; echo " "; echo $child2;
} else {
echo $child;
}
Probably you want something like this:
$child = 1; // Or $child = 2; Or $child = 3;
if ($child == 1) {
echo 'Kim';
} elseif ($child == 2) {
echo 'Pom';
} else {
echo 'Rob';
}
But I recommend switch() as soon as you have elseif.
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child3){
echo $child; echo " "; echo $child2; echo " "; echo $child3;
}elseif($child2){
echo $child; echo " "; echo $child2;
}else{
echo $child;
}
How about this?
if ($child) {
echo "{$child} ";
}
if ($child2) {
echo "{$child2} ";
}
if ($child3) {
echo "{$child3} ";
}
If that's your actual code, you'll only ever get Kim Rob, as $child2 will always be true, thereby bypassing your else clauses.
Also, you can combine your echos into:
echo "$child $child2 $child3";
It makes it far easier to read that way.
Here's how I would do it. I agree with Dragon that a switch would be clearer/better.
switch (true)
{
case (isset($child,$child2,$child3)) :
echo $child . ' ' . $child2 . ' ' . $child3;
break;
case (isset($child, $child2)) :
echo $child . ' ' . $child2;
break;
case (isset($child)) :
echo $child;
break;
}

Infinite loop - why?

for($i=0; $i<5; $i++) {
switch($i) {
case 0:
echo "<div class=\"darkgrey topdarkgrey\">";
break;
case 1:
case 3:
echo "<div class=\"lightgrey\">";
break;
case 2:
case 4:
echo "<div class=\"darkgrey\">";
break;
case 5:
echo "<div class\"darkgrey bottomdarkgrey\">";
break;
}
if($i=$idagInt)
echo "<div id=\"idag\">" . $dag[$i] . "<br>";
else
echo "<div class=\"dag\"><span class=\"veckoDag\">" . $dag[$i] . "</span><br>";
echo "<span class=\"month\">" . $datumDay[$i] . " " . $month[$i] . "</span></div>";
echo "<div class=\"mat\">" . strip_tags($mat[$i], "<p>") . "</div></div>";
}
This is the code I'm using to print things to the website and after some trouble-shooting my conclusion is that there's something wrong with the switch-statement, but I cant see what?
Here's your problem. You're assigning $i the value of $idagInt rather then comparing it. As a result $i never reaches 5.
if($i=$idagInt)
Change it to:
if($i==$idagInt)

Categories