I try show all the hours of the day in order 8, 9, 10 ... but to distinguish the hours that are in the database from the hours that are not. For instance, to give a different color. Can anyone help? (I am not a programmer and I am just learning php alone, so any I would appreciate any help, but explain it in a simple way, please)
This gives me the hours that I have in the database in blue. But I cannot to get hours that are not in the database and I cannot give them another color and the right position: 8, 9,10, 11...
$result = mysqli_query($con, 'SELECT * FROM consulta
WHERE professional=1
AND client=0');
while ($row = mysqli_fetch_array($result)) {
if ($row['hour']=='09:00:00') { echo '<p style="color:blue;">9</p>'; }
elseif ($row['hour']=='10:00:00') { echo '<p style="color:blue;">10</p>'; }
elseif ($row['hour']=='11:00:00') { echo '<p style="color:blue;">11</p>'; }
elseif ($row['hour']=='12:00:00') { echo '<p style="color:blue;">12</p>'; }
}
Here's some sudo code for you. Make an array with all the hours in it. Then iterate that array instead of the result from the database.
for ($i = 0; $i < 24; $i++) {
if(in_array("$i:00:00", $row)) {
// hour was found in the database
echo '<p style="color:blue;">'.$i.'</p>';
} else {
// hour was not found
echo '<p style="color:red;">'.$i.'</p>';
}
}
This way you're iterating over hours that are in the database. Just them. So if 11 is not in the database, if simply won't show. You need a different logic.
You need to iterate over all 24 hours and for each hour check if it is in the database, if so, apply styling, if not, render normally. And a hint, it might be easier to defince CSS classes instead of using inline styling (<p class="db">9</p> instead of <p style="color:blue;">9</p>, and of course, having the db class defined properly; that way you only need to change one rule instead of styling of each element in case you want to change something).
Related
im trying to write a loop that displays the counter on one line, been sitting here for over an hour but cant figure it out.
The main loop is
while($counter< 100){
echo $counter;
usleep($timeInSeconds*1000000);
$counter=$counter+1;
}
Now this prints 100 numbers after a delay each on a new line. Is it possible for the echo to instead replace itself for each loop?
I tried many options, here is one that didnt crash:
while($counter < 100){
$counter=$counter+1;
echo $counter;
usleep($timeInSeconds*1000000);
flush();
ob_flush();
}
However, with this option it works in one line with a delay, but it doesnt clear the previous echo, so its just a bunch of number next to each other
Could someone help me out?
You are trying to do something on the server that should be done on the client.
I expect you are making a timer. You should write some JavaScript code instructing the web browser on how to display multiple numbers with a delay in between. Your current code will show a loading wheel and a blank screen for the entire duration on many browsers.
Instead, replace your loop with something like:
var time_in_seconds = 1; // You can replace 1 with the value of the PHP variable
var count_element = document.getElementById("example_counter");
var n = 0;
var interval_id;
function update_counter(){
n += 1;
if (n >= 100) {
clearInterval(interval_id);
}
count_element.textContent = n;
}
interval_id = setInterval(update_counter, time_in_seconds * 1000);
<span id="example_counter"></span>
I am working on a PHP application and stumbled upon a problem on auto-highlighting.. I want to ask how to auto-highlight a cell of a table, whose data came from a database, after checking if the value is negative, 0, or positive, Red for negative, yellow for 0 and green for positive.
Please note that I have no experience regarding JavaScript or Ajax and rudimentary knowledge only on CSS. Thank you.
If needed, I can post any part of my code here.
It might be helpful for you:
function getSampleStatus($sampleid){
if($sampleid==1){
$color="#007334";
}elseif($sampleid==2){
$color="#3f96e8";
}elseif($sampleid==3){
$color="#ff9900";
}elseif($sampleid==4){
$color="#ff9770";
}
else{
$color="#ff0000";
}
$query='Select status from config where status_id='.$sampleid;
$this->_db->setQuery( $query );
$status =$this->_db->loadResult();
return "<span style='color:".$color.";padding-left:200px;'>".$status."</span>";
}
This function simply adds different colors depending on sample status.
For example:
For disapproved records, color red.
For Approved records, color green.
For Lab completed records, color yellow and so on..
Edit:
For Simplicity, try this:
$yourdatafromdatabase = 3; //which is either -ve, zero or positive
if($yourdatafromdatabase < 0){
$color="#FF0000"; //red for less than zero
}elseif($yourdatafromdatabase== 0){
$color="#FFFF00"; //yellow for zero
}
else{
$color="#00FF00"; //green for positive
}
echo "<span style=\"color: $color\"> <h1> Wow Color! </h1></span>";
?>
Working Demo:>>
just write css in table tag e.g
if ($value <0)
{echo "<td bgcolor=\"#FF0000\">$value</td>";}
I have a problem:
Here's a block of the code:
function draw()
{
$out_string="";
$out_string.=$this->script;
reset($this->fields);
$num_list_box=0;
while( $field = each($this->fields) )
{
if (isset($this->fields[$field[1]->field]->options))
{
if (preg_match("/<script type=\"text\/javascript\">/i",$this->fields[$field[1]->field]->options[0][1])&& $this->fields[$field[1]->field]->value!="")
{
if ($num_list_box==0) $out_string.= "<script type=\"text/javascript\">levels.forValue(\"".$field_prev[0]."\").setDefaultOptions(\"".$this->fields[$field[1]->field]->value."\");</script>\n";
else $out_string.= "<script type=\"text/javascript\">levels.forValue(\"".$field_prev[0]."\").forValue(\"".$field_prev[1]."\").setDefaultOptions(\"".$this->fields[$field[1]->field]->value."\");</script>\n";
$field_prev[]=$this->fields[$field[1]->field]->value;
$num_list_box++;
} else
{
$field_prev[0]=$this->fields[$field[1]->field]->value;
$num_list_box=0;
}
}
}
$out_string.=$this->draw_title();
$out_string.=$this->draw_header();
$out_string.= "<table class=\"forms\">\n";
$field=array_keys($this->fields);
reset($field);
$ind_first=true;
while( list($pos,$field_name) = each($field) )
{
if ($this->num_cols>0) {
if ($this->fields[$field_name]->col==1){
if ($ind_first) $ind_first=false;else $out_string.="</tr>";
$out_string.="<tr><td class=\"field_title\">";}
else $out_string.="<td class=\"field_title\">";
$out_string.= $this->fields[$field_name]->title."</td>";
$colspan="";
if ($this->num_cols>1) {
if ($this->fields[$field_name]->col==1 && array_key_exists($pos+1,$field) && $this->fields[$field[$pos+1]]->col==1)
$colspan="colspan=\"3\"";
}
$out_string.="<td class=\"field_value\" $colspan>";
$out_string.=$this->fields[$field_name]->draw()."</td>";
} else
{
if ($ind_first) $ind_first=false;else $out_string.="</tr>";
$out_string.="<tr><td class=\"field_value\">".$this->fields[$field_name]->title."<br />";
$out_string.=$this->fields[$field_name]->draw()."</td>";
}
}
$out_string.= "</tr></table>\n";
return $out_string;
}
This above block of code produces something like this:
I want it such that in the example provided that the word "Transaction" is above the text box.
Please help, the person that programmed this part is indisposed and we've got a deadline.
Thanks for the help.
P.S. The CSS class name for the text is: field_title and the one for the textbox is field_value
Thanks once more.
You will have to debug that code to find out when the label "Transaction" is getting inserted into that cludge of table code. Once you find where "Transaction" is inserted you can then create new logic to add another TR that colspans the table and place the label on that new row.
Good luck, looks like a headache.
Your code is apparently building a rather complex form based on some data ($fields property of the class). I guess some "field settings" (like col) describe how the form should look like.
So, your code is doing things that are neither described in your question nor in the code itself. Furthermore, we have no clue what the complete form currently looks like, so we can't even guess the intention of the code.
Your request, to let the description appear above the selection box(?) could be done probably throwing away half of the code, but that won't help you.
PS: Please check the FAQ - this site is for questions, not for finding people to do your (or elses) work. You should really have a programmer solve your problem directly having access to the whole page.
I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
$(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.
Trying to get it to loop through 3 times and after the 3rd time (if not guessed right) show the right answer.
Currently - its going through the guesses, but isnt showing how many guesses are left (should be deducting each # each attempt).
Anyone? If you could show me where I'm going wrong here.
<style type="text/css">
input {border:1px solid #ADD8E6; font-size:1.2em;}
input.spec {background-color:#ddd;}
</style>
<?php
echo "<fieldset><h1><legend>Testing your Academy Award Trivia</h1>";
$ages['Casablanca'] = "1943";
$ages['Around The World in 80 Days'] = "1956";
$ages['Patton'] = "1970";
$ages['Annie Hall'] = "1977";
$ages['Chariots of Fire'] = "1981";
$ages['Dances With Wolves'] = "1990";
$ages['Crash'] = "2005";
$ages['The Departed'] = "2006";
$rand_keys = array_rand($ages, 1);
$guesses = 3;
?>
<form method='post' name="inputyear" onsubmit="return validate(this);">
Give the year below won academy award<br><br>
<Strong>Movie:</strong> <input type='text' name='movie' class="spec" value='<?= $rand_keys ?>' readonly='readonly' /><br><br>
<Strong>Year it Won the Oscar:</Strong> <input type='text' name='year' size="30" /><br/><br>
<strong>You have: </strong> <?php $guesses; ?> guesses left<br><br>
<input type='submit' name='submit' value="Get Result" onClick="makeGuess()" />
</form>
<?php
$movie = isset($_POST['movie']) ? $_POST['movie'] : false;
$guessedYear = isset($_POST['year']) ? (int) $_POST['year'] : false;
if ($movie && $guessedYear) {
$realyear = $ages[$movie];
}
#$_SESSION[$movie]['$guesses']++;
if ($realyear && $_SESSION[$movie]['$guesses'] < 3) {
if ($guessedYear == $realyear) {
echo "Correct! " . "during year " . $realyear;
}
if ($guessedYear < $realyear) {
echo "Wrong, year too low";
$guesses--;
}
if ($guessedYear > $realyear) {
echo "Wrong, year too high";
$guesses--;
}
} elseif ($_SESSION[$movie]['$guesses'] >= 3) {
echo "Sorry, too many tries. the answer was " . $realyear;
} else {
echo "Sorry, You managed not to pick a year. Please try again";
$_SESSION[$movie]['guesscount']--;
}
?>
the return statement is leaving the loop and the script
get rid of both return statements
DC
Further to your comments on the duplicate question at...
Allowing 3 attempts at game - php
It would appear that this question is a 'homework' question as such and in fact with all questions no-one will give you the complete answer, nor in my opinion should they. We all expect that the person asking the question will take it upon themselves to investigate and understand the answers given.
Now in the case of your question, you appear to be missing a vital piece of information about how HTTP works (http is the protocol that drives all web pages and many other parts of the internet).
http is what's considered a stateless protocol, that is when you click on a link in a web page and go to another web page (or even the same web page), the new web page considers you a totally new visitor. It in effect has forgotten you.
Because this introduced issues for things like shopping carts (and PHP games) cookies were invented. this allowed the browser to carry around a small bit of information about you, in this way the web server or application remembered you. This has been extended into what respondents here are calling sessions.
A session is (usually) a cookie that stores an identifier. that identifier tells, in this case PHP, that you have been there before and where to find the information about you. PHP can load this information and make it available to you the programmer.
This happens EVERY TIME a page is loaded.
Now PHP does not know what to store in this 'session' it is up to you the programmer to decide what information needs to be stored. you need to tell PHP to save this information for the next time the page is loaded.
In your case its up to you to decide what needs to be remembered. Consider the reloading of the page to be a new 'iteration' of the loop. this should lead you to some obvious conclusions about what needs to be passed from one iteration to the next.
There you go. I haven't written the answer for you but hopefully have provided enough for you to pass your class in flying colours.
DC
I think you're problem is this line $rand_keys = array_rand($ages, 1);. Each time the user submits their answer a new $rand_keys is selected and fed into the dropdown regardless of what the submitted answer was.
So you'll want to check if there exists an answer (otherwise it's the first time the page is loaded). If there is an answer and it was correct then show a congrats message and generate a new movie id.
if($_POST['submit']) {
$movie = $_POST['movie'];
$guessedYear = $_POST['year'];
if ($guessedYear == $ages[$movie]) {
// well done you got it right, next movie
$rand_keys = array_rand($ages, 1);
}
else if ($guessedYear == $ages[$movie] && $_POST['tries'] >= 3) {
// took over 3 tries and didn't get it right, next movie
$rand_keys = array_rand($ages, 1);
}
else {
// find $movie index from $ages and use that
}
// you have one less try
$tries = $_POST['tries'] - 1;
}
else {
$rand_keys = array_rand($ages, 1);
$tries = 3;
}
Then in the form send the $tries variable along with the other ones, or as the other people here have said put it in the session variables. With that I think you should be able to remove the while loop completely.
After you fix what DeveloperChris says, you still need to put guesscount into as session or form field, and increment on each attempt.
if($guesscount < 3 && $guessedYear > $realyear){
echo "Wrong, year too high";
}
if($guesscount < 3 && $guessedYear > $realyear){
echo "Wrong, year too high";
}
duplicate code there. also i think you are looking for if{...}else if{..}else if{...}else{...}
and your question has nothing to do with javascript.
maybe core logic more like this?
$movie = isset($_POST['movie']) ? $_POST['movie'] : false;
$guessedYear = isset($_POST['year']) ? (int) $_POST['year'] : false;
if ($movie && $guessedYear) {
$realyear = $ages[$movie];
}
#$_SESSION[$movie]['guesscount']++;
if ($realyear && $_SESSION[$movie]['guesscount'] < 3) {
if ($guessedYear == $realyear) {
echo "Correct! " . "during year " . $realyear;
}
if ($guessedYear < $realyear) {
echo "Wrong, year too low";
}
if ($guessedYear > $realyear) {
echo "Wrong, year too high";
}
} elseif ($_SESSION[$movie]['guesscount'] >= 3) {
echo "Sorry, too many tries. the answer was " . $realyear;
} else {
echo "Sorry, You managed not to pick a year. Please try again";
$_SESSION[$movie]['guesscount']--;
}