I have a database table that is called roles. and it contains 5 roles and has id from 1 to 5, I have gotten the code below to work with 1 id only but want to add more without re using the entire block. so if id equals 3,4,5 show the link. can I add multiple id's in the if?
while ($row = mysqli_fetch_assoc($result)) {
$RoleID = $row['RoleID'];
if ($RoleID == 3) {
echo '<li><span>Admin Area</span></li>';
}
}
I guess you can use in_array:
$admin_array = [3,4,5];
while ($row = mysqli_fetch_assoc($result)) {
if (in_array($row['RoleID'], $admin_array) {
echo '<li><span>Admin Area</span></li>';
}
}
Hope below code will help you
I have used in_array() function
while ($row = mysqli_fetch_assoc($result)) {
$RoleID = $row['RoleID'];
if (in_array($RoleID,array(3,4,5))) {
echo '<li><span>Admin Area</span></li>';
}
}
Something that will give some added flexibility when say you want an id to do something similar but maybe end in the same way is to use a switch case.
while ($row = mysqli_fetch_assoc($result)) {
switch($row['RoleID']) {
case 1:
//Id 1 logic only
break;
case 2:
//Id 2 logic only
break;
case 3:
//Without a break it will fall through.
//Nice because if for some reason you need
//custom for individual id do it with no break
case 4:
case 5:
echo '<li><span>Admin Area</span></li>';
break;
default:
//Do something here for instances when a ROLE ID is not found
}
}
Related
I'm trying to make a tab for my page, where each tab shows a different field of a mysql table row. I'd like to switch contents in the tab.
Every row has a different id, and I would like to make a tabbed design. The data should be chosen by the id of the table.
The tab works fine if i use just a simple text in the echo part, but I can't fetch the data from my database.
I tried this code, but it doesn't work.
<?php
if (isset($data[0]) && is_numeric($data[0]) ) {
$content = mysql_fetch_assoc ( mysql_query( "select id,tab_content_one,tab_content_two,tab_content_three,tab_content_four,tab_content_five from db_name where id = $data[0];") );
} else {
$content = mysql_fetch_assoc ( mysql_query( "select id,tab_content_one,tab_content_two,tab_content_three,tab_content_four,tab_content_five from db_name order by id asc limit 1;") );
}
switch($_GET['tabNum']) {
case 1: echo strip_tags($content['tab_content_one']); break;
case 2: echo strip_tags($content['tab_content_two']); break;
case 3: echo strip_tags($content['tab_content_three']); break;
case 4: echo strip_tags($content['tab_content_four']); break;
case 5: echo strip_tags($content['tab_content_five']); break;
}
?>
I don't know what's wrong with my code. Do you have any idea?
You've got to enclose the mysql_fetch_assoc into a while loop! For your code it will be something like this:
if (isset($data[0]) && is_numeric($data[0]) ) {
$sql = "select id,tab_content_one,tab_content_two,tab_content_three,tab_content_four,tab_content_five from db_name where id = $data[0];";
} else {
$sql = "select id,tab_content_one,tab_content_two,tab_content_three,tab_content_four,tab_content_five from db_name order by id asc limit 1;";
}
$result = mysql_query($sql);
while($content = mysql_fetch_assoc($result)){
switch($_GET['tabNum']) {
case 1: echo strip_tags($content['tab_content_one']); break;
case 2: echo strip_tags($content['tab_content_two']); break;
case 3: echo strip_tags($content['tab_content_three']); break;
case 4: echo strip_tags($content['tab_content_four']); break;
case 5: echo strip_tags($content['tab_content_five']); break;
}
}
Anyway it's suggested to you as mysql_fetch_assoc it's going to be deprecated starting from php 5.5.0 to use the mysql_PDO extension instead.
I need to use the goto operator in my code as I can't seem to think of a way around it. However the problem is my host only has PHP version 5.2.17 installed.
Any ideas?
Below is my code:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
goto skip;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
skip:
There are a few anti-patterns in your code. Let's clean it up. I'll explain what's been changed in a jiffy.
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
}
}
First things first: There is no need to perform a query, fetch all of the results, then loop through those results (in_array) looking for a specific value. Let the database do that for you by expressly looking only for rows where inserted is the string literal "n".
Because we know that we're only getting "n" records back, we just need to check if there are any results. If so, run the query. If there are no "n" records, the UPDATE isn't run.
If you need to know that the UPDATE ran, add a check for it:
$ran_update = false;
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
$ran_update = true;
}
}
if($ran_update) {
// ...
}
You want to use the correct control word to break from the loop:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
break;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
The break keyword will do exactly what you want: End the execution of the while loop. Never ever ever use a goto!
As a direct response to the title of this post:
do{
if (!$condition){
break;
}
// Code called if conditions above are met
}while(0);
//Code always called
In some circumstances, this, or a goto, can make for very tidy and readable code.
First, you could use a break to exit your initial loop. Second, if you need to test for anything, set a variable (must be global not local) as a flag or indicator before calling break, then do a conditional test statement where your skip line is to perform any additional steps you need.
I'm retrieving data from a MySQL db and creating reports from it. I need to get counts when certain conditions are met, and since db queries are rather expensive (and I will have a lot of traffic), I'm looping thru the results from a single query in order to increment a counter.
It seems like it's working (the counter is incrementing) and the results are somewhat close, but the counters are not correct.
At the moment, there are 411 records in the table, but I'm getting numbers like 934 from a ['total'] counter and 927 for ['males'], and that definitely can't be right. However, I get 4 from ['females'], which is correct…
I'm pretty sure it was working last night, but now it's not—I'm quite baffled. (there are still just 411 records)
$surveydata = mysql_query("SELECT `age`,`e_part`,`gender` FROM $db_surveydata;") or die(mysql_error());
$rowcount = mysql_num_rows($surveydata);
$age=array('18+'=>0,'<18'=>0,'total'=>0);
$e_part=array('yes'=>0,'no'=>0,'total'=>0);
$genders=array('male'=>0,'female'=>0,'trans'=>0,'don\'t know'=>0,'total'=>0);
while ($responses = mysql_fetch_assoc($surveydata)) {
foreach ($responses as $response){
switch ($response){
case $responses['age']:
if ($responses['age'] > 18) {$age['18+']++;$age['total']++;}
// i tried putting the ['total'] incrementer in the if/else
// just in case, but same result
else {$age['<18']++;$age['total']++;}
break;
case $responses['e_part']:
if ($responses['e_part']) {$e_part['yes']++;}
else {$e_part['no']++;}
$e_part['total']++;
break;
case $responses['gender']:
switch ($responses['gender']){
case 1:$genders['male']++;break;
case 2:$genders['female']++;break;
case 3:$genders['trans']++;break;
case 9:$genders['don\'t know']++;break;
default:break;
}
$genders['total']++;
break;
default:break;
} // end switch
} //end for
} // end while
thanks!
this is the problem:
foreach ($responses as $response){
switch ($response){
case $responses['age']:
switch $responses looks for match
foreach ($responses as $k=>$v){
switch ($k){
case 'age':
if ($v > 18) ....
mysql_fetch_assoc() retrieves a single row from the table. You then loop over that row, processing each individual field. Then the long set of if() checks to determine which field you're on. That entire structure could be changed to:
while($response = mysql_fetch_assoc($surveydata)) {
if ($responses['age'] > 18) {
$age['18+']++;
} else {
$age['<18']++;
$age['total']++;}
if ($responses['e_part']) {
$e_part['yes']++;
} else {
$e_part['no']++;
}
$e_part['total']++;
switch ($responses['gender']){
case 1:$genders['male']++;break;
case 2:$genders['female']++;break;
case 3:$genders['trans']++;break;
case 9:$genders['don\'t know']++;break;
default:break;
}
$genders['total']++;
}
There's no need for the switch ($response); you can't really switch on an array like that. And even if you could, the 'values' you get wouldn't make any sense -- i'm thinking if it works at all, the value you're switching on would be either 'Array' or the length of the array. (I forget how PHP handles arrays-as-scalars.)
You'll want something like this...
$total = 0;
while ($response = mysql_fetch_assoc($surveydata))
{
if (isset($response['age']))
{
++$age[($response['age'] < 18) ? '<18' : '18+'];
++$age['total'];
}
if (isset($response['e_part']))
{
++$e_part[($responses['e_part']) ? 'yes' : 'no'];
++$e_part['total'];
}
if (isset($response['gender']))
{
switch ($response['gender'])
{
case 1: ++$genders['male']; break;
case 2: ++$genders['female']; break;
case 3: ++$genders['trans']; break;
case 9: ++$genders["don't know"]; break;
}
++$genders['total'];
}
++$total;
}
The benefit of the if (isset(...)) is that if 'age', 'e_part', or 'gender' is null, the corresponding code to count it won't get activated. It does about the same thing as your code, minus the embarrassing loop -- and minus the counting of the field even though it is null, because every row will have the same fields.
I have a code like this
<?php
$getLeftSide = 'select * from leftmenu';
$result = $db -> query ($getLeftSide) or die ("$db->error");
if ($result) {
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
echo "<div class='left_main_cat'>Web and Desigen</div>";
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
}
?>
I need to echo this line one time
echo "<div class='left_main_cat'>Web and Design</div>";
of course it's under the while loop so it print it self many times
is there is a why to solve this and print this line one time only.
As Ben suggests, the easiest and clearest solution is to use a boolean check variable:
$catFound = FALSE;
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
// We only want this category printed for the first category,
// if it exists.
if(!$catFound) {
echo "<div class='left_main_cat'>Web and Desigen</div>";
$catFound = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
Although it seems better to use a boolean variable and a comment to make clear your intent.
Ugly, but I'm not that good at PHP yet!
$has_printed = FALSE;
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
if(!$has_printed){
echo "<div class='left_main_cat'>Web and Desigen</div>";
$has_printed = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
Simple solution: Add another boolean variable with default value false Then just check if false, print your text and set it true.
adding a boolean or check variable or any kind of conditional inside of a loop is a very bad idea imho, i NEVER do it. every time you swing through the loop, the condition has to be checked. it's like a badly written switch/case.
figure out a way to do it before the loop.
unroll the loops, most people do it to save space but most compilers will unroll them anyway for optimization
stick it before the loop
find a java or css way to hide it until the loop is done or you want to display stuff.
function addAds($n) {
for ($i=0;$i<=$n;$i++) {
while($row=mysql_fetch_array(mysql_query("SELECT * FROM users"))) {
$aut[]=$row['name'];
}
$author=$aut[rand(0,mysql_num_rows(mysql_query("SELECT * FROM users")))];
$name="pavadinimas".rand(0,3600);
$rnd=rand(0,1);
if($rnd==0) {
$type="siulo";
} else {
$type="iesko";
}
$text="tekstas".md5("tekstas".rand(0,8000));
$time=time()-rand(3600,86400);
$catid=rand(1,9);
switch ($catid) {
case 1:
$subid=rand(1,8);
break;
case 2:
$subid=rand(9,16);
break;
case 3:
$subid=rand(17,24);
break;
case 4:
$subid=rand(25,32);
break;
case 5:
$subid=rand(33,41);
break;
case 6:
$subid=rand(42,49);
break;
case 7:
$subid=rand(50,56);
break;
case 8:
$subid=rand(57,64);
break;
case 9:
$subid=rand(65,70);
break;
}
mysql_query("INSERT INTO advert(author,name,type,text,time,catid,subid) VALUES('$author','$name','$type','$text','$time','$catid','$subid')") or die(mysql_error());
}
echo "$n adverts successfully added.";
}
The problem with this function, is that it never loads. As I noticed, my while loop causes it. If i comment it, everything is ok. It has to get random user from my db and set it to variable $author.
The problem is that the query is in the loop, so it gets run every time (so you start from the beginning every time). Just move the mysql_query() part to right before the while loop and store it in a variable:
$query = mysql_query("SELECT * FROM users");
while($row=mysql_fetch_array($query))
You can replace this mega switch with one line:
$subid = rand(($catid * 8) - 7, min($catid * 8, 70));
The condition of a while loop is executed and evaluated with each iteration. So mysql_query is called with every iteration and retunrs true.
Just execute your database query once and cache the result:
function addAds($n) {
$result = mysql_query("SELECT * FROM users");
$aut = array();
while ($row = mysql_fetch_array($result)) {
$aut[]=$row['name'];
}
$rowCount = count($aut);
for ($i=0; $i<=$n; $i++) {
$author=$aut[rand(0,$rowCount)];
// …
mysql_query("INSERT INTO advert(author,name,type,text,time,catid,subid) VALUES('$author','$name','$type','$text','$time','$catid','$subid')") or die(mysql_error());
}
echo "$n adverts successfully added.";
}
I also think the problem is your functions are way too big to understand(quickly). You should make them smaller and test them with a unit testing framework like phpunit.
It's a lot of time that I don't use PHP but I think that the assignment
$row=mysql_fetch_array(mysql_query("SELECT * FROM users"))
should always returns true, it executes the query again and again on every iteration..
You're starting a new query each time you run the loop.