PHP for loop count from select list - php

I am working on a project and am still relatively new to PHP. I am attempting to run a for loop which counts the number of times each flower is selected from a select list off of an HTML page. I am continuously getting "1" for all 3 flower types after choosing different combinations from the select lists during testing. If anyone has any input as to where my mistakes are I would greatly appreciate it! Here is my HTML code:
<html>
<head>
</head>
<body>
<h1>FLOWERS</h1>
<form action = 'php 08.php' method = 'post'>
<select id = '0' name = '0'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<select id = '1' name = '1'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<select id = '2' name = '2'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<select id = '3' name = '3'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<select id = '4' name = '4'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<input type = 'submit' id = 'go' value = 'COUNT'>
</form>
</body>
</html>
Here is my PHP code:
<?php
$marigold = $_POST['marigold'];
$rose = $_POST['rose'];
$tulip = $_POST['tulip'];
for ($i = 0; $i <= 4; $i++) {
if ($i == 'marigold') {
$marigold++;
};
if ($i == 'rose') {
$rose++;
};
if ($i == 'tulip') {
$tulip++;
};
};
echo "MARIGOLD <span id = 'marigold'>$marigold</span>";
echo "<br><br>";
echo "ROSE <span id = 'rose'>$rose</span>";
echo "<br><br>";
echo "TULIP <span id = 'tulip'>$tulip</span>";
?>

If you want to keep your HTML like this, your PHP code should be like that:
//Initialise your counter
$marigold=$rose=$tulip=0
for ($i = 0; $i <= 4; $i++) {
if ($_POST[$i] == 'marigold') {
$marigold++;
}
if ($_POST[$i] == 'rose') {
$rose++;
}
if ($_POST[$i] == 'tulip') {
$tulip++;
}
}
echo "MARIGOLD <span id = 'marigold'>$marigold</span>";
echo "<br><br>";
echo "ROSE <span id = 'rose'>$rose</span>";
echo "<br><br>";
echo "TULIP <span id = 'tulip'>$tulip</span>";

Related

Validation for multiselect using PHP

I have a multiple select on my code, what I need to do is to have a validation when the user click the submit button without selecting any of the given list.
Here's the sample code:
index.php
<?php
IF(isset($_POST['Rtype'])){
$RetrieveType = $_POST['Rtype'];
IF($RetrieveType == 'date_range'){
$start_date = new DateTime($_POST['start_date']);
$sd = date_format($start_date,'Y-m-d');
$p_week=array();
$m_month=01;
$end_date = new DateTime($_POST['end_date']);
$end_date-> add(new DateInterval('P1D'));
$ed =date_format($end_date,'Y-m-d');
}
ELSEIF($RetrieveType == 'weekly'){
$p_week = $_POST['week'];
$m_week = implode(',',$p_week);
$m_month =$_POST['month_m'];
$m_year =$_POST['year_m'];
$p_lob = $_POST['lob'];
$sc_lob=implode(',',$p_lob);
} ELSE
{
$RetrieveType = 'date_range';
$sd = date('Y-m-01');
$start_date = date('Y-m-01');
$ed = date('Y-m-d');
$end_date = date('Y-m-d');
$m_month=date ('m');
$p_week=array();
$m_year= date ('Y');
$sc_lob='';
}
?>
<html>
<head>
<head>
<body>
<form action="index.php" method="POST" class="form-inline">
<label for="sel1">Week:</label>
<select data-placeholder="<?php echo (isset($_POST['week']) ? "Week/s Currently Selected: ".implode(",",$_POST['week']) : "Select Week"); ?>"
class="chosen-select" multiple tabindex="4" style="width:350px;" name= "week[]">
<option value="1" id="empty">Week 1</option>
<option value="2" id="empty">Week 2</option>
<option value="3" id="empty">Week 3</option>
<option value="4" id="empty">Week 4</option>
<option value="5" id="empty">Week 5</option>
</select>
<label for="sel1">LOB:</label>
<select data-placeholder="<?php echo (isset($_POST['lob']) ? "LOB/s Currently Selected: ".implode(",",$_POST['lob']) : "Select LOB"); ?>"
class="chosen-select" multiple tabindex="4" style="width:350px;" name= "lob[]">
<?php
$lob = array();
$q = "SELECT distinct LOB from roster where EmployStatus='active' and SDLead <> '' group by LOB";
$params = array();
$query = sqlsrv_query($conn, $q);
while($rowsss= sqlsrv_fetch_array($query)) {
$lob = $rowsss['LOB'];
echo "<option value='".$lob."'>".$lob."</option>";
}
for ($i = 0; $i <= count($lob) - 1; $i++) {
IF($sc_lob == $lob[$i])
{$isSelected = 'selected';}
elseif(1==1)
{$isSelected='';}
echo "<option ".$isSelected." value='".$lob[$i]."'>".$lob[$i]."</option>"; }
?>
<input type="hidden" name="Rtype" value="weekly">
<input class="btn btn-primary" type="submit" />
</form>
What I wanted to achieve is when the user clicked the submit button without selecting any on the "Week" list or "LOB" list, there would be an error message that says "This field is required, select at least one.". Actually I already did this before, when I'm just using a checkbox. I placed the code below after the label tag:
sample code:
<?php
if(isset($_GET['err']))
{
$err = $_GET['err'];
if($err == 1)
{
echo "<span class='text-danger'>* This field is required, select at least one.</span>";
}
else
{
echo "";
}
}
else
{
echo "";
}
?>
Try this
if(isset($_POST['submit']){
errors = 0;
if($_POST['nameOfSelect'] == ""){
errors++;
}
if(errors == 0){
return true;
}else{
return false;
}

How to make a list filled from database visible in php?

I am taking the values of the course and the semester,and searching in database for the instructors who teach the course at that semester,It worked. But I want the values to be shown in a list after submitting it, I want the list to appear only after submitting.Then I want to choose from the list an instructor and add him in database with the course and the semester selected first,without re selecting them.Please help..
<?php
session_start();
$_SESSION['courses'] = $_SESSION['semester'] = $coursechosen = $semesterchosen = "";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
error_reporting(E_ALL ^ E_NOTICE);
require_once 'connect.php';
$semester = "";
$courses = $_GET['courses'];
$sem = $_GET['sem'];
$semyr = $_GET['semyr'];
$semester = $sem . $semyr;
if (isset($_GET['courses']) && isset($_GET['sem']) && isset($_GET['semyr'])) {
$_SESSION['courses'] = $courses;
$_SESSION['semester'] = $semester;
$instructors = mysql_query("select Instructor_Id from teach where
Semester='$semester' AND course_code='$courses' ");
if (!$instructors) {
die("Database access failed: " . mysql_error());
}
$row = mysql_num_rows($instructors);
}
}
?>
<?php
$instructor = $_GET['instructor'];
if (isset($_SESSION['courses']) && isset($_SESSION['semester'])) {
$coursechosen = $_SESSION['courses'];
$semesterchosen = $_SESSION['semester'];
$query = "Insert INTO coordinators(instructor_id,course_code,semester)
VALUES ('$instructor','$coursechosen','$semesterchosen')";
// $query="Insert INTO instructors(Fname)VALUES('$instructor')";
mysql_query($query);
}
?>
<form method="get" action="Chairman.php" onsubmit="return
validate()">
<select name="courses" id="courses" >
<option value="courses"><--Courses--></option>
<option value="PHYS220">Physics for Engineers</option>
<option value="MATH210">Calculus II</option>
<option value="MATH225">Linear Algebra with Applications</option>
</select>
<select name="sem" id="sem" >
<option selected="selected">Season</option>
<option value="Fall">Fall</option>
<option value="Spring">Spring</option>
<option value="Summer">Summer</option>
</select>
<select name="semyr" id="semyr" >
<option>Year</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<div> <input type="submit" value="Submit" ></input></div>
<div>
<select name="instructor">
<?php
if ($row !== 0) {
for ($i = 0; $i < $row; ++$i) {
$instructor_id = mysql_fetch_array($instructors);
$instructorsname = mysql_query("select * from instructors where
Id='$instructor_id[0]'");
$rowname = mysql_num_rows($instructorsname);
$instructorsnames = mysql_fetch_array($instructorsname);
echo "<option
value='$instructorsnames[0]'>" . $instructorsnames['Fname'] . "
" . $instructorsnames['Lname'] . "</option>";
}
}
?>
</select>
</div>
</form>
</body>
</html>
mysql_fetch_array returns an array with your data. So, to show instructors, you have to iterate through your list and write them out. Try:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<option value='$row['id']'>".$row['Fname']."
".$row['Lname']."</option>";
}
That should give you a list of option. But I'm not quite sure if I understood what your question is. If that doesn't answer it, could you be more specific?

Database does not get updated, But no error appears. MySQL and PHP

I'm making a website for a friend and basically I have 15 fields that are editable depending on the user type. Basically my code is echoing the row out on to the field, but when when I go to change it and update the database nothing happens. I don't receive any error messages, so i'm thinking it's something to do with my condition statements. My functions work fine, how ever my query doesn't seem to like me.
<?php
//end of function
}
// connect to the database
$server = 'localhost';
$user = 'root';
$pass = '';
$database = 'bubbles';
//Connect to the database
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
//Select the database name
$select = mysql_select_db($database) or die ("Could not connect to database ... \n" . mysql_error ());
// check if the form has been submitted. If it has, process the form and save it to the database
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
//Get form data to make sure it's valid
$id = $_POST["id"];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$dueDate = mysql_real_escape_string(htmlspecialchars($_POST['dueDate']));
$numOfPages = mysql_real_escape_string(htmlspecialchars($_POST['numOfPages']));
$numOfCopies = mysql_real_escape_string(htmlspecialchars($_POST['numOfCopies']));
$paperSize = mysql_real_escape_string(htmlspecialchars($_POST['paperSize']));
$paperColor = mysql_real_escape_string(htmlspecialchars($_POST['paperColor']));
$weight = mysql_real_escape_string(htmlspecialchars($_POST['weight']));
$finishing = mysql_real_escape_string(htmlspecialchars($_POST['finishing']));
$paymentMethod = mysql_real_escape_string(htmlspecialchars($_POST['paymentMethod']));
$printColor = mysql_real_escape_string(htmlspecialchars($_POST['printColor']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
$comment = mysql_real_escape_string(htmlspecialchars($_POST['comment']));
// check that firstname/lastname fields are both filled in
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '' || $comment == '')
{
// generate error message
$error = 'Please fill in all required fields!';
//error, display form
displayForm($id,
$name,
$dueDate,
$numOfPages,
$numOfCopies,
$paperSize,
$paperColor,
$weight,
$finishing,
$paymentMethod,
$printColor,
$comment,
$status,
$error);
}
else
{
//Insert form data into the database or die if there is an error
print $sql;
$sql = ("UPDATE orders SET `name` = '".$name."',
due_date = '".$dueDate."',
numOfPages = '".$numOfPages."',
numOfCopies = '".$numOfCopies."',
paper_size = '".$paperSize."',
paper_color = '".$paperColor."',
weight = '".$weight."',
finishing = '".$finishing."',
payment_method = '".$paymentMethod."',
color = '".$printColor."',
comments = '".$comment."',
`status` = '".$status."' WHERE id = '".$id."'");
$result = mysql_query($sql) or die (mysql_error());
// once saved, redirect back to the view page
header("Location: http://localhost/Bubbles/view-orders.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
{
// if the form hasn't been submitted, get the data from the db and display the form
// get the 'id' value from the URL (if it exists), making sure that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM orders WHERE id = '$id'") or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$id = $row['id'];
$name = $row['name'];
$dueDate = $row['due_date'];
$numOfPages = $row['numOfPages'];
$numOfCopies = $row['numOfCopies'];
$paperSize = $row['paper_size'];
$paperColor = $row['paper_color'];
$weight = $row['weight'];
$finishing = $row['finishing'];
$paymentMethod = $row['payment_method'];
$printColor = $row['color'];
$status = $row['status'];
$comment = $row['comments'];
// show form
displayForm($id,
$name,
$dueDate,
$numOfPages,
$numOfCopies,
$paperSize,
$paperColor,
$weight,
$finishing,
$paymentMethod,
$printColor,
$comment,
$status,
'');
}
else
{
// if no match, display result
echo "No results!";
}
}
else
{
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
Updated with HTML
<html>
<head>
</head>
<body>
<form action"" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div class="floatLeft">
<p>Name: <br /> <input type="text" name="name" value="<?php echo $name; ?>"/></p>
<p>Due Date (ex: yyyy-mm-dd): <br /> <input type="datetime" name="dueDate" value="<?php echo $dueDate; ?>" /></p>
<p># of Pages <br /> <input type="number" name="numOfPages" value="<?php echo $numOfPages; ?>"/></p>
<p># of Copies <br /> <input type="number" name="numOfCopies" value="<?php echo $numOfCopies; ?>"/></p>
</div>
<div class="floatLeft">
<p>Paper Size<br />
<select name = "paperSize" value="<?php echo $paperSize; ?>">
<option value="8.5 x 11in">8.5 x 11 inches</option>
<option value="8.5 x 14in">8.5 x 14 inches</option>
<option value="11 x 17in">11 x 17 inches</option>
</select>
</p>
<p>Paper Color<br />
<select name = "paperColor" value="<?php echo $paperColor; ?>">
<option value = "pulsar pink">Pulsar Pink</option>
<option value = "fireball fuchsia">Fireball Fuchsia</option>
<option value = "plasma pink">Plasma Pink</option>
<option value = "re-entry red">Re-entry Red</option>
<option value = "rocket red">Rocket Red</option>
<option value = "cosmic orange">Cosmic Orange</option>
<option value = "galaxy gold">Galaxy Gold</option>
<option value = "solar yellow">Solar Yellow</option>
<option value = "venus violet">Venus Violet</option>
<option value = "planetary purple">Planetary Purple</option>
<option value = "celestial blue">Celestial Blue</option>
<option value = "lunar blue">Lunar Blue</option>
<option value = "gamma green">Gamma Green</option>
<option value = "martian green">Martian Green</option>
<option value = "terra green">Terra Green</option>
<option value = "lift-off lemmon">Lift-off Lemon</option>
</select>
</p>
<p>Weight<br/>
<select name = "weight" value="<?php echo $weight; ?>">
<option value="20lbs">20lbs</option>
<option value="60lbs">60lbs</option>
<option value="65lbs">65lbs</option>
</select>
</p>
<p>Finishing<br />
<select name = "finishing" value="<?php echo $finishing; ?>">
<option value="none">None</option>
<option value="cutting">Cutting</option>
<option value="folding">Folding</option>
<option value="quaters">Quaters</option>
<option value="binding">Bindings</option>
</select>
</p>
<p>Payment method<br />
<select name = "paymentMethod" value="<?php echo $paymentMethod; ?>">
<option value="Cash">Cash</option>
<option value="Credit">Credit</option>
<option value="Check">Check</option>
<option value="Wilscard">Wilscard</option>
</select>
</p>
<p>Print BW/C<br />
<select name = "printColor" value="<?php echo $printColor; ?>">
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Color">Color</option>
</select>
</p>
</p>
</div>
<div class="floatLeft">
<p>Status<br />
<select name = "status" value="<?php echo $row['status']; ?>">
<option value="Recieved">Received</option>
<option value="In Progress">In Progress</option>
<option value="Completed">Completed</option>
</select>
<p>Comment (Cannot exceed 200 characters):<br />
<textarea name="comment" value="<?php echo $comment; ?>"></textarea><br />
</p>
<input type="submit" value="Edit Order" />
</div>
</body>
</html>
UPDATE: I fixed the code, thanks everyone for all the help, but my error was that when I check the empty field, there was nothing written in the comment box so it was thinking all fields were empty when in reality they weren't. i updated the field check with this code and it works fine now.
I updated the if statement from this:
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '' || $comment == '')
To this:
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '')
It doesn't look like you're running the query after you create it in the $sql variable. You'll want to execute the query like you do later in the code:
$result = mysql_query($sql) or die(mysql_error());
This will return true on success or false (and die) on failure.
If you execute your UPDATE sql statement should give you some ERROR (since you forgot SET). However, you are not executing it. Once you fix that issue, you need to change your UPDATE statement to
$sql = "UPDATE orders
SET
`name` = '".$name."',
due_date = '".$dueDate."',
numOfPages = '".$numOfPages."',
numOfCopies = '".$numOfCopies."',
paper_size = '".$paperSize."',
paper_color = '".$paperColor."',
weight = '".$weight."',
finishing = '".$finishing."',
payment_method = '".$paymentMethod."',
color = '".$printColor."',
comments = '".$comment."',
`status` = '".$status."'
WHERE
id = '".$id."'";
Reference: https://dev.mysql.com/doc/refman/5.0/en/update.html
Note: I escaped name and status columns since their are reserved words
Use this query it may solve your problem:
$sql = "UPDATE orders set name ='".$name."' set due_date = '".$dueDate."' set numOfPages = '".$numOfPages."' set numOfCopies = '".$numOfCopies."' set paper_size = '".$paperSize."' set paper_color = '".$paperColor."' set weight = '".$weight."' set finishing = '".$finishing."' set payment_method = '".$paymentMethod."' set color = '".$printColor."' set comments = '".$comment."' set status = '".$status."' WHERE id = '".$id."' ";

How to get the text of dropdown and echo in php

I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
You may try something like this:
Category
<select name="supplier" style="text-transform:uppercase;" onchange = "GetChangedValue(this);">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<script>
function GetChangedValue(e) {
var value = e.options[e.selectedIndex].text;
alert(value);
}
</script>
To get the selected text, you can use Javascript
var element = document.getElementById("mySelectTag");
var selected_text = element.options[element.selectedIndex].text;
To get a substring of a text, use Javascript, for example:
selected_text.substring(0,3)
function change(){
var selectedtext = document.getElementById("idselect").value;
document.getElementById("myTextField").value = selectedtext.substring(0,3);
}
<h1 id="title">Javascript example</h1>
<input type="text" id="myTextField"/>
<select id="idselect" onchange="change()">
<option>Choose one</option>
<option value="BLUE">Blue</option>
<option value="YELLOW">Yellow</option>
<option value="RED">Red</option>
</select>
http://jsfiddle.net/Fx5T8/

Cannot insert data in the database using option(textarea)

I got this code but it is not inserting the content of the option (textarea) into the database.
connection.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "copy";
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$db);
?>
submit.php
<?php
include 'connection.php';
$foodA = $_POST['foodA'];
$foodB = $_POST['foodB'];
$foodC = $_POST['foodC'];
$foodD = $_POST['foodD'];
$foodE = $_POST['foodE'];
if(!$_POST['submit']) {
echo "please fill out the form";
header('Location: select.html');
}
else {
$sql = "INSERT INTO remove(foodA, foodB, foodC, foodD, foodE) VALUES (?,?,?,?,?);";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt,"sssss",$foodA,$foodB,$foodC,$foodD,$foodE);
mysqli_stmt_execute($stmt);
echo "User has been added!";
header('Location: select.html');
}
select.html
<html lang="en">
<title>Catering Service</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/js.1.js" type="text/javascript"></script>
</head>
<body>
<form action="submit.php" method="post">
<select multiple="multiple" class="options" id="textarea" >
<option value="foodA">foodA</option>
<option value="foodB">foodB</option>
<option value="foodC">foodC</option>
<option value="foodD">foodD</option>
<option value="foodE">foodE</option>
</select>
<button type="button" id="copy" onclick="yourFunction()">Copy</button>
<button type="button" id="remove" onclick="yourFunction()">Remove</button>
<select id="textarea2" multiple class="remove" >
<input type="submit" name="submit" />
</form>
</select>
</html>
You need to name the <select> so you can use the data.
name="food[]"
Like this
<select multiple="multiple" name="food[]" class="options" id="text area" >
<option value="foodA">foodA</option>
<option value="foodB">foodB</option>
<option value="foodC">foodC</option>
<option value="foodD">foodD</option>
<option value="foodE">foodE</option>
</select>
Then if you want the value to be 0 or 1, depending on selected or not, you can use the following to replace this:
$foodA = $_POST['foodA'];
$foodB = $_POST['foodB'];
$foodC = $_POST['foodC'];
$foodD = $_POST['foodD'];
$foodE = $_POST['foodE'];
to
$foodA = 0;
$foodB = 0;
$foodC = 0;
$foodD = 0;
$foodE = 0;
foreach ($_POST['food'] as $value) {
if($value == 'foodA')
$foodA = 1;
if($value == 'foodB')
$foodB = 1;
if($value == 'foodC')
$foodC = 1;
if($value == 'foodD')
$foodD = 1;
if($value == 'foodE')
$foodE = 1;
}
You need to name your select with name=food or something so it will be in $_POST['food']. Each option in the select does not show up in $_POST, only what is selected will be in the name of the select. Each option is not it's own thing.
<select multiple="multiple" name="food" class="options" id="textarea" >
<option value="foodA">foodA</option>
<option value="foodB">foodB</option>
<option value="foodC">foodC</option>
<option value="foodD">foodD</option>
<option value="foodE">foodE</option>
</select>
When you save the data it will have:
$_POST['food'] with the value of 'foodA' if multiples, it will be 'foodA, foodB'

Categories