adding selected attribute to dropdownlist item if is in array - php

I have code table like this.
code
00
01
02
03
I'm adding this codes as array from dropdown list to assigned_code column in the user table.
assigned_code
00,02,03
When I want to edit the codes assigned to the user, I need to add selected attribute which codes are assigned previously in dropdown list. I'm stuck at this point. Can anyone show me the how to do this?
<?php
$assigned_code = array();
$sql = "select assigned_code from user where ID=1";
$rq = mysqli_query($conn, $sql);
$count = mysqli_num_rows($rq);
if ($count>0) {
while ($row = mysqli_fetch_array($rq)) {
$assigned_code=$row["$assigned_code"];
}
}
?>
<select name="u_codes[]" id="u_codes" class="selectpicker" multiple="multiple">
<?php
$sql = "select code,desc from codes";
$rq = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($rq)) {
$code = $row["code"];
$codeDesc = $row["desc"];
if ($assigned_code == $code) {
echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
} else {
echo '<option value="'.$code.'">'.$codeDesc.'</option>';
}
}
?>
</select>

try using array_push to items
array_push($assigned_code,$row["$assigned_code"]);
because every time you use $assigned_code=$row["$assigned_code"];
you erase the existing value inside $assigned_code
and debug it with var_dump() it will give you a clear information about the data and it's type.

$assigned_code = array();
$assigned_code=$row["$assigned_code"];
$expArr = explode(',',$assigned_code);
if (in_array($code,$expArr)) {
echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
} else {
echo '<option value="'.$code.'">'.$codeDesc.'</option>';
}
in_array perfectly worked for me.

Related

How do i get record in a dropdown list based on a first drop down list in php ajax request

Php ajax request not working even though the onchange function seems to be working.
Initially the get_data.php was in a folder different from the parent folder. I moved it to the same folder but still not working.
//html select option
<select name="slct" id="slct1">
<option selected disabled>----Choose Class ----</option>
<?php
$query = "SELECT * FROM classes ";
//GET RESULT
$result = $pdo->query($query);
$result->setFetchMode(PDO::FETCH_ASSOC);
while($row = $result->fetch()){
?>
<option value="<?php echo $row['class_name']?>"><?php echo $row['class_name']?></option>
<?php
}
?>
<select name="slct" id="slct2" >
<option selected disabled>----Select Student----</option>
</select>
//ajax request
<script type="text/javascript">
$(document).ready(function(){
$('#slct1').on('change',function(){
var StudentID = $(this).val();
if(StudentID){
$.ajax({
type:'POST',
url:'get_data.php',
data:'class_name='+StudentID,
success:function(html){
$('#slct2').html(html);
}
});
}else{
$('#slct2').html('<option value="">Select Class First</option>');
}
});
});
</script>
//get_data.php
<?php
//Include the database configuration file
include '../config/dbconfig.php';
if(isset($_POST["class_name"])){
//Fetch all state data
$query = "SELECT * FROM students WHERE class = ".$_POST['class_name']." ORDER BY id ASC";
//Count total number of rows
$result = $pdo->query($query);
$result->setFetchMode(PDO::FETCH_ASSOC);
$rowCount = $result->num_rows;
//State option list
if($rowCount > 0){
echo '<option value="">Select Student</option>';
while($row = $result->fetch()){
echo '<option value="'.$row['class'].'">'.$row['firstname']. $row['middlename'] . $row['lastname']. '</option>';
}
}else{
echo '<option value="">No Student Registered</option>';
}
}
?>
I want to get student records in the second select option when class is selected.
As mentioned in the comment - it looks like the issue might be dues to lack of quotes around the POST variable in the SQL query. This would not have been an issue had you used a prepared statement and bound the POST variable to a placeholder - the added benefit is of course greater protection from SQL injection.
<?php
if( isset( $_POST['class_name'] ) ){
include '../config/dbconfig.php';
$sql = 'select * from `students` where `class` = :classname order by id asc';
$args = array(
':classname' => $_POST['class_name']
);
$stmt=$pdo->prepare( $sql );
if( $stmt ){
$result=$stmt->execute( $args );
if( $result && $stmt->rowCount() > 0 ){
echo '<option selected hidden disabled>Select student';
while( $rs=$stmt->fetch( PDO::FETCH_OBJ ) ){
printf('<option value='%s'>%s %s %s', $rs->class, $rs->firstname, $rs->middlename, $rs->lastname );
}
} else {
echo '<option selected hidden disabled>No student registered';
}
} else {
exit( '<option selected hidden disabled>error' );
}
}
?>

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.

Select all data after selecting another option

I am trying to create a submission on a form where I can show all results from a table as well as show individual results. I can achieve the page load to show all until the form is submitted, however when I then try and select all again im struggling.
On page load im simply doing:
<?php
if (isset($_POST['submit'])) {
$teamData = $_POST['teamData'];
var_dump($teamData);
$sql = "SELECT * FROM team WHERE dashboardId = 1 AND id = $teamData";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$teamName = $row['name'];
}
}
} else {
$teamName = 'All';
echo 'no submission yet';
}
?>
Setting the variable to say 'all'
<p>Team: <?php echo $teamName; ?></p>
Once an option has been selected it check the database and uses the name of and sets it. However in the dropdown list if i want to show all results again i get an error of:
Undefined variable: teamName
which makes sense because of my form:
<form method="POST" action="">
<select name="teamData">
<option selected value="" disabled>Select your team</option>
<option value="allTeamData">All team data</option>
<?php teamMembers(); ?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
I am just struggling to understand the logic of how to select all again from the drop down.
$teamName = 'All'; // Initialise the variable at top
// Change the condition to this for better restriction
if ($_POST && isset($_POST['submit'])) {
$teamData = $_POST['teamData'];
var_dump($teamData);
$sql = "SELECT * FROM team WHERE dashboardId = 1 AND id = $teamData";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$teamName = $row['name'];
}
}
}

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

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

Categories