Having Trouble with an odd/even script - php

I'm trying to make a script that outputs user names based on weather they are assigned an odd or even value. I think I've managed to get the odd ones working but the even ones wont output. Here is what it looks like. The 'commentid' is the value which determines if they are to be assigned to odd or even.
<?php
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query2 = "SELECT * FROM comments";
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2))
if ( $row2['commentid'] % 2 )
{
echo $row2['name'];
echo "<br />";
}
elseif (!$row2['commentid'] % 2)
{
echo $row2['name'];
}
else
{
echo "";
}
?>
I think it has something to do with either the $row2['name'] or (!$row2['commentid'] % 2) or maybe I need to assign rows to strings or something but I can't figure out what I'm doing wrong.
EDIT I really should have made it more clear exactly what I am trying to do with this script because while your answers make sense they dont solve my problem. On the same page as this script I have another script running. This script calls a value from a different table in the same database. It's running on a timed cron event that resets daily so the value is different every day. It looks like this and is working as it should.
<?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbnamesameasother', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
?>
What I am trying to do is only call up the names associated with either the odd or even value based on the number the script above dictates. So if this script chooses Result 1, I only want to display the user names who would fall under Result 1.

It is sufficient to do a:
if ($row2['commentid'] % 2)
{
// odd
}
else
{
// even
}
If you want to know whats wrong with your logic, you should learn something about operator precedence in PHP. According to the chart, ! has higher precendence than %. The expression !$row2['commentid'] % 2 is thus evaluated as follows:
when $row2['commentid'] is 0
!0 = true
true % 2 = 1
when $row2['commentid'] is 1
!1 = false
false % 2 = 0
when $row2['commentid'] is 2
!2 = false
false % 2 = 0

Hope this helps
if ( $row2['commentid'] % 2 ==0 )
{
echo $row2['name'];
echo "<br />";
}
else
{
echo $row2['name'];
}

if ( $row2['commentid'] % 2 )
{
echo $row2['name'];
echo "<br />";
}
elseif (!$row2['commentid'] % 2)
{
echo $row2['name'];
}
else
{
echo "";
}
replace this code with
if ( $row2['commentid'] % 2 )
{
echo $row2['name'];
echo "<br />";
}
else
{
echo $row2['name'];
}
since there is only two posibility either it commentid divisible by 2 or not divisible by 2

There is a problem. If you delete a comment, you will get 2 adiacent rows with/without <br>. You should use a an iterator variable, like this:
$i=1;
while ($row2 = mysql_fetch_assoc($result2)){
echo $row2['name'];
if($i % 2 == 0){
echo "<br />";
}
$i++;
}

Related

Php how to change background color <td> table?

I have a website and I prediction soccer. http://goaltips.nl/zeynel/Almanya2.php
I want to change background color(green) of the away wins fields if the nummer is bigger than 40 and Data is bigger than 5.
I have use this code for main page;
<?php
include 'almanya2fft.php';
include 'almanya2macsonu.php';
include 'almanya2ikibucuk.php';
foreach($array as $key => $data) {
echo "<tr>";
echo "<td>".$data['H']."</td>";
echo "<td>".$data['M']."</td>";
echo "<td>".$AwayPrediction[$key]."</td>";
echo "<td>".$IkiBucukAltPrediction[$key]." \r %".$IkiBucukUstPrediction[$key]."</td>";
echo "<td>".$VerisayisiData[$key]."</td>";
}
?>
</table>
</div>
and for almanya2ikibucuk.php is;
foreach($array as $key => $val) {
$IkiBucukAlt=0;
$IkiBucukUst=0;
$Verisayisi=0;
$sql = "SELECT * FROM Almanya2 where B = '{$val['B']}' AND E = '{$val['E']}' AND F = '{$val['F']}' AND O ='{$val['O']}' AND A = '*' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rowcount=mysqli_num_rows($result);
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['T'] == A){
$IkiBucukAlt++;
}else{
$IkiBucukUst++;
}
}
//We use an array rather than overriding everytime
$VerisayisiData[$key]=$rowcount;
$IkiBucukAltPrediction[$key] = round(($IkiBucukAlt/$rowcount )*100);
$IkiBucukUstPrediction[$key] = round(($IkiBucukUst/$rowcount)*100);
} else {
echo " ";
}
}
$conn->close();
?>
What is the best way to do this conditions.
I hoop i was clear and someone can help me...
Thank you.
Right after you started your foreach loop get the needed color :
$color = '';
if ($AwayPrediction[$key] > 40 && $VerisayisiData[$key] > 5) {
$color = "style='background-color : green';";
}
Then add the style to each cell :
echo "<td ".$color.">".$AwayPrediction[$key]."</td>";
So when the condition is true, an inline css is applied and colors your cell else it does nothing.
You can do it with ternary operator:
foreach($array as $key => $data) {
$color = $AwayPrediction[$key] > 40 && $VerisayisiData[$key] > 5 ? 'style="background-color:green"' : '';
echo "<tr $color>";
echo "<td>".$data['H']."</td>";
echo "<td>".$data['M']."</td>";
echo "<td>".$AwayPrediction[$key]."</td>";
echo "<td>".$IkiBucukAltPrediction[$key]." \r %".$IkiBucukUstPrediction[$key]."</td>";
echo "<td>".$VerisayisiData[$key]."</td>";
}

The value still store in database even the number of room is max number

<?php
$sql1 = "SELECT rmType,dateCi, SUM(rmNum) as total FROM reserve GROUP BY rmType,dateCi";
$result = mysqli_query($conn,$sql1);
while ($row1 = mysqli_fetch_assoc($result)) {
if ($row1['dateCi'] == $_SESSION['checkIn']){
if ($row1['rmType'] == 'sBed'){
if ($row1['total'] >= 10) {
echo "<script>alert('Single Bed Room is Full Occupied.')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'tSBed'){
if ($row1['total'] >= 10) {
echo "<script>alert('Two Single Bed Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'dBed'){
if ($row1['total'] >= 5) {
echo "<script>alert('Double Bed Room is Full Occupied')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'fBed'){
if ($row1['total'] >= 12) {
echo "<script>alert('Four-Bed Domitary Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
}
if ($row1['dateCi'] == $_SESSION['checkOut']){
if ($row1['rmType'] == 'sBed'){
if ($row1['total'] >= 10) {
echo "<script>alert('Single Bed Room is Full Occupied.')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'tSBed'){
if ($row1['total'] >= 10) {
echo "<script>alert('Two Single Bed Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'dBed'){
if ($row1['total'] >= 5) {
echo "<script>alert('Double Bed Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'fBed'){
if ($row1['total'] >= 12) {
echo "<script>alert('Four-Bed Domitary Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
}
}
?>
<?php
$query = "INSERT INTO `reserve` (`userId`,`userName`,`userEmail`,`rmType`,`rmNum`,`guest`,`dateCi`,`dateCo`,`cost`) VALUES('".$userRow['userId']."','".$userRow['userName']."','".$userRow['userEmail']."','".$roomtype."','".$roomNum."','".$guest."','".$checkIn."','".$checkOut."','".$pay."')";
$res1 = mysqli_query($conn,$query);
if($res1) {
$update = "UPDATE users SET costPay='$pay1' WHERE userId=".$_SESSION['user'];
$run_up = mysqli_query($conn,$update);
if($run_up){
echo "<script>alert('This process reservation has successful.')</script>";
echo "<script>window.open('index.php','_self')</script>";
}}
else
{
echo "Error: " . $res . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
From the coding shown is explain about checking the room number, if it reach the max then it will echo the script that room full and open new window to homepage.
if it do not reach the max then it will store those value into table.
but the problem i met now is even the room is full, it still store those value into the table.
May someone help me please?
You are (wrongly) assuming that echo outputs the contents straight away in all cases. It doesn't. Instead it builds up a buffer to output when:
the buffer reaches a certain size, or
when the script stops executing, or
when the buffer is flushed to force an output
As you build the output and don't have any controls around the insert statement, it will always hit that insert statement, which is what it is currently doing.
Fortunately there's a few ways around this:
put an exit; after each block of echo'd script (that will terminate the script and cause the output to happen)
set a variable after the echo parts and check for that before inserting (or not inserting)
Change the control flow so instead of if ... if ... if ... you make use of if...elseif...else, where the else houses the insert statement which will then only run if none of the other conditions matched
There are other ways of doing the same action, but the up-shot is, the script will try not to output anything until it has completed, and part of that includes the insert.

Auto Increment a Variable

I am trying to get the step number to increase with each step that is pulled from the database. Here is my code:
//get the project steps
$ID=mysqli_real_escape_string($con,$_GET['id']);
$projSteps="SELECT project_steps.projectStepDesc,project_steps.projectID FROM project_steps WHERE project_steps.projectID=$ID";
$results1 = mysqli_query($con,$projSteps);
if (!$results1) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
if (mysqli_num_rows($results1) > 0){
echo '<h2>Project Steps:</h2>';
while ($rows = mysqli_fetch_assoc($results1))
{
$a=1;
echo "Step ". $a++ ."<br />";
$psteps=$rows['projectStepDesc'];
echo '<div id="steps">';
echo "$psteps";
echo '</div>';
}}//end project steps
This just outputs Step 1 on each step. I am trying to get it to say Step 1, Step 2, Step 3 ect. How can i do this?
You're declaring the counter inside the while loop. This won't work as, $a = 1; is called each time you loop through and do something. Change:
while ($rows = mysqli_fetch_assoc($results1))
{
$a=1;
To:
$a=1;
while ($rows = mysqli_fetch_assoc($results1))
{
You're setting $a = 1 within your loop each time. Put it outside the loop.
You have put $a=1 outside the while ,other wise when the loops runs value of a gets changes to 1 every time.
$ID=mysqli_real_escape_string($con,$_GET['id']);
$projSteps="SELECT project_steps.projectStepDesc,project_steps.projectID FROM project_steps WHERE project_steps.projectID=$ID";
$results1 = mysqli_query($con,$projSteps);
if (!$results1) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
if (mysqli_num_rows($results1) > 0){
echo '<h2>Project Steps:</h2>';
$a=1;
while ($rows = mysqli_fetch_assoc($results1))
{
echo "Step ". $a++ ."<br />";
$psteps=$rows['projectStepDesc'];
echo '<div id="steps">';
echo "$psteps";
echo '</div>';
}}//end project steps

Using php's count () command to count the result of an if statement

I am trying to work my head round this, I am using the following code to check the answers to a quiz and output either CORRECT or INCORRECT depending on the result of the comparison, and if the answer field is black (which only comes from the feedback form) a different message is displayed.
I cant quite work out how to apply the php count function in this situation though, what im trying to get it to do it count the amount of CORRECT and INCORRECT answers and add the two together, and then I can work out a % score from that.
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.questionID = q.questionID ORDER BY a.cf_id ASC" or die("MySQL ERROR: ".mysql_error());
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}}
?>
Iv found this example and have been trying to work out how to work it in, but cant think how to count the results of an if statement with it ?.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = count($people);
echo $result;
?>
Just increment two counters
$correct_answers = 0;
$incorrect_answers = 0;
while ($row = mysql_fetch_array($result)) {
if ($row['correctanswer'] == '') {...
} elseif ($row['correctanswer'] == $row['quizselectanswer']) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$correct_answers++;
} else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$incorrect_answers++;
}
}
Simply increase some counter in each branch of your if/elseif/else construct...
$counters = array( 'blank'=>0, 'correct'=>0, 'incorrect'=>0 );
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ( ''==$row['correctanswer'] ) {
echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';
$counters['blank'] += 1;
}
elseif ( $row['correctanswer']==$row['quizselectanswer'] ) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$counters['correct'] += 1;
}
else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$counters['incorrect'] += 1;
}
}
echo '#correct answers: ', $counters['correct'];
How about creating a variable with a count of correct answers? For each question you loop through, increment the value by one.
<?php
$correct_answers = 0;
while($questions) {
if($answer_is_correct) {
// Increment the number of correct answers.
$correct_answers++;
// Display the message you need to and continue to next question.
}
else {
// Don't increment the number of correct answers, display the message
// you need to and continue to the next question.
}
}
echo 'You got ' . $correct_answers . ' question(s) right!';
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT ... ";
$result = mysql_query($query) or die(mysql_error());
$countCorrect = 0;
$countIncorrect = 0;
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
$countCorrect++;
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {
$countIncorrect++;
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}
}
echo ((int)($countCorrect/($countIncorrect + $countCorrect) * 100)) . "% answers were correct!" ;
?>

Comparing 2 exact same strings returns false

I have a variable that is posted through a html form:
$_POST['ref']
And a variable that is pulled from a table in a database:
$row['ref']
i have a basic comparison script to check if they are both the same:
$ref = $_POST['ref'];
$result = mysql_query("SELECT * FROM logbook.job");
if (!$result) {
die("Query to show fields from table failed");
}
$row = mysql_fetch_array($result);
$refdb = $row['ref'];
$refform = $_POST['ref'];
echo $_POST['ref'] ."<br>". $row['ref'] . "<br><br>";
if ($refdb == $refform) {
echo "Yes they are<br><br>";
}
else {
echo "No they are not<br><br>";
}
if (is_string($_POST['ref']))
{
echo "Yes";
} else {
echo "No";
}
echo "<br>";
if (is_string($row['ref']))
{
echo "Yes";
} else {
echo "No";
}
Which outputs:
G2mtxW
G2mtxW
No they are not
Yes
Yes
I echo them both out. Than i ask if they are the same. Then i check whether each is a string.
How come they are not the same? How can i get them to match
Any help would be appreciated
Try using the binary-safe comparison for String:
result = strcmp($str1, $str2);
If the result is 0, then both are the same. Otherwise, they aren't.
One of your strings (probably the one from the DB) might be null-terminated. I've tested the following
$foo = "abc\0";
$bar = "abc";
echo "$foo\n$bar\n";
if($foo == $bar)
echo "Equal.";
else
echo "Not equal."
Output is
abc
abc
Not equal.
Try var_dump-ing both values, check their lengths and inspect them using view-source. They are different in someway.
echo $status_message;
echo "Accepted";
if(strcmp($status_message,"Accepted")==0)
{
echo "equal";
}
else
{
echo "not equal";
}
?>
$row['status'] is a field from table

Categories