Trouble with retrieving data from mysql with HTML select box - php

Okay so I am developing a search engine for a non-profit group using MYSQL and PHP. The data appears fine from all the other fields. But when I try to get data from a drop down select box the data doesn't appear.
I know my code is pron to SQL injections however there isn't any important data kept on the server, it just info about treatments and research studies.
I would like to do it with a function. I was also wondering if there is anyway to retrieve data from multiple boxes. Like I have a keyword search and a drop down combo box both of them are set. How do I retrieve data from both columns in the database using the function I have? Thanks
Here is my code if you guys could help me that would be great thanks
The code for the html box
Broad Research Topic <select name="Treatment1">
<option value="Other">
Other
</option>
<option value="Treatment">
Treatment
</option>
<option value="PracticalCure">
Practical Cure
</option>
The php code to check if it is set
if (isset($_GET['Treatment1']) && in_array($_GET(['Treatment1']),
array('Treatment', 'PracticalCure', 'Other')) {
$state = $_GET['Treatment1'];
Investigator6($state); }
}
The Function Investigator6
function Investigator6($state)
{
$state = trim($state);
$state = preg_replace('/\s+/', ' ', $state);
//seperate multiple keywords into array space delimited
$keywords = explode(" ", $state);
//Clean empty arrays so they don't get every row as result
$keywords = array_diff($keywords, array(
""
));
//Set the MySQL query
if ($state == NULL or $state == '%') {
} else {
for ($i = 0; $i < count($keywords); $i++) {
$query = ("SELECT * FROM Studies1 WHERE BroadResearchTopic LIKE
' %$keywords[$i]%'");
}
//Store the results in a variable or die if query fails
$result = mysql_query($query) or die(mysql_error());
}
if ($state == NULL or $state == '%') {
} else {
//Count the rows retrived
$count = mysql_num_rows($result);
echo $count;
}
//If search variable is null do nothing, else print it.
if ($state == NULL) {
} else {
echo "You searched for <b><FONT COLOR=\"blue\">";
foreach ($keywords as $value) {
print "$value ";
}
echo "</font></b>";
}
echo "<p> </p><br />";
echo "</center>";
//If users doesn't enter anything into search box tell them to.
if ($state == NULL) {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
b</font></b><br /></center>";
} elseif ($state == '%') {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
</font></b><br /></center>";
//If no results are returned print it
} elseif ($count <= 0) {
echo "<center><b><FONT COLOR=\"red\">Your query returned no results from the
database.</font></b><br /></center>";
//ELSE print the data in a table
} else {
//Table header
echo "<center>";
echo "</center>";
//Colors for alternation of row color on results table
$color1 = "#d5d5d5";
$color2 = "#e5e5e5";
//While there are rows, print it.
while ($row = mysql_fetch_array($result)) {
//Row color alternates for each row
$row_color = ($row_count % 2) ? $color1 : $color2;
//table background color = row_color variable
echo "<td style = \"padding: 10px\">" . $row['BroadResearchTopic'] . "</td>";
$row_count++;
if ($state == NULL or $state == '%') {
} else {
//clear memory
mysql_free_result($result);
}
}

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>";
}

Append data and display html table

I have some data set. I want to arrange data like this:
My code displays result like this:
.
How can I fix this. This is my code:
<?php
echo "<tr><th></th><th>Control</th><th>Sub 1</th><th>Sub2</th></tr>";
$i=0;
$PrevIssoff=0;
$sql="SELECT `code`, `name`,`type`
FROM `testdate`
WHERE `code`='11111'
ORDER BY `code` ASC, `type` ASC ";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$frm=$row['code'];
if ($frm != $PrevIssoff && $row['type']==0)
{
$i=$i+1;
$PrevIssoff=$frm;
echo "<tr><td>$i</td><td>$row[name]</td><td></td><td></td></tr>";
}
else if($row['type']==1 )
{
echo "<tr><td></td><td></td><td>$row[name]</td><td></td></tr>";
}
else if ($row['type']==2)
{
echo "<tr><td></td><td></td><td></td><td>$row[name]</td></tr>";
}
}
echo"</table>";
?>
Database table structure - testdate
databasetable
First, your data needs to be normalized. There should be a way to write a database query to skip this step if you look hard enough.
Walkthrough each row in the while loop, building a close representation for it an array.
$dataTable = [];
while ($row = mysqli_fetch_array($result)) {
$numRows = count($dataTable);
$lastRowIndex = $numRows == 0 ? 0 : $numRows-1;
if($numRows == 0) {
$dataTable[] = [];
}
if(count($dataTable[$lastRowIndex]) == 3) {
$dataTable[] = [];
$lastRowIndex += 1;
}
$type = $row['type'];
$dataTable[$lastRowIndex][$type] = $row['name'];
}
Then make your $rowsMarkup which can be readily concatenated with the table heading.
$rowsMarkup = array_map(function($row) {
return '<tr>'.
'<td>'.$row[0] .'</td>'.
'<td>'.$row[1] .'</td>'.
'<td>'.$row[2] .'</td>'.
'</tr>';
},
$dataTable
);

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.

How to display php script output in column wise based on the match in if statement

I have the following PHP code which will print the server names with different color codes likes Green-Ok,Yellow-warning,Red-critical,Orange-unknown.
foreach ($status->members_with_state as $server) {
if ($server[1] == 0) {
$state = "OK";
echo "Server: <font color=\"green\">$server[0]</font><br />";
} elseif ($server[1] == 2) {
$state = "WARNING";
echo "Server: <font color=\"yellow\">$server[0]</font><br />";
} elseif ($server[1] == 1) {
$state = "CRITICAL";
echo "Server: <font color=\"red\">$server[0]</font><br />";
} elseif ($server[1] == 3) {
$state = "UNKNOWN";
echo "Server: <font color=\"orange\">$server[0]</font><br />";
}
}
ISSUE:
All the servers are printed in one big list in a single column.
Could you please suggest required modifications in code to get the server names column wise like in attached screenshotenter image description here

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!" ;
?>

Categories