php retain an array checkbox - php

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)
}
?>

Related

Dropdown to read in and sort users with PHP

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.

Comparing stored data in a column to an existing value

I have a column called favid. I am trying to pull and compare the data in that column to an existing value:
<?php $query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid=$favid");
while ($row = mysql_fetch_assoc($query)) {
echo $row['favid']; };?>
I also have an existing value:
$x
But when I do something like this it doesn't work:
<?php if($row['favid'] == $x){?>
Do this...
<?php } else { ?>
Do nothing...
<?php}?>
I realize the data in the column somehow isn't pulled out. What should be done for this to work?
Try this, I assume you already connected to DB.
<?php
$x = 1;
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid='$favid'") or die(mysql_error());
if (mysql_num_rows($query) > 0)
{
while ($row = mysql_fetch_assoc($query))
{
if ($row["existing_column_name"] == $x)
{
echo "Yes";
} else
{
echo "No";
}
}
} else
{
echo "Nothing was found";
}
?>
<?php
$x = 100500; // integer for example
$CID = mysql_connect("host","user","pass") or die(mysql_error());
mysql_select_db("db_name");
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid='{$favid}'", $CID);
while ($row = mysql_fetch_assoc($query)) {
if (intval($row["some_existing_column_name"])==$x){
print "Is equals!";
} else {
print "Is different!";
}
}
?>
Please be informed that mysql_connect and other functions with the prefix of mysql_ is deprecated and can be removed in the next versions of PHP.

Reselect with $_POST after submit

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

Button submit, gets the other buttons from the database

This is my code so far:
require_once 'functions.php';
// makes the connection to the server to get the state button names
$query = "SELECT state FROM state";
$result = $connection->query($query);
if ($result === false) {
// error mssg
echo "<p>Query fout.</p>";
}
// button of the state gets the buttons of the city
if (isset($_POST['state'])) $state = $_POST['state']; {
query = "SELECT city FROM city='$cityid'";
$result = $connection->query($query);
} if ($result === false) {
// geef nette foutmelding
echo "<p>Query fout.</p>";
}
<?php
//gives the result to Submit html
while ($row = $result->fetch_assoc()) {
echo "<input type ='submit' name='provincie' value='".$row['provincie']."'>";
}
$result->free();
?>
</for
I would like to have a form submit button that gives a variable to PHP, depending on that variable, other buttons are created in the same form. So you can select a country and than you can select the cities in that country. I have the first button up and running. I thought I could just use the same submit button with the same variables. Because php would just rewrite the variables if there is a new input. But I think its not that simple, I don't know how to Google this question or that it is even something I should do with PHP instead of JavaScript/jQuery and just let the buttons hide and display and only use the last one to give an input with PHP.
you need to do the query result separately, so there should be two while statements
not the best way but here is one way i would do it:
require_once 'functions.php';
$query = "SELECT state FROM state";
if($query->num_rows > 0){
while($row= $result->fetch_assoc()) {
echo "<input type ='submit' name='provincie' value='".$row['provincie']."' onclick="sendVal(this.value)" >";
}
}
<script type="text/javascript">
function sendVal(item) {
document.cookie="city=" + item + ";";
location.reload();
}
</script>
<?php
if(!is_null($_COOKIE['city'])){
$retrievedcities= "SELECT city FROM city WHERE city ='".$_COOKIE['city']."'";
$con->query($retrievedcities);
while ($row = $result->fetch_assoc()) {
echo "<input type ='submit' name='citybut' value='".$row['city']."'>";
}
unset($_COOKIE['city']);
}
?>

Instant search using jQuery is giving all the fields if nothing is typed in search box

This is the PHP code of my main search section.
This search is working fine except in one case: When nothing is typed in the search box, it returns all values from the table.
How can I fix that?
<?php
mysql_connect("localhost","root","0392") or die("Could not connect");
mysql_select_db("emm") or die("could not connect");
$output="";
if(isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query=mysql_query("select name, code from employee_table where name LIKE '%$searchq%' or code LIKE '%$searchq%'");
$count = mysql_num_rows($query);
if($count == 0){
$output='No Matching Results Found !!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$code= $row['code'];
$output.="<a href='altprofile.php?cod=".$code."'><div class='col-md-3'><input type='text' name='nam' disabled='disabled' value='".$name."'></input></div></a> ";
}
}
}
echo($output);
?>
Just use
if(isset($_POST['searchVal']) && !empty($_POST['searchVal'])){
// DO code
}else{
echo "no results";
}
Try this
...
if(isset($_POST['searchVal']) && $_POST['searchVal'] != ''){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query=mysql_query("select name, code from employee_table where name LIKE '%$searchq%' or code LIKE '%$searchq%'");
$count = mysql_num_rows($query);
if($count == 0){
$output='No Matching Results Found !!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$code= $row['code'];
$output.="<a href='altprofile.php?cod=".$code."'><div class='col-md-`enter code here`3'>`enter code here`<input type='text' name='nam' `enter code here`disabled='disabled' value='".$name."'></input></div></a> ";
}
}
}
...
Note: Don't use mysql use mysqli or PDO
Just do the following two things,change if condition as
//checks value is not empty
if(isset($_POST['searchVal']) && !empty($_POST['searchVal']))
{
//all your stuff
}
else
{
echo "No results"
}

Categories