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 = "";
}
Related
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.
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.
I've been using mysql and it did what I want, but as my project is getting larger, I decided to opt for mysqli.
I looked at the tutorial at enter link description here which was really straight forward up until the point where I want to display some data
stored procedure (connect.php)
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $con;
// Try and connect to the database, if a connection has not been established yet
if(!isset($con)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('config.ini');
$con = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if( $con === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $con;
}
function db_query($query) {
// Connect to the database
$con = db_connect();
// Query the database
$result = mysqli_query( $con,$query);
return $result;
}
function db_error() {
$con = db_connect();
return mysqli_error($con);
}
function db_select($query) {
$rows = array();
$result = db_query($query);
// If query failed, return `false`
if($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
function db_quote($value) {
$con = db_connect();
return "'" . mysqli_real_escape_string($con,$value) . "'";
}
?>
php/html
<div class="grid_4">
<div class="left-1">
<h2 class="top-1 p3">Find a property</h2>
<form id="form-1" method="post" class="form-1 bot-1" action="prop_result.php">
<div class="select-1">
<label>Select Area</label>
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}else
{
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}}
?>
</select>
</div>
What I don't understand is how to use the stored procedure in a while loop so it will output the data in the fields ID and Area so my select box and any other input can be properly populated based on the query
current
I've tried different ways :
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
<?php
$rows = db_select("SELECT area_id from property");
if($rows === false) {
$error = db_error();
}
{
echo "<option value='".$rows['id']."'>".$rows[$col4]."</option>";
}
?>
None of these output any data. Echoing $rows gives no data. I don't know what the logic is for using the stored procedure to display the output.
Any help would be appreciated, if any other information is required to assist in resolving this issue, please let me know.
Awesome to hear that the data is returning. Try this out for size...
foreach($rows as $key => $value){
foreach($value as $k => $v){
if($k == 'id'){
$newID = $v;
}
if($k == 'type'){
$newType = $v
}
}
echo "<option value='".$newID."'>".$newType."</option>";
}
with this you should be able to make it work for you liking.
Edit: Didnt see the additional arrays until later...the nested loop should suite you better.
Siniseus way works but its too much code for a simple task. I did work with it to finally come to this
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id, city_id,area FROM area");
foreach($rows as $row){
echo "<option value='".$row['id']."'>".$row['area']."</option>";
}
?>
</select>
Simple, clean and really straight forward without too many variables.
$rows = db_select ("Select Query")foreach($rows as $row){
do this
}
I can't insert my data in mysql when count value in column No_KP when row No_KP is empty
<?php
session_start();
include ("../Connections/connection_db.php");
include ("../Connections/db_connect.php");
$no_kp = '765454104321';
$id = '101';
mysql_select_db($database_connection_db, $connection_db);
$query_viewAduan = mysql_query("SELECT No_KP, COUNT(*) FROM aduan_tidak_hadir WHERE No_KP LIKE '%".$no_kp."%' GROUP BY No_KP;");
while ($row = mysql_fetch_array($query_viewAduan))
{
if (!$row['COUNT(*)'])
{
echo 'satu';
}
else if ($row['COUNT(*)'] == '1')
{
echo 'dua';
}
else if ($row['COUNT(*)'] == '2')
{
echo 'tiga';
}
}
?>
my problem is that I can't display when the column is empty, but when the column have any value the data it can be displayed
sorry for my poor english...i wanna to update my question...
what i want to do is before i add an value in my database this function will do is count that value what i insert if that value is not inside my database so that this function will add the value inside my database and count it to 1.if that value already at the database this function will count and show it to 2 when the same value insert on second time and also same when the same value insert at the third time will show it to 3
Untested: Assume that you want to know if something has been 'echoed' or not...
This line of code...
$row = mysql_fetch_array($query_viewAduan);
$row will be an 'empty' array if 'no rows returned'. Therefore the 'while' loop will not be entered.
<?php
session_start();
include ("../Connections/connection_db.php");
include ("../Connections/db_connect.php");
$no_kp = '765454104321';
$id = '101';
mysql_select_db($database_connection_db, $connection_db);
$query_viewAduan = mysql_query("SELECT No_KP, COUNT(*) FROM aduan_tidak_hadir WHERE No_KP LIKE '%".$no_kp."%' GROUP BY No_KP;");
$somethingEchoed = false;
while ($row = mysql_fetch_array($query_viewAduan))
{
$somethingEchoed = true;
if (!$row['COUNT(*)'])
{
echo 'satu';
}
else if ($row['COUNT(*)'] == '1')
{
echo 'dua';
}
else if ($row['COUNT(*)'] == '2')
{
echo 'tiga';
}
}
if (!$somethingEchoed) {
// do 'nothing echoed' processing here
}
?>
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)
}
?>