Getting form data from POST and inserting to mysqli database - php

Learning PHP and for my most recent assignment, I had to create an HTML form, use PHP for error checking, insert the data into a database using mysqli, and then retrieve the values and display them in a table. I turned the assignment in even though I didn't have it working 100%, but I'm just trying to figure out where I've gone wrong while waiting for feedback from my instructor. I've checked out several similar threads, but so far none of the solutions offered seem to work for me.
So far, my form works and it seems to redirect and connect to the database just fine. It also retrieves data already stored in the database and displays it in a table. But I can't for the life of me seem to get it to actually write the form data that gets submitted via POST. Regardless of what data is or is not entered on the form, when the submit button is clicked, it writes a blank row to my database, which should be prevented by my error-checking. So in addition Here's my code for the form:
<?php
include ("dbinfo.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_WARNING);
//declare variables
$errors = 0;
//if form is submitted
if ( isset($_POST['submit']) ) {
//store submitted values
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$street = $_POST['street'];
$city = $_POST['city'];
$province = $_POST['province'];
$postal = $_POST['postal'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$newsletter = $_POST['newsletter'];
//error checking routine
if ( !isset($_POST[$title]) || empty($_POST[$title]) ) $errors = 1;
if ( !isset($_POST[$firstName]) || empty($_POST[$firstName]) ) $errors = 2;
if ( !isset($_POST[$lastName]) || empty($_POST[$lastName]) ) $errors = 3;
if ( !isset($_POST[$street]) || empty($_POST[$street]) ) $errors = 4;
if ( !isset($_POST[$city]) || empty($_POST[$city]) ) $errors = 5;
if ( !isset($_POST[$province]) || empty($_POST[$province]) ) $errors = 6;
if ( !isset($_POST[$postal]) || empty($_POST[$postal]) ) $errors = 7;
if ( !isset($_POST[$country]) || empty($_POST[$country]) ) $errors = 8;
if ( !isset($_POST[$phone]) || empty($_POST[$phone]) ) $errors = 9;
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) === false ) $errors = 10;
if ( !isset($_POST[$email]) || empty($_POST[$email]) ) $errors = 11;
}
//if error flag is still 0
if ( $errors == 0 ) {
?>
<!-- display the form -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
</head>
<body>
<!-- if errors exist, display error message(s -->
<p>
<strong>Instructions:</strong> To complete your registration, please fill out the following form.
<?php if ($errors > 0) echo "<p><font color=red><strong>Please ensure all required fields are filled.</strong></font></p>"; ?>
</p>
<form action="" method="POST" enctype="multipart/form-data">
<label for="title" >Title</label>
<select name="title">
<option value="" <?php if (isset($title) && $title =="") echo "selected";?>></option>
<option value="Mr" <?php if (isset($title) && $title == "Mr") echo "selected";?>>Mr</option>
<option value="Mrs" <?php if (isset($title) && $title == "Mrs") echo "selected";?>>Mrs</option>
<option value="Ms" <?php if (isset($title) && $title =="Ms") echo "selected";?>>Ms</option>
<option value="Dr" <?php if (isset($title) && $title =="Dr") echo "selected";?>>Dr</option>
</select>
<?php if ( $errors > 0 && empty($title) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="firstName">First Name: </label>
<input type="text" name="firstName" placeholder="Jane" value="<?php echo isset($_POST["firstName"]) ? $_POST["firstName"] : ''; ?>">
<?php if ( $errors > 0 && empty($firstName) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">Last Name: </label>
<input type="text" name="lastName" placeholder="Doe" value="<?php echo isset($_POST["lastName"]) ? $_POST["lastName"] : ''; ?>">
<?php if ( $errors > 0 && empty($lastName) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">Street Address: </label>
<input type="text" name="street" placeholder="123 ABC Drive" value="<?php echo isset($_POST["street"]) ? $_POST["street"] : ''; ?>">
<?php if ( $errors > 0 && empty($street) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">City: </label>
<input type="text" name="city" placeholder="Anytown" value="<?php echo isset($_POST["city"]) ? $_POST["city"] : ''; ?>">
<?php if ( $errors > 0 && empty($city) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">Province: </label>
<input type="text" name="province" placeholder="Nova Scotia" value="<?php echo isset($_POST["province"]) ? $_POST["province"] : ''; ?>">
<?php if ( $errors > 0 && empty($province) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">Postal Code:</label>
<input type="text" name="postal" placeholder="A1A 1A1" value="<?php echo isset($_POST["postal"]) ? $_POST["postal"] : ''; ?>">
<?php if ( $errors > 0 && empty($postal) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="country">Country: </label>
<select name="country">
<option value="" <?php if ( isset($country) && $country == "" ) echo "selected";?>></option>
<option value="canada" <?php if (isset($country) && $country == "canada") echo "selected";?>>Canada</option>
<option value="usa" <?php if (isset($country) && $country == "usa") echo "selected";?>>USA</option>
</select>
<?php if ( $errors > 0 && empty($country) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="phone">Phone Number: </label>
<input type="text" name="phone" placeholder="555-555-5555" value="<?php echo isset($_POST["phone"]) ? $_POST["phone"] : ''; ?>">
<?php if ( $errors > 0 && empty($phone) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="email">Email Address: </label>
<input type="text" name="email" placeholder="email#domain.com" value="<?php echo isset($_POST["email"]) ? $_POST["email"] : ''; ?>">
<?php if ( $errors > 0 && empty($email) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="newsletter">Subscribe to our newsletter? </label>
<input type="checkbox" name="newsletter" value="1">
<br /><br />
<input name="submit" type="submit" value="submit">
</form>
</body>
</html>
<?php
} else {
//redirect to database
header("Location: regdatabase.php");
exit;
}
My dbinfo file only contains $db_host, $db_user, $db_pass, and $db_name. This is the code for the regdatabase.php.
<?php
include ("dbinfo.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//establish a DB connection to a specific database
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
//check for valid connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully. <br />";
//prepare and bind
$sql = "INSERT INTO registered_users (title, firstName, lastName, street, city, province, postal, country, phone, email, newsletter)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssssssssi", $_REQUEST['title'], $_REQUEST['firstName'], $_REQUEST['lastName'], $_REQUEST['street'], $_REQUEST['city'], $_REQUEST['province'],
$_REQUEST['postal'], $_REQUEST['country'], $_REQUEST['phone'], $_REQUEST['email'], $_REQUEST['newsletter']);
$stmt->execute();
$stmt->close();
//retrieve values and display in table
$sql = "SELECT * FROM registered_users";
$results = mysqli_query($conn, $sql);
if ($results->num_rows > 0) {
echo "Data stored in database successfully.<br /><br />
<table><tr>
<th>User ID</th>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Street Address</th>
<th>City</th>
<th>Province</th>
<th>Postal Code</th>
<th>Country</th>
<th>Phone Number</th>
<th>Email Address</th>
<th>Newsletter Sub</th>
</tr>";
while($row = mysqli_fetch_assoc($results)) {
echo "<tr><td>" . $row["user_id"]. "</td>" .
"<td>" . $row["title"]. "</td>" .
"<td>" . $row["firstName"]. "</td>" .
"<td>" . $row["lastName"]. "</td>" .
"<td>" . $row["street"]. "</td>" .
"<td>" . $row["city"]. "</td>" .
"<td>" . $row["province"]. "</td>" .
"<td>" . $row["postal"]. "</td>" .
"<td>" . $row["country"]. "</td>" .
"<td>" . $row["phone"]. "</td>" .
"<td>" . $row["email"]. "</td>" .
"<td>" . $row["newsletter"]. "</td></tr>";
}
echo "</table>";
} else {
echo "There are 0 results.";
}
mysqli_close($conn);
?>
A var_dump shows that all my variables are NULL. Blank records are being recorded in the database. I've also rewritten my bind statement in the following format, but had no luck with that either.
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$street = $_POST['street'];
$city = $_POST['city'];
$province = $_POST['province'];
$postal = $_POST['postal'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$newsletter = $_POST['newsletter'];
$stmt->bind_param("ssssssssssi", $title, $firstName, $lastName, $street, $province, $postal, $country, $phone, $email, $newsletter);
If I write and declare values explicitly like this, they write to the database properly which seems to indicate my prepared statement works properly.
$title = "Ms";
$firstName = "Jane";
$lastName = "Doe";
$street = "123 ABC Lane";
$city = "AnyTown";
$province = "Nova Scotia";
$postal = "A1A 1A1";
$country = "Canada";
$phone = "555-555-5555";
$email = "email#domain.com";
$newsletter = 1;
$stmt->bind_param("ssssssssssi", $title, $firstName, $lastName, $street, $province, $postal, $country, $phone, $email, $newsletter);
I'll be very grateful for any help in diagnosing why everything seems to work except getting the values through POST. Also willing to accept any tips about why my error-checking seems to get skipped over when submitting to the database. Thanks in advance!

Related

Cannot set email variable from session so mail() function nto working

I'm very new to php and sql and I'm trying to set a _SESSION variable for my user_email, I know that the column name is correct and I'm pulling the other information from the session like the user_id etc correctly but cannot seem to get the email to set even though I've done it the same as my other variables. I'm also trying to use the mail() function but I'm not sure if this is set up correctly? Any help would be really appreciated!
I've tried doing the variable as a _POST one using a hidden input but that hasn't worked either.
<div>
<?php
if (isset($_POST['request_date'])) {
$user_email = $_SESSION['user_email'];
$user_id = $_SESSION['user_id'];
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
// $request_time = date("d-m-Y H:i:s");
$lend_status = 1;
$requested_start_date = date('Y-m-d H:i:s', strtotime($_POST['requested_start_date'] . ' ' . $_POST['requested_start_time'] . ':00:00'));
$requested_end_date = date('Y-m-d H:i:s', strtotime($_POST['requested_end_date'] . ' ' . $_POST['requested_end_time'] . ':00:00'));
$comments = $_POST['comments'];
// Declare available laptops array
$available_laptops = array();
// GET ALL LAPTOPS IN OPERATION
$STH = $DBH->prepare("
SELECT laptop_id,
laptop_name
FROM laptops
WHERE 1
");
$STH->execute(array());
while ($row = $STH->fetch()) {
// CHECK EACH LAPTOP FOR THE REQUESTED DATES
$STH2 = $DBH->prepare("
SELECT lend_id
FROM laptop_system
WHERE (
(
approved_start_date <= ?
AND approved_end_date >= ?
) OR (
approved_start_date <= ?
AND approved_end_date >= ?
) OR (
approved_start_date >= ?
AND approved_end_date <= ?
)
)
AND laptop_id = ?
");
$STH2->execute(array(
$requested_start_date,
$requested_start_date,
$requested_end_date,
$requested_end_date,
$requested_start_date,
$requested_end_date,
$row->laptop_id
));
// IF IT'S NOT BOOKED OUT, ADD TO ARRAY
if ($STH2->rowCount() < 1) {
$available_laptops[$row->laptop_id] = $row->laptop_name;
}
}
if (empty($available_laptops)) {
echo '<h3>Sorry, this date is not available.</h3>';
} else {
$STH = $DBH->prepare("
INSERT INTO laptop_system (
user_id,
first_name,
last_name,
lend_status,
requested_start_date,
requested_end_date,
comments
)
VALUES(?, ?, ?, ?, ?, ?, ?)
");
$STH->execute(array(
$user_id,
$first_name,
$last_name,
$lend_status,
$requested_start_date,
$requested_end_date,
$comments
));
echo '<h2 style="color:#D80B8C; margin-bottom:1em;">' . $first_name . ', your laptop request is now pending approval.</h2>';
$to = $user_email;
$subject = "Laptop Request";
$message = "Thank you for your laptop request for " . $requested_start_date . " - " . $requested_end_date . "It is now pending and you will be notified if it's been approved or declined.";
$message = wordwrap($message,70);
$headers = "From: Timmy and Edwardo";
mail($to,$subject,$txt,$headers);
}
} ?>
<form action="" method="post" >
<div>
<label for="requested_start_date"> Requested Start Date </label>
<input type="date" name="requested_start_date" value="<?php echo $requested_start_date; ?>">
<label for="requested_start_time">Requested start time </label>
<select name="requested_start_time" style="width:auto;margin:1em 1em 1em 0;">
<?php for ($i = 0; $i < 25; $i++) {$i = str_pad($i, 2, "0", STR_PAD_LEFT); ?>
<option value="<?php echo $i; ?>"><?php echo $i . ':00'; ?></option>
<?php } ?>
</select>
</div>
<div>
<label for="requested_end_date">Requested End Date </label>
<input type="date" name="requested_end_date" value="<?php echo $requested_end_date; ?>">
<label for="requested_end_time">Requested end time</label>
<select name="requested_end_time" style="width:auto;margin:1em 1em 1em 0;">
<?php for ($i = 0; $i < 25; $i++) {$i = str_pad($i, 2, "0", STR_PAD_LEFT); ?>
<option value="<?php echo $i; ?>"><?php echo $i . ':00'; ?></option>
<?php } ?>
</select>
</div>
<div>
<p style="margin-bottom:0;">
Please can you let us know below why you need the laptop and if there are any special requirements needed -
</p>
<input type="textarea" rows="4" cols="50" name="comments" placeholder="" required>
<input type="submit" name="request_date" value="Request Date">
<!-- <input type="hidden" name="user_email" value="<?php echo $user_email;?>" > -->
</div>
</form>
<?php
?>
</div>

Update value based on checkbox selected

I am trying to update the value in a text box based on selections made on the form. When a user checks a box for an option, I am trying to get the total cost to increase by a defined amount. Everything else is working on the form and if I change the cost value manually it will post to database correctly. Is this possible with my approach or do I need to resort to a different technique?
<HEAD>
<script>
function tally()
{
Cost = 60;
if (Document.edituser.survivor10.checked ) { Cost = Cost + 10; }
if (document.edituser.high5.checked ) { Cost = Cost + 10; }
if (document.edituser.margin.checked == true ) { Cost = Cost + 10; }
if (document.edituser.survivor20.checked == true ) { Cost = Cost + 20; }
if (document.edituser.confidence.checked == true ) { Cost = Cost + 10; }
if (document.edituser.loser.checked == true ) { Cost = Cost + 10; }
if (document.edituser.vegas.checked == true ) { Cost = Cost + 10; }
document.edituser.cost.value = Cost;
}
<?php
require('includes/application_top.php');
include('includes/classes/class.formvalidation.php');
if (isset($_POST['submit'])) {
$my_form = new validator;
if($my_form->checkEmail($_POST['email'])) { // check for good mail
if ($my_form->validate_fields('firstname,lastname,email,password')) { //
comma delimited list of the required form fields
if ($_POST['password'] == $_POST['password2']) {
$salt = substr($crypto->encrypt((uniqid(mt_rand(), true))), 0, 10);
$secure_password = $crypto->encrypt($salt . $crypto->encrypt($_POST['password']));
$sql = "update nflp_users ";
$sql .= "set password = '".$secure_password."', salt = '".$salt."', firstname = '".$_POST['firstname']."', lastname = '".$_POST['lastname']."', textOption = '".$_POST['textOption']."', phone = '".$_POST['phone']."', carrier = '".$_POST['carrier']."', email = '".$_POST['email']."', survivor10 = '".$_POST['survivor10']."', survivor20 = '".$_POST['survivor20']."', loser = '".$_POST['loser']."', margin = '".$_POST['margin']."', high5 = '".$_POST['high5']."', vegas = '".$_POST['vegas']."', confidence = '".$_POST['confidence']."', cost = '".$_POST['cost']."'";
$sql .= "where userID = " . $user->userID . ";";
//die($sql);
$mysqli->query($sql) or die($mysqli->error);
//set confirmation message
$display = '<div class="responseOk">Account updated successfully.</div><br/>';
} else {
$display = '<div class="responseError">Passwords do not match, please try again.</div><br/>';
}
} else {
$display = str_replace($_SESSION['email_field_name'], 'Email', $my_form->error);
$display = '<div class="responseError">' . $display . '</div><br/>';
}
} else {
$display = '<div class="responseError">There seems to be a problem with your email address, please check.</div><br/>';
}
}
include('includes/header.php');
$sql = "select * from " . DB_PREFIX . "users where userID = " . $user->userID;
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$row = $query->fetch_assoc();
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$email = $row['email'];
$survivor10 = $row['survivor10'];
$survivor20 = $row['survivor20'];
$loser = $row['loser'];
$margin = $row['margin'];
$high5 = $row['high5'];
$confidence = $row['confidence'];
$vegas = $row['vegas'];
// $textOption = $row['textOption'];
// $phone = $row['phone'];
// $carrier = $row['carrier'];
$cost = $row['cost'];
}
if (!empty($_POST['firstname'])) $firstname = $_POST['firstname'];
if (!empty($_POST['lastname'])) $lastname = $_POST['lastname'];
if (!empty($_POST['email'])) $email = $_POST['email'];
if (!empty($_POST['survivor10'])) $survivor10 = $_POST['survivor10'];
if (!empty($_POST['survivor20'])) $survivor20 = $_POST['survivor20'];
if (!empty($_POST['loser'])) $loser = $_POST['loser'];
if (!empty($_POST['margin'])) $margin = $_POST['margin'];
if (!empty($_POST['high5'])) $high5 = $_POST['high5'];
if (!empty($_POST['confidence'])) $confidence = $_POST['confidence'];
if (!empty($_POST['vegas'])) $vegas = $_POST['vegas'];
// if (!empty($_POST['textOption'])) $textOption = $_POST['textOption'];
// if (!empty($_POST['phone'])) $phone = $_POST['phone'];
// if (!empty($_POST['carrier'])) $carrier = $_POST['carrier'];
if (!empty($_POST['cost'])) $cost = $_POST['cost'];
?>
<h1>Edit User Account Details</h1>
<?php if(isset($display)) echo $display; ?>
<form action="user_edit.php" method="post" name="edituser">
<fieldset>
<legend style="font-weight:bold;">Enter User Details:</legend>
<p>First Name:<br />
<input type="text" name="firstname" value="<?php echo $firstname; ?>"></p>
<p>Last Name:<br />
<input type="text" name="lastname" value="<?php echo $lastname; ?>"></p>
<p>Email:<br />
<input type="text" name="email" value="<?php echo $email; ?>" size="30"></p>
<p>New Password:<br />
<input type="password" name="password" value=""></p>
<p>Confirm Password:<br />
<input type="password" name="password2" value=""></p><br>
<tr><td></td></tr>
<legend style="font-weight:bold;">Side Pools:</legend>
<tr>
<p><type=hidden value=" " name="survivor10" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="survivor10" <? if($survivor10== "1") {echo "checked";} ?>><b> Survivor $10</b></p>
<p><type=hidden value=" " name="survivor20" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="survivor20" <? if($survivor20== "1") {echo "checked";} ?>><b> Survivor2 $20</b></p>
<p><type=hidden value=" " name="loser" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="loser" <? if($loser== "1") {echo "checked";} ?> ><b> Loser $10</b></p>
<p><type=hidden value=" " name="high5" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="high5" <? if($high5== "1") {echo "checked";} ?>><b> High 5 $10</b></p>
<p><type=hidden value=" " name="margin" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="margin" <? if($margin== "1") {echo "checked";} ?> ><b> Margin $10</b></p>
<p><type=hidden value=" " name="vegas" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="vegas" <? if($vegas== "1") {echo "checked";} ?> ><b> Vegas $10</b></p>
<p><type=hidden value=" " name="confidence" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="confidence" <? if($confidence== "1") {echo "checked";} ?>><b> Confidence $10</b></p>
</tr><br>
<td><font color=red>Your Total Fee Is :</font><input type="int" size="3" name="cost" value= "<? if($cost!= "") {echo "$cost"; } else {echo "60";}?>"</td><br><br>
<!--<tr>Text alert option: Message and data rates may apply. Expect approx. 3 msgs/week.</tr> -->
<p><input type="submit" name="submit" value="Submit" class="btn btn-primary"></p>
</fieldset>
</form>
JavaScript is case sensitive, so Document and document are two different things. In your case, you want to use document. So you should change all if conditions inside tally, to use document.
Btw. never trust the user! You could do the calculation on the client side as an indicator for the user, but you should definitly do it again on the serverside or everyone could post costs as the like - even negative ones.

I'm Unable to set value of textbox using php variable

I'm trying to set value of html input type text textboxes to empty when user clicks Search button and empID is not matched, but its giving error:
mysqli_num_rows() expects parameter 1 to be mysqli_result
Here is code:
<html>
<body>
<form action="" method="post">
<h2>Employee Form</h2>
<input type="text" name="empID">
<input type="submit" name="searchRec" value="Search" />
<hr>
Employee ID: <input type="text" name="empIDC" value="<?php echo htmlentities($employeeID); ?>">
<br><br>
Name: <input type="text" name="name" value="<?php echo htmlentities($Name); ?>">
<br><br>
Address: <input type="text" name="address" value="<?php echo htmlentities($Address); ?>">
<br><br>
</form>
<?php
if( isset( $_REQUEST['searchRec'] ))
{
$employeeID = ($_POST["empID"]);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bc140_DB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT empID, Name, Address, Dateofbirth, Salary, Timein from Employee where empID == $employeeID";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result > 0)){ while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $employeeID = $row['empID']; $Name = $row['Name']; $Address = $row['Address']; $Dateofbirth = $row['Dateofbirth']; $Salary = $row['Salary']; $timestamp = $row['timeIn']; } }else{ $employeeID = ""; $Name = ""; $Address = ""; $Dateofbirth = ""; $Salary = ""; $timestamp = ""; }
}
?>
</body>
</html>
1st : Change your code order otherwise you will get undefined error . your trying the embed the variable with html before creating the variable .
2nd : should be use single = not == empID = $employeeID
3rd : your mixing mysql with mysqli here mysql_fetch_array($result, MYSQL_ASSOC)
Change to
mysqli_fetch_array($result,MYSQLI_ASSOC);
4th: And also use isset() to confirm that variable exists or not if exists echo it otherwise echo the empty string .
5th: change your if like this if(mysqli_num_rows($result)>0){ }
file.php
<?php
if( isset( $_REQUEST['searchRec'] ))
{
......
$employeeID = $row['empID'];
$Name = $row['Name'];
$Address = $row['Address'];
$Dateofbirth = $row['Dateofbirth'];
$Salary = $row['Salary'];
$timestamp = $row['timeIn'];
......
}
?>
<html>
<body>
.....
Employee ID: <input type="text" name="empIDC" value="<?php if(isset($employeeID)){ echo htmlentities($employeeID); } else { echo ""; } ?>">
.....
</body>
</html>
you have forgotten ';' value="<?php echo htmlentities($employeeID); ?>"

PHP search results and link photo to a profile.php page?

How do I create a link to each photo or text of these search results to a profile.php to query and output database?
In a nutshell - search database and click any result that would take you to their profile page. Example: Match.com, facebook.com...etc (search and click to view profile).
Also, how can I output first name and last name on the same line?
Please Help.
Here is the HTML Search Form.
<h2>Search</h2>
<form name="search" action="searchresults.php" method="POST">
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="firstName">First Name</option>
<Option VALUE="email">Email</option>
</Select>
Search for: <input type="text" name="find1" /> in
<Select NAME="field1">
<Option VALUE="lastName">Last Name</option>
</Select>
<br><br>
Search for: <input type="text" name="find2" /> in
<Select NAME="field2">
<Option VALUE="gender">Gender</option>
</Select>
<br><br>
Search for: <input type="text" name="find3" /> in
<Select NAME="field3">
<Option VALUE="age">Age</option>
</Select>
<br><br>
Search for: <input type="text" name="find4" /> in
<Select NAME="field4">
<Option VALUE="city">City</option>
</Select>
Search for: <input type="text" name="find5" /> in
<Select NAME="field5">
<Option VALUE="state">State</option>
</Select>
<br><br>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
Here is the searchresults.php.
DATABASE CONNECTION
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
$find=$_POST['find'];
$field=$_POST['field'];
$find1=$_POST['find1'];
$field1=$_POST['field1'];
$find2=$_POST['find2'];
$field2=$_POST['field2'];
$find3=$_POST['find3'];
$field3=$_POST['field3'];
$find4=$_POST['find4'];
$field4=$_POST['field4'];
$find5=$_POST['find5'];
$field5=$_POST['field5'];
$data="SELECT firstName, lastName, email, userphoto, gender, age, city, state FROM actorsInfo
WHERE upper($field) LIKE '%$find%'
AND upper($field1) LIKE '%$find1%'
AND upper($field2) LIKE '%$find2%'
AND upper($field3) LIKE '%$find3%'
AND upper($field4) LIKE '%$find4%'
AND upper($field5) LIKE '%$find5%'
";
$result = mysql_query($data);
$count=mysql_numrows($result);
echo '<br><br>';
if($count > 0){
echo"<table border=0>";
//get images and names in two arrays
$firstName= $row["firstName"];
$lastName= $row["lastName"];
$email= $row["email"];
$userphoto= $row["userphoto"];
$gender= $row["gender"];
$age= $row["age"];
$city= $row["city"];
$state= $row["state"];
$age = array();
$gender = array();
$userphoto = array();
$firstName = array();
$lastName = array();
$city = array();
$state = array();
while ($row = mysql_fetch_array($result))
{
$userphoto[] = "<img src='images/".$row['userphoto']."' height='200' width='160'>";
$firstName[] = $row['firstName'];
$lastName[] = $row['lastName'];
$age[] = $row['age'];
$gender[] = $row['gender'];
$email[] = $row['email'];
$city[] = $row['city'];
$state[] = $row['state'];
}
while(!empty($userphoto))
{
//output images
foreach(array($userphoto, $firstName, $lastName, $age, $email, $city, $state) as $items)
{
echo "<tr>";
foreach($items as $key=>$item)
{
echo "<td><font size =\"2\" >$item</td>";
//output only four of them
if($key==4)
{
break;
}
}
echo "</tr>";
}
//remove the first five images from $images because they're already printed
$userphoto = array_slice($userphoto, 5);
$firstName = array_slice($firstName, 5);
$lastName= array_slice($lastName, 5);
$email = array_slice($email, 5);
$age = array_slice($age, 5);
$city = array_slice($city, 5);
$state = array_slice($state, 5);
}
Here is the solution that passes the id to profile.php.
$userphoto[] = "<a href='profile.php?id=".$row['id']."'><img src='images/".$row['userphoto']."' height='200' width='160'></a>";
Here is the profile.php.
<?php
$id = (int)$_GET['id'];
if (isset($_GET['id']))
{
//fetch and display the information with database Query
$con=mysqli_connect("127.0.0.1", "admin", "password","actors");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM actorsInfo where id = " . $_GET['id']);
while($row = mysqli_fetch_array($result))
{
echo $row['firstName'] . " " . $row['email'];
echo "<br>";
}
mysqli_close($con);
}
?>

Editing Checkboxes, radios, and dropdowns

I found this site providing code for creating, reading, updating and deleting. I am confused about how to add checkboxes, radio buttons, and dropdowns
http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
I'm not concerned with the pagination at all——my primary concern is to be able to put in two dropdowns, yes/no radio button, and a collection of 3 checkboxes using PHP.
My attempts were useless as when I tried to edit choices the values did not stay. Included are my three files: pets, editpets, and view.(I changed the file name for database, etc.)
<?php
function renderForm($first, $last, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE html>
<html>
<head>
<title>New Customer</title>
</head>
<body>
<?php
// display possible errors
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name:</strong> <input type="text" name="firstname" value="<?php echo
$first; ?>" />
<strong>Last Name:</strong> <input align="center" type="text" name="lastname" value="<
?php echo $last; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<br/>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<input style="color:purple;" type="submit" name="submit" value="Create My Order :-)">
</div>
</form>
<center>Click Here for Orders</center>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if my form submits and, upon triumph, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, check its validity
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check to make sure everything is filled!
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, show the form again
renderForm($firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("INSERT customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years'")
or die(mysql_error());
// once saved, redirect to cheview page
header("Location: view.php");
}
}
else
// if the form is not submitted, show my form again.
{
renderForm('','','','','','','');
}
?>
<?php
$types = array("Cats", "Dogs", "Others");
function renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: </strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>" /><br/>
<strong>Last Name: </strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<br /><br />
<input type="submit" name="submit" value="Resubmit My Order :-)">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// check for id being an integer
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.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 (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM customers 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
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$pets = $row['pets'];
$size = $row['size'];
$type = serialize($row['type']);
$years = $row['years'];
// show form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, '');
}
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!';
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View customer orders</title>
</head>
<body>
<?php
include('connect-db.php');
$result = mysql_query("SELECT * FROM customers")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Pets</th>
<th>Size</th>
<th>Type</th>
<th>Years</th>
<th></th>
<th></th>
</tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['pets'] . '</td>';
echo '<td>' . $row['size'] . '</td>';
echo '<td>' . $row['type']. '</td>';
echo '<td>' . $row['years'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
I'm honestly lost at this point. I've been working on this for an entire month and I have no idea what I'm doing any more. I'd be so thankful if anyone can help me to edit this to work.
Thanks everyone.
Right, to get your saved results from the database I'm sure you're aware of how to do this.
For your radio buttons you're going to want to select your 'size' value from the database and use an if statement to determine which radio button will be 'checked'
forename/surname is a matter of simply getting the forename/surname from database and setting the appropriate input tags to the acquired values
You've already posted a technique for handling the combo/drop-down boxes
you'd perform a similar process for the 'type' checkboxes, compare your database values to the values of your checkbox input tags and if the value matches, set the checkbox to checked.
Next time please be more specific in what you are asking for help with and separate your code into segments that correspond with the files it is contained in.
if you have 3 files, have a code block for each file.

Categories