I am working on a project where I need to read in users (am using MySQL) and be able to sort 1. Men/Women 2. Salary (eg. 30k+, 50k+, 100k+...)
I've tried setting up a select dropdown but for some reason it's showing only the men, even if I select women.
<form action="#" method="post">
<select name="Gender">
<option value=''>Select Gender</option>
<option value="Men">Men</option>
<option value="Women">Women</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
if(isset($_POST['submit']) && $_POST['submit'] = "Men"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
elseif (isset($_POST['submit']) && $_POST['submit'] = "Women"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
else {
print("-");
}
You've assigned the values in the ifs instead of comparing against them. Also, you've used the wrong input to compare against. $_POST['submit'] will always contain the value Get Selected Values.
if (isset($_POST['submit']) && $_POST['Gender'] === "Men") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} elseif (isset($_POST['submit']) && $_POST['Gender'] === "Women") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} else {
print("-");
}
Here's the code a little more simplified and less redundant. And under the assumption that you're using PHPs PDO.
if (strtolower($_SERVER['REQUEST_METHOD']) === 'post') {
$gender = $_POST['Gender'] ?? null; // your old $selected_val variable
if (!$gender) {
// do something to abort the execution and display an error message.
// for now, we're killing it.
print '-';
exit;
}
/** #var PDO $dbConnection */
$dbConnection = create_Conn();
$sql = 'SELECT * FROM users WHERE kon = :gender';
$stmt = $dbConnection->prepare($sql);
$stmt->bindParam('gender', $gender);
$stmt->execute();
foreach ($stmt->fetchAll() as $user) {
if (isset($_SESSION['anvnamn'])) {
// Prints user data
} else {
// Prints user data but emails
}
}
}
As Dan has provided a grand answer prior to mine, this is now just a tack on for something to review.
If you look at your form you have two elements.
On Submission, your script will see..
Gender - $_POST['Gender'] will either be '', 'Men', or 'Women'
Submit - $_POST['submit'] will either be null or the value "Get Selected Values".
It can only be null if the php file is called by something else.
You can see this by using the command print_r($_POST) in your code just before your first if(). This allows you to test and check what is actually being posted during debugging.
So to see if the form is posted you could blanket your code with an outer check for the submit and then check the state of Gender.
The following has the corrections to your IF()s and some suggestions to also tidy up the code a little bit.
<?php
// Process the form data using Ternary operators
// Test ? True Condition : False Condition
$form_submitted = isset($_POST['submit'])? $_POST['submit']:FALSE;
$gender = isset($_POST['Gender'])? $_POST['Gender']:FALSE;
if($form_submitted){
if($gender == 'Men') {
// Stuff here
}
else if($gender == 'Women') {
// Stuff here
}
else {
print("-");
}
} else {
// Optional: Case where the form wasn't submitted if other code is present.
}
You could also consider using the switch / case structure. I'll leave that to you to look up.
Related
A HTML form contain 4 fields (first name, last name, mobile and attendid). This is a search form to find a record in the attend mysql table. All of these fields are optional with intention being that the more fields you enter in the form, you are narrowing down the search. I know that the issue is with the first SQL as it is not taking into account all the variables.
The second bit to confuse it in more... Where results are echoed in a table, the last field of the echoed table should contain data that is selected from the second SQL statement but this data is in another table.
Sorry if anything is vague but I have no idea how to approach this, been looking at it too long!
Thanks so much for you help!
<html>
<body>
<table>
<table border="1">
<tr><th>AttendeeID</th><th>Wristband</th><th>Firstname</th><th>Lastname</th><th>Telephone
</th><th>Mobile</th><th>Address 1</th><th>Address 2</th><th>Town</th><th>Postcode</th><th>
E-Mail</th><th>Medical Notes</th><th>Last Reader Tap</th></tr>
<?php
include "checkmysqlconnect.php";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mobile = $_POST['mobile'];
$attendid = $_POST['attendid'];
$search = $_POST['search'];
if ($search == "Search") {
if ($firstname == '' AND $lastname == '' AND $attendid == '' AND $mobile == '') {
header("Location: searchattendform.php?result=1");
$error = true;
}
if ($error != true) {
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' OR `lastname` = '".$lastname."' OR `attendid` = '".$attendid."' OR `mobile` = '".$mobile."'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
$sql1 = "SELECT `readerid` FROM `taps` WHERE `attendid` = '".$attendid."' ORDER BY `time` DESC LIMIT 1";
$query1 = mysql_query($sql1);
if ($count > 1) {
echo "More than one matching attendee. Entering more details will help narrow down results.";
while($value = mysql_fetch_assoc($query));
while($value1 = mysql_fetch_assoc($query1)) {
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname'].
"</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1'].
"</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email'].
"</td><td>".$value['medical']."</td><td>".$value1['readerid']."</td></tr>";
} } else {
if ($count == 0) {
header("Location: searchattendform.php?result=2");
} else {
if ($count == 1) {
($value = mysql_fetch_assoc($query));
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname'].
"</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1'].
"</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email'].
"</td><td>".$value['medical']."</td><td>".$value1['readerid']."</td></tr>";
} else {
echo "There was an issue searching attendees. Please contact SOFia Admin.";
} }
}
}
}
?>
</table>
</body>
</html>
Take a look at your outer loop while($value = mysql_fetch_assoc($query));.
Shouldn´t this not be while($value = mysql_fetch_assoc($query)){?
I just want to re-select chosen selections after submit a form like..
Here is what's wrong, I have selected first three options
And after submit it's show selected only the last one, i want to see all three selected.
Here is my code
<select multiple name="prod_opt_id[]" class="focusSelect">
<?php
// if (isset($_GET['prod_atr_id'])){
// echo "<option selected value=".$_GET['prod_atr_id'].">Selected</option>";
// }
$sql = "SELECT * FROM `products_options`";
$connect = mysqli_query($db_connect, $sql);
while (($item = mysqli_fetch_array($connect))) {
if ($_POST['prod_opt_id']) {
foreach ($_POST['prod_opt_id'] as $optiun_selct) {
if ($item['prod_opt_id'] == $optiun_selct) {
$slctd = "selected";
} else {
$slctd = "";
}
}
echo "<option ".$slctd." value=".$item['prod_opt_id'].">".$item['prod_opt_name']."</option>";
} else {
echo "<option value=".$item['prod_opt_id'].">".$item['prod_opt_name']."</option>";
}
}
?>
</select>
If you need to see what i use from DB
The problem is that your foreach loop will set $slctd = "selected" when it finds a matching item, but then set it back to "" on the next iteration that doesn't match. So it actually just tests whether the item matches the last entry in $_POST['prod_option_id'], not any entry. Replace the loop with:
UPDATED
if (in_array($item['prod_opt_id'], $_POST['prod_opt_id'])) {
$slctd = "selected";
} else {
$slctd = "";
}
I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}
I'm a complete noob but I have searched everywhere and can't find a solution.
What I have is an array of courses that I pull from my database (e.g.:
maths, art, science). These can change so I must add new courses all the time.
When a user ticks 2 of 3 courses (for example) but fails to add his username, then after the validation I want those 2 checkboxes to keep their old tick, so he must refill only his username in order to proceed.
What I get are all the checkboxes ticked :{
I'm so confused.
<?PHP
$check="unchecked";
?>
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
foreach ($_POST['cid'] as $cid ) {
$check="checked";
}
}
?>
<?PHP
$course_data = "SELECT * FROM course ORDER BY cname";
$get_course = mysql_query($course_data) or die (mysql_error());
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' $check>"; // here are the courses(checkboxes)
}
?>
You have to set your $checked variable independently for each checkbox.
$checkedBoxes = array();
foreach($cid as $id) {
$checkedBoxes[$id] = "checked='false'";
}
foreach ($_POST['cid'] as $cid) {
$checkedBoxes[$cid] = "checked='true'";
}
Then in your loop that outputs the checkboxes, print the corresponding $checked value.
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' {$checkedBoxes[$cid]}>"; // here are the courses(checkboxes)
}
Is this what you want?
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$cid_array = $_POST['cid'];
/*foreach ($_POST['cid'] as $cid ) {
$check="checked";
}*/
}
?>
<?PHP
$course_data = "SELECT * FROM course ORDER BY cname";
$get_course = mysql_query($course_data) or die (mysql_error());
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
if(is_array($cid_array))
{
if(in_array($cid, $cid_array))
{
$check="checked='checked'";
}
else
{
$check="";
}
}
else//it is not array because nothing was checked
{
if($cid == $cid_array)
{
$check="checked='checked'";
}
else
{
$check="";
}
}
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' $check>"; // here are the courses(checkboxes)
}
?>
I have a html page with the form log-in with username and password. When people enter the correct password, it will take them to the php page with their bills. If the password is incorrect, it will display the error message and then exit the program. I got the log-in function to work. However, it's also effecting my other program. Now every time i try to write something in the item/amount row, it also display the error message and exit the program. I know it has something to do with the $numresult>0 condition. When i took that condition out, my amount/item rows work, but the log-in page also allow blank entry in username/password to log in. Any idea how i can make sure that people have to enter the correct password (not a blank entries) to log in, at the same time, get my item/amount rows in the second page behave as normal? My codes are below. Sorry it's a little long.
</head>
<body style="font-family: Arial, Helvetica, sans-serif; color: black;" onload=>
<h1>My Bills</h1>
<form method=post>
<?php
//*************************************************
//Connect to Database
//*************************************************
//*************************************************
//Verify password and username
//*************************************************
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '$userid' AND
password='$password'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
process();
}
}else{
err_msg();
}
//*************************************************
//Error message.
//*************************************************
function err_msg()
{
print "The username and/or password you have entered are invalid.";
print "</body>";
print"</html>";
exit;
}
//*************************************************
//Write out records with data if they exist.
//*************************************************
function process()
{
print "<table>";
print "<tr><th>Item</th><th>Amount</th></tr>";
$action = $_POST['action'];
if ($action == 'update')
{
$write_ctr = 1;
// Delete all rows in the table
$query = "DELETE FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error - Cannot delete from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
// Loop through table and insert values into the database
while (true)
{
$item_name = 'item'."$write_ctr";
$item_value = $_POST[$item_name];
$amount_name = 'amount'."$write_ctr";
$amount_value = $_POST[$amount_name];
if (empty($item_value))
{
break;
}
// Insert an item to the table
if(!is_numeric($amount_value))
{
print "<font color=red>I'm sorry, amount \"".$amount_value."\" is not a valid number.</font><br>\n";
}else{
$query = "INSERT INTO n1417_expenses (item, amount)
VALUES('".$item_value."','".$amount_value."') ";
$result = mysql_query($query);
}
if (mysql_error())
{
echo("<br>MySQL Error - Cannot insert a row into table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
$write_ctr++;
}
}
//*************************************************
//Now Select from table and Display
//*************************************************
$err_cnt = 0;
$read_ctr = 1;
$query = "SELECT item, amount FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error- Cannot select from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
if (!empty($result))
{
$rowresults = mysql_num_rows($result);
if ($rowresults > 0)
{
for ($read_ctr=1; $read_ctr<=$rowresults; $read_ctr++)
{
$row = mysql_fetch_array($result);
$item_value = $row['item'];
$item_name = 'item'."$read_ctr";
$amount_value = $row['amount'];
$amount_name = 'amount'."$read_ctr";
print "<tr>";
print "<td><input type=text name=$item_name value='$item_value'></td>\n";
print "<td><input type=text name=$amount_name value='$amount_value'></td>\n";
print "<td>";
print "</tr>";
$total_amt = $total_amt + $amount_value;
}
}
}
//*************************************************
//Now write the blank lines
//*************************************************
for ($i = $read_ctr; $i < $read_ctr + 2; $i++)
{
$item_name = 'item'."$i";
$amount_name = 'amount'."$i";
print '<tr>';
print "<td><input type=text name=$item_name value=''></td>\n";
print "<td><input type=text name=$amount_name value=''></td>\n";
print '</tr>';
}
print "</table>";
print "<br>Total Bills: $total_amt";
}
?>
<br><input type=submit value=Submit>
<br<br>
<!-- Hidden Action Field -->
<input type=hidden name=action value=update>
</form>
To answer the question posted, your problem appears to be that the username and password being are checked again when your user submits the form. Because the fields don't exist, the query finds zero rows, triggering your error message.
There are a number of ways of fixing your problem, one way would be to use a Session to remember that a user is logged in. This could be implemented by altering your password check as follows:
session_start();
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in'])
{
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '".mysql_real_escape_string($userid)."' AND
password='".mysql_real_escape_string($password)."'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
$_SESSION['logged_in'] = TRUE;
process();
}
}else{
err_msg();
}
}
I've kept the code as similar to the original as possible, but I will echo the comments above on the need to secure your SQL calls. Have a look at using PDO if possible, or at the very least start using mysql_real_escape_string as above.