php export data to cvs - php

I need a help exporting search query by clicking on export button. I am able to get data from database to the browser. However, when I click on export button, it refreshes the page, and doesnt do anything.
I am new to php and and programming. Any help will be appreciated :)
<?php
include('dbcon.php');
?>
<form id="searchform" action="index.php" method="post">
<table>
<tr>
<td class="searchleftcol"><h3>Service:</h3></td>
<td>
<select id="service" name="service" class="searchoption">
<option value="">-- Select Service Name --</option>
<?php
$resultservice = mysqli_query($con,"Select * from services") ?>
<?php
while ($line = mysqli_fetch_array($resultservice)) {
?>
<option value="<?php echo $line['serviceid'];?>"> <?php echo $line['service'];?> </option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<h3>Environment:</h3>
</td>
<td>
<select id="environment" name="environment" class="searchoption">
<option value="">-- Select Environment --</option>
<?php
$resultdomain = mysqli_query($con,"Select * from evn") ?>
<?php
while ($line = mysqli_fetch_array($resultdomain)) {
?>
<option value="<?php echo $line['envid'];?>"> <?php echo $line['env'];?> </option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<h3>Status:</h3>
</td>
<td>
<select name="status" class="searchoption">
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
</select>
</td>
</tr>
</table>
<input type="reset" name="reset">
<input type="submit" name="submit" value="Search">
<input type="submit" name="export" value="Export" />
</ul>
</form>
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['service'])) {
echo "Please select service in dropdown" . "</br>";
}
else {
$service = $_POST['service'];
}
if (empty($_POST['environment'])) {
echo "Please select Environment in dropdown" . "</br>";
}
else {
$env = $_POST['environment'];
}
if ((!empty($service)) && (!empty($env))) {
$sql="SELECT * from servers";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
$mydata = mysqli_query($con,$sql);
$rowcount = mysqli_num_rows($mydata);
// Here I erased code that displays data from MySQL.
if (isset($_POST['export'])) {
if (empty($_POST['service'])) {
echo "Please select service in dropdown" . "</br>";
}
else {
$service = $_POST['service'];
}
if (empty($_POST['environment'])) {
echo "Please select Environment in dropdown" . "</br>";
}
else {
$env = $_POST['environment'];
}
if ((!empty($service)) && (!empty($env))) {
$sql="SELECT * from servers";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
$mydata = mysqli_query($con,$sql);
$rowcount = mysqli_num_rows($mydata);
//Programetically get the Headings of the excel columns
$columns_total = mysqli_num_fields($sql);
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$contents .= '"'.$heading.'",';
}
$contents .="\n";
// Get Records from the table
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$contents.='"'.$row["$i"].'",';
}
$contents.="\n";
}
// Remove html and php tags etc.
$contents = strip_tags($contents);
//header to make force download the file
Header("Content-Disposition: attachment; filename=ProductsReport".date('d-m-Y').".csv");
print $contents;
}
}
mysqli_close($con);
}
?>}
Thanks,
Ray

Related

Not Able to save data to Mysql database

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.

Data not being able to be saved into database PHP

I have this problem here where when I press the Add button, it should save my selected choices into my table in database.
But when I press it, my table in database did not receive any data.
Did I do something wrong with my code? I need to find a right way to save the data into my designated table.
Any help would be greatly appreciated. Thanks
<?php
include "..\subjects\connect3.php";
//echo "Connection successs";
$query = "SELECT * FROM programmes_list";
$result = mysqli_query($link, $query);
?>
<form name = "form1" action="dropdownindex.php" method="post">
<table>
<tr>
<td>Select Pragramme</td>
<td>
<select id="programmedd" onChange="change_programme()">
<option>select</option>
<?php while($row=mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row["ID"]; ?>"><?php echo $row["programme_name"]; ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Select intake</td>
<td>
<div id="intake">
<select>
<option>Select</option>
</select>
</div>
</td>
</tr>
<tr>
<td>Select Subjects</td>
<td>
<div id="subject">
<select >
<option>Select</option>
</select>
</div>
</td>
</tr>
<input type="submit" value="Add" name="send">
</table>
</form>
<?php
if(isset($_POST['Add'])) {
//print_r($_POST);
$course1 = implode(',',$_POST['programmedd']);
$course2 = implode(',',$_POST['intake']);
$course3 = implode(',',$_POST['subject']);
$db->query("INSERT INTO programmes(programme_registered, intake_registered, subjects_registered)
VALUES (' ".$course1." ',' ".$course2." ', ' ".$course3." ' )");
echo $db->affected_rows;
}
?>
<script type="text/javascript">
function change_programme()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?programme="+document.getElementById("programmedd").value,false);
xmlhttp.send(null);
document.getElementById("intake").innerHTML=xmlhttp.responseText;
if(document.getElementById("programmedd").value=="Select"){
document.getElementById("subject").innerHTML="<select><option>Select</option></select>";
}
}
function change_intake()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?intake="+document.getElementById("intakedd").value,false);
xmlhttp.send(null);
document.getElementById("subject").innerHTML=xmlhttp.responseText;
}
</script>
//ajax.php
<?php
$dbhost = 'localhost' ;
$username = 'root' ;
$password = '' ;
$db = 'programmes' ;
$link = mysqli_connect("$dbhost", "$username", "$password");
mysqli_select_db($link, $db);
if (isset($_GET["programme"])) {
$programme = $_GET["programme"];
} else {
$programme = "";
}
if (isset($_GET["intake"])) {
$intake = $_GET["intake"];
} else {
$intake = "";
}
if ($programme!="") {
$res=mysqli_query($link, "select * from intakes where intake_no = $programme");
echo "<select id='intakedd' onChange='change_intake()'>";
echo "<option>" ; echo "Select" ; echo "</option>";
while($value = mysqli_fetch_assoc($res)) {
echo "<option value=".$value['ID'].">";
echo $value["intake_list"];
echo "</option>";
}
echo "</select>";
}
if ($intake!="") {
$res=mysqli_query($link, "select * from subject_list where subject_no = $intake");
echo "<select>";
echo "<option>" ; echo "Select" ; echo "</option>";
while($value = mysqli_fetch_assoc($res)) {
echo "<option value=".$value['ID'].">";
echo $value["subjects"];
echo "</option>";
}
echo "</select>";
}
?>
Your error is where you check for button click.
Change to this
If(isset($_POST['send']))
For future purposes and references, When doing the above, include the name attribute from your button and not the value attribute

I need help to create search data using seleted value

I want to ask about this code. I have two dropdown menu and one button. I want to search in sql database what I choose in those drop down menu. What is the sql syntax for search item in sql database by using two drop down menu.
This is my database = test
this is my table
Table = student
name | class | sex | mark |
John | Five | Male | 75
Jashi | Four | Female | 89 |
This is my code
----------
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db ("test");
$whereClauses = '';
$class = count($_POST['class']);
$sex = count($_POST['sex']);
$i = 0;
if (! empty($_POST['class'])) {
foreach ($_POST['class'] as $class) {
$whereClauses .="class='".mysql_real_escape_string($class)."'";
if ($i++ == $class) {
$whereClauses .= " AND";
}
}
}
if (! empty($_POST['sex'])) {
foreach ($_POST['sex'] as $sex) {
$whereClauses .="sex='".mysql_real_escape_string($sex)."'";
}
if ($i++ == $sex) {
$whereClauses .= " AND";
}
}
$sql = "SELECT * FROM student '".$where."' ORDER BY id DESC '".$limit."'";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
echo $row['class'];
echo $row['sex'];
echo $row['mark'];
}
?>
----------
HTML
<form action="search2.php" method="post">
<select name="class">
<option value="" selected="selected">Class</option>
</select>
<select name="sex">
<option value="" selected="selected">Sex</option>
</select>
<input type="submit" value="search" />
</form>
ANY HELP WOULD BE APPRECIATED
mysql_connect('localhost', 'root', '');
mysql_select_db ("test");
$whereClauses = '';
if (! empty($_POST['class'])) {
foreach ($_POST['class'] as $class) {
$whereClauses[] .="class='".mysql_real_escape_string($class)."'";
}
}
if (! empty($_POST['sex'])) {
foreach ($_POST['sex'] as $sex) {
$whereClauses[] .="sex='".mysql_real_escape_string($sex)."'";
}
}
$where = !empty($whereClauses) ? implode(' and ', $whereClauses) : '';
$sql = "SELECT * FROM student '".$where."' ORDER BY id DESC '".$limit."'";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
echo $row['class'];
echo $row['sex'];
echo $row['mark'];
}
you can do like this example easy and simple
you got something like this
<form method=post>
<?php
// some fetching over here like
$id = $_GET['id']; // getting id just for example
$sql = mysql_query("SELECT FROM `somewhere` where `id`='$id'");
<select name="somename">
while($someid = mysql_fetch_array($sql))
{
?>
<option value="<?php echo $someid['id']; ?>"><?php echo $displayname; ?></option>
<?php } ?>
</select>
<input type="submit" name="sub" /></form>
<?php
if(isset($_POST['sub']))
{
$search_id = $_POST['somename']; // value from option
$search = mysql_query("SELECT * FROM `somewhere` WHERE `id`='$search_id'");
// or you can use LIKE //
// LIKE THIS //
/*
$search = mysql_query("SELECT * FROM `somewhere` WHERE `something` LIKE %SOMETHING%");
*/
// Just example result down here //
$result = mysql_fetch_array($search);
echo '<table cellpadding="10">
<tr>
<th>Name</th><th>SOMETHING</tH>
</tr>
<tr>
<Td>'.$result['name'].'</td><td>'.$result['something'].'</td>
</tr>
</table>';
}
?>
your Solution is here, try this
Database Table Structure
CREATE TABLE IF NOT EXISTS `student` (
`name` varchar(255) NOT NULL,
`class` varchar(255) NOT NULL,
`sex` varchar(255) NOT NULL,
`mark` int(12) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Insert Record
INSERT INTO `student` (`name`, `class`, `sex`, `mark`) VALUES
('John', 'Five', 'Male', 75),
('Jashi', 'Four', 'Female', 89);
<form action="" method="post">
<select name="class">
<option value="">-SELECT CLASS-</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
</select>
<select name="sex">
<option value="">-SELECT GENDER-</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input type="submit" name="search" value="search" />
</form>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db ("test");
extract($_POST);
if(isset($search))
{
if($class!='' || $sex!='')
{
$wh='';
if($class!='') $wh.=" AND class='".$class."'";
if($sex!='') $wh.=" AND sex='".$sex."'";
$qry=mysql_query("SELECT * FROM student where 1 ".$wh."");
$total_record=mysql_num_rows($qry);
if($total_record>0)
{
echo "<table border='1'>
<tr>
<td>Name</td>
<td>Class</td>
<td>Sex</td>
<td>Mark</td>
</tr>
";
while($row=mysql_fetch_array($qry))
{
echo "<tr>
<td>".$row['name']."</td>
<td>".$row['class']."</td>
<td>".$row['sex']."</td>
<td>".$row['mark']."</td>
</tr>";
}
}
else
{
echo "No Record Found";
}
}
else
{
echo "No Record Found";
}
}
?>
Pls mark correct answer if your problem solved
<form action="" method="post">
<select name="class">
<option value="">-SELECT CLASS-</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
</select>
<select name="sex">
<option value="">-SELECT GENDER-</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input type="submit" name="search" value="search" />
</form>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db ("test");
extract($_POST);
if(isset($search))
{
if($class!='' || $sex!='')
{
$wh='';
if($class!='') $wh.=" AND class='".$class."'";
if($sex!='') $wh.=" AND sex='".$sex."'";
$qry=mysql_query("SELECT * FROM student where 1 ".$wh."");
$total_record=mysql_num_rows($qry);
if($total_record>0)
{
echo "<table border='1'>
<tr>
<td>Name</td>
<td>Class</td>
<td>Sex</td>
<td>Mark</td>
</tr>
";
while($row=mysql_fetch_array($qry))
{
echo "<tr>
<td>".$row['name']."</td>
<td>".$row['class']."</td>
<td>".$row['sex']."</td>
<td>".$row['mark']."</td>
</tr>";
}
}
else
{
echo "No Record Found";
}
}
else
{
echo "No Record Found";
}
}
?>
<form action="" method="post">
<select name="class">
<option value="">-SELECT CLASS-</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
</select>
<select name="sex">
<option value="">-SELECT GENDER-</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input type="submit" name="search" value="search" />
</form>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db ("test");
extract($_POST);
if(isset($search))
{
if($class!='' || $sex!='')
{
$wh='';
if($class!='') $wh.=" AND class='".$class."'";
if($sex!='') $wh.=" AND sex='".$sex."'";
$qry=mysql_query("SELECT * FROM student where 1 ".$wh."");
$total_record=mysql_num_rows($qry);
if($total_record>0)
{
echo "<table border='1'>
<tr>
<td>Name</td>
<td>Class</td>
<td>Sex</td>
<td>Mark</td>
</tr>
";
while($row=mysql_fetch_array($qry))
{
echo "<tr>
<td>".$row['name']."</td>
<td>".$row['class']."</td>
<td>".$row['sex']."</td>
<td>".$row['mark']."</td>
</tr>";
}
}
else
{
echo "No Record Found";
}
}
else
{
echo "No Record Found";
}
}
?>
Wow - what service! Thanks for the PROMPT response to my problem. Your code is working fine. I really do appreciate. Thanks

Multiple Form Dropdown Form, Validation, PHP

I have this whole code. Jumbled but what I'm trying to do is to have a drop down menu with selections from 1 -10. Then after selecting one, would spit out another form so that if there 3 were selected, would show three rows of fields (name, email). Validation included. What I was first "hard coded" on how many rows of fields to spit out but now what I wanted to do is to have a "selection" in dropdown menu so that the user has the ability to select.... Seem to work but doesn't process. Any PHP expert help? No db, no client-base, no smart alec. If you have time to help please do.
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
echo '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
if (isset($_POST['submit-invite'])) { //DROPDOWN MENU
$row = $_POST['invitee'];
// Check if the form has been submitted:
if (isset($_POST['submit'])) {
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 1; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1) ) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
$row = $i+1;
echo $row.": ".$_POST['firstname'][$i]." ".$_POST['lastname'][$i].", ".$_POST['email'][$i]." <br/>";
// Send the email:
$body = file_get_contents("Lab12_Obj1_email_template.txt");
$body = str_replace("#firstname#",$_POST['firstname'][$i],$body);
$body = str_replace("#lastname#",$_POST['lastname'][$i],$body);
$body = str_replace("#email#",$_POST['email'][$i],$body);
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: jvicencio#johnvicencio.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
echo '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
//show form
?>
<form action="" method="post">
<table>
<tr style="font-weight:bold">
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 1; $i <= $row; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<? echo $i.': '; ?><input type="text" name="firstname[]" size="20" value="<?php if (isset($_POST['firstname'][$i])) { print htmlspecialchars($_POST['firstname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<input type="text" name="lastname[]" size="20" value="<?php if (isset($_POST['lastname'] [$i])) { print htmlspecialchars($_POST['lastname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?><input type="text" name="email[]" size="20" value="<?php if (isset($_POST['email'][$i])) { print htmlspecialchars($_POST['email'][$i]); } ?>" />
</td>
</tr>
<?php } ?>
<tr><td><p><input type="submit" class="button" name="submit" value="Register!" /></td>
</tr>
</table>
</form>
<?php
}
else {
echo '
<form action="" method="post">
<select name="invitee">
<option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
<input type="submit" class="button" name="submit-invite" value="Invite">
</form>
';
}
?>
</div>
</body>
</html>
You have to move the second form submit code outside of first form submit. Try this
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
echo '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
if (isset($_POST['submit-invite'])) { //DROPDOWN MENU
$row = $_POST['invitee'];
$problem = false; //always try to initialize variables, you may not run into unexpected warnings and problems.
//show form
?>
<form action="" method="post">
<table>
<tr style="font-weight:bold">
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 1; $i <= $row; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?>
<? echo $i . ': '; ?><input type="text" name="firstname[]" size="20"
value="<?php if (isset($_POST['firstname'][$i])) {
print htmlspecialchars($_POST['firstname'][$i]);
} ?>"/>
</td>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?>
<input type="text" name="lastname[]" size="20"
value="<?php if (isset($_POST['lastname'] [$i])) {
print htmlspecialchars($_POST['lastname'][$i]);
} ?>"/>
</td>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?><input type="text" name="email[]" size="20"
value="<?php if (isset($_POST['email'][$i])) {
print htmlspecialchars($_POST['email'][$i]);
} ?>"/>
</td>
</tr>
<?php } ?>
<tr>
<td><p><input type="submit" class="button" name="submit" value="Register!"/></td>
</tr>
</table>
</form>
<?php
} // moved second for submit to here
elseif (isset($_POST['submit'])) { // Check if the form has been submitted:
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 1; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1)) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
$row = $i + 1;
echo $row . ": " . $_POST['firstname'][$i] . " " . $_POST['lastname'][$i] . ", " . $_POST['email'][$i] . " <br/>";
// Send the email:
$body = file_get_contents("Lab12_Obj1_email_template.txt");
$body = str_replace("#firstname#", $_POST['firstname'][$i], $body);
$body = str_replace("#lastname#", $_POST['lastname'][$i], $body);
$body = str_replace("#email#", $_POST['email'][$i], $body);
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: jvicencio#johnvicencio.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
echo '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
else {
echo '
<form action="" method="post">
<select name="invitee">
<option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
<input type="submit" class="button" name="submit-invite" value="Invite">
</form>
';
}
?>
</div>
</body>
</html>

show city depending on the state selected

My script is working, the problem is that I am on a page to edit, and was to appear all data
<tr>
<td class="left">Estado</td>
<td>
<select name="estado" id="select2_1" onChange="buscar_cidades()" style="width: 40%;">
<option value="">--</option>
<?php foreach ($arrEstados as $value => $name) {
echo "<option value='{$value}' ".selected($estado,$value).">{$name}</option>";
}?>
</select>
</td>
</tr>
<tr>
<td class="left">Cidade</td>
<td>
<div id="load_cidades">
<select name="cidade" id="select2_2" style="width: 50%;">
<option value="">Select the state</option>
</select>
</div>
</td>
</tr>
function buscar_cidades(){
var estado = $('#select2_1').val();
if(estado){
var url = 'ajax_cidades.php?estado='+estado;
$.get(url, function(dataReturn) {
$('#load_cidades').html(dataReturn);
});
}
}
my file ajax_cidades.php
<?php
require_once('application/config/database.php');
$estado = $_GET['estado'];
$sql = "SELECT * FROM loc_cidade WHERE id_uf = $estado ORDER BY nome";
$res = mysql_query($sql) or die(mysql_error());
$num = mysql_num_rows($res);
for ($i = 0; $i < $num; $i++) {
$dados = mysql_fetch_array($res);
$arrCidades[$dados['id']] = $dados['nome'];
}
?>
<select name="cidade" id="select2_2" style="width: 50%;">
<?php foreach($arrCidades as $value => $nome){
echo "<option value='{$value}'>{$nome}</option>";
}
?>
I already tried everything and could not, function 'selected' checks are equal to brand as 'selected'
print screen
http://oi44.tinypic.com/pu5w6.jpg
I'm not sure why you are having your ajax_cidades.php loop through the same data twice.
<?php
require_once('application/config/database.php');
$estado = $_GET['estado'];
$sql = "SELECT * FROM loc_cidade WHERE id_uf = $estado ORDER BY nome";
$res = mysql_query($sql) or die(mysql_error());
$num = mysql_num_rows($res);
echo '<select name="cidade" id="select2_2" style="width:50%;">';
for ($i = 0; $i < $num; $i++) {
$dados = mysql_fetch_array($res);
echo '<option value="'.$dados['id'].'">'.$dados['nome'].'</option>';
}
echo '</select>';
?>
also, try debugging what the ajax call is returning, by adding
console.log(dataReturn)
to your function after $.get(url, function(dataReturn) {
then check your console to make sure your page is returning the data expected.

Categories