Edit MySQL Row PHP - php

I'm trying to edit and update a row using PHP.
Here is the code:
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<div class="header">
<?php include 'header.php';?>
</div>
<center>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include_once('../connection.php');
// get results from database
$query = "SELECT EmployeeName, DOB, Age, StreetAddress, City, State, ZipCode,
Email, HomePhone, Wireless, JobTitle, id, HomeDept, Manager FROM headcount ORDER BY `headcount`.`EmployeeName` ASC";
$response = #mysqli_query($dbc, $query);
// display data in table
echo "<p><b>View All</b> | <a href='../employees/rides.php'>Rides</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Employee Name</th> <th>Home Department</th> <th>Job Title</th> <th>Edit</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysqli_fetch_array($response)){
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['EmployeeName'] . '</td>';
echo '<td>' . $row['HomeDept'] . '</td>';
echo '<td>' . $row['JobTitle'] . '</td>';
echo '<td>Edit</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
</center>
edit.php
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db("hwss") or die(mysql_error());
$UID = (int)$_GET['ID'];
$query = mysql_query("SELECT * FROM headcount WHERE id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$EmployeeName = $row['EmployeeName'];
$DOB = $row['DOB'];
$Age = $row['Age'];
$email = $row['email'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$UID;?>">
email: <input type="text" name="ud_email" value="<?=$email;?>"><br>
Name: <input type="text" name="ud_EmployeeName" value="<?=$EmployeeName?>"><br>
DOB: <input type="text" name="ud_dob" value="<?=$DOB?>"><br>
Age: <input type="text" name="ud_Age" value="<?=$Age?>"><br>
<input type="Submit">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</body>
</html>
When I click edit it says "No entry found" with the back link on each ID url. I understand that I don't have any Update code yet. I'm simply just trying to get it to display the data before adding the rest.
Error Message
Notice: Undefined index: ID in C:\xampp\htdocs\Scheduling\Employees\edit.php on line 5
No entry found. Go back

Use: $_GET['id']
$UID = (int)$_GET['id'];
instead of
$UID = (int)$_GET['ID'];

Related

PHP | Object not found! Simple CRUD

I am still trying out PHP and with database capability. I'm new to stack overflow as well.
I'm having a problem with updating and deleting a row in my database but for now updating is the concern and surely deletion will follow if I manage to get assisted for this.
I have database "dbSample" and it has 3 columns "id, name, address, email".
I am having problems redirecting correctly to my update classes and it shows an error every time.
Below is the said connection file:(sample/class/dbconnection.php):
<?php
/*
==============================SQL Connection=================================
*/
$connections = mysqli_connect("localhost","root","","dbSample"); //checks database connection
if(mysqli_connect_errno()){
echo '<script type="text/javascript">alert("' . "Database Status: " . mysqli_connect_error() . '")</script>';
}
?>
Below serves as my index php file(sample/dbsample.php):
<?php require 'class/dbconnection.php';?>
<html>
<head>
</head>
<body>
<div>
<?php include 'class/dbupdate.php'; ?>
</div>
</body>
</html>
Below is the said dbupdate file:(sample/class/dbupdate.php):
<?php
/*
==============================SQL Update=================================
*/
$view_query = mysqli_query($connections, "SELECT * FROM tblSample");
echo "<table border = '1'>";
echo "<tr>
<td>Name</td>
<td>Address</td>
<td>Email</td>
<td>Option</td>
</tr>";
while($row = mysqli_fetch_assoc($view_query)){ //make variables to hold the values from the table
$user_id = $row["id"];
$db_name = $row["name"];
$db_address = $row["address"];
$db_email = $row["email"];
//get the value id and pass it
echo "<tr>
<td>$db_name</td>
<td>$db_address</td>
<td>$db_email</td>
<td><a href='class/updatepass.php?id=$user_id'>Update</a></td>
</tr>";
}
echo "</table>";
?>
Below is the said updatepass file:(sample/class/updatepass.php):
<?php
require_once(__DIR__."\dbconnection.php");
$user_id = $_REQUEST["id"];
$get_record = mysqli_query($connections, "SELECT * FROM tblSample WHERE id='$user_id'");
while($row_edit = mysqli_fetch_assoc($get_record)){
$db_name = $row_edit["name"];
$db_address = $row_edit["address"];
$db_email = $row_edit["email"];
}
?>
<form method="POST" action="class/updatenow.php">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
Name: <input type="text" name="new_name" value="<?php echo $db_name; ?>">
<hr />
Address: <input type="text" name="new_address" value="<?php echo $db_address; ?>">
<hr />
Email: <input type="text" name="new_email" value="<?php echo $db_email; ?>">
<hr />
<input type="submit" value="Update">
</form>
Below is the said updatenow file:(sample/class/updatenow.php):
<?php
header('Content-Type: text/plain; charset=utf-8');
require_once(__DIR__."\class\updatepass.php");
require_once(__DIR__."\class\dbconnection.php");
$user_id = $_POST["id"];
$new_name = $_POST["new_name"];
$new_address = $_POST["new_address"];
$new_email = $_POST["new_email"];
mysqli_query($connections, "UPDATE tblSample SET name='$new_name', address='$new_address', email='$new_email' WHERE id='$user_id'");
echo '<script type="text/javascript">alert("' . "Record has been updated" . '")</script>';
header('location: dbsample.php');
?>
Thank you for the help in advance, I will deeply appreciate it.

Update query not functioning

I'm trying to develop a small "To Do List" application. The data for the app is stored in a database, and it needs to perform all CRUD operations. As it is right now, Select, Insert, and Delete work just fine. I'm stuck on updating though. The index.php page is shown below:
<?php
session_start();
require_once 'connect.php';
if (isset($_POST['DeleteTask'])) {
$sqldelete = "DELETE FROM Tasks WHERE dbTaskID = :bvTaskID";
$stmtdelete = $db->prepare($sqldelete);
$stmtdelete->bindValue(':bvTaskID', $_POST['taskID']);
$stmtdelete->execute();
echo "<div>Task successfully deleted</div>";
}
if (isset($_POST['theSubmit'])){
echo '<p>New task added</p>';
$formfield['ffTaskName'] = trim($_POST['taskName']);
$formfield['ffTaskDue'] = trim($_POST['taskDue']);
if(empty($formfield['ffTaskName'])){$errormsg .= "<p>Task field is empty.</p>";}
if(empty($formfield['ffTaskDue'])){$errormsg .= "<p>Deadline field is empty.</p>";}
if ($errormsg != "") {
echo "<div class='error'><p>Please fill out all fields before submitting.</p>";
echo $errormsg;
echo "</div>";
} else {
try {
$sqlinsert = 'INSERT INTO Tasks (dbTaskName, dbTaskDue, dbTaskDone)
VALUES (:bvTaskName, :bvTaskDue, :bvTaskDone)';
$stmtinsert = $db->prepare($sqlinsert);
$stmtinsert->bindValue(':bvTaskName', $formfield['ffTaskName']);
$stmtinsert->bindValue(':bvTaskDue', $formfield['ffTaskDue']);
$stmtinsert->bindValue(':bvTaskDone', 0);
$stmtinsert->execute();
echo "<div><p>There are no errors. Thank you.</p></div>";
} catch(PDOException $e){
echo 'ERROR!!!' .$e->getMessage();
exit();
}
}
}
$sqlselect = "SELECT * from Tasks";
$result = $db->prepare($sqlselect);
$result->execute();
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do Application</title>
</head>
<body>
<h1><u>To-Do List</u></h1>
<table border>
<tr>
<th>Task</th>
<th>Deadline</th>
<th>Status</th>
<th>Complete</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php
while ($row = $result->fetch()) {
if ($row['dbTaskDone'] == 0) {
$status = "Unfinished";
} else {
$status = "Finished";
}
echo '<tr><td>' . $row['dbTaskName']
. '</td><td>' . $row['dbTaskDue']
. '</td><td>' . $status;
/*if ($status == "Unfinished"){
echo '</td><td>';
echo '<form action="'. $_SERVER['PHP_SELF'] . '" method="post">';
echo '<input type="hidden" name="taskID" value"' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="CompleteTask" value="Complete Task">';
echo '</form>';
}*/
echo '</td><td>';
echo '<form action="updateTask.php" method="post">';
echo '<input type="hidden" name="taskID" value="' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="EditTask" id="EditTask" value="Edit Task">';
echo '</form></td><td>';
echo '<form action="'. $_SERVER['PHP_SELF'] . '" method="post">';
echo '<input type="hidden" name="taskID" value="' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="DeleteTask" value="Delete Task">';
echo '</td></tr>';
}
?>
</table>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="toDoForm">
<fieldset><legend>New Task</legend>
<table>
<tr>
<th>Task</th>
<td><input type="text" name="taskName" id="taskName"
value="<?php echo $formfield['ffTaskName']; ?>"></td>
</tr><tr>
<th>Deadline</th>
<td><input type="text" name="taskDue" id="taskDue"
value="<?php echo $formfield['ffTaskDue']; ?>"></td>
</tr>
</table>
<input type="submit" name = "theSubmit" value="Add Task">
</fieldset>
</form>
</body>
</html>
Each record displays an "Edit" button that grabs the PK from the "Tasks" table and sends it to the updateTask.php page:
<?php
require_once 'connect.php';
$errormsg = "";
if (isset($_POST['EditTask']) ) {
$formfield['ffTaskID'] = $_POST['taskID'];
$sqlselect = "SELECT * FROM Tasks WHERE dbTaskId = :bvTaskID";
$result = $db->prepare($sqlselect);
$result->bindValue(':bvTaskID', $formfield['ffTaskID']);
$result->execute();
$row = $result->fetch();
if( isset($_POST['theEdit']) )
{
$formfield['ffTaskID'] = $_POST['taskID'];
$formfield['ffTaskName'] = trim($_POST['taskName']);
$formfield['ffTaskDue'] = trim($_POST['taskDue']);
if(empty($formfield['ffTaskName'])){$errormsg .= "<p>Task field is empty.</p>";}
if(empty($formfield['ffTaskDue'])){$errormsg .= "<p>Deadline field is empty.</p>";}
if ($errormsg != "") {
echo "<div class='error'><p>Please fill out all fields before submitting.</p>";
echo $errormsg;
echo "</div>";
} else {
try
{
$sqlUpdate = "UPDATE Tasks SET dbTaskName = :bvTaskName,
dbTaskDue = :bvTaskDue
WHERE dbTaskID = :bvTaskID";
$stmtUpdate = $db->prepare($sqlUpdate);
$stmtUpdate->bindvalue(':bvTaskName', $formfield['ffTaskName']);
$stmtUpdate->bindvalue(':bvTaskDue', $formfield['ffTaskDue']);
$stmtUpdate->bindvalue(':bvTaskID', $formfield['ffTaskID']);
$stmtUpdate->execute();
}
catch(PDOException $e)
{
echo 'ERROR!!!' .$e->getMessage();
exit();
}
}
}
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do Application</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="editForm">
<fieldset><legend>Edit Task</legend>
<table>
<tr>
<th>Task</th>
<td><input type="text" name="taskName" id="taskName"
value="<?php echo $row['dbTaskName'];?>" ></td>
</tr><tr>
<th>Deadline</th>
<td><input type="text" name="taskDue" id="taskDue"
value="<?php echo $row['dbTaskDue']; ?>"></td>
</tr>
<tr>
<th>Submit Changes</th>
<input type="hidden" name="taskID" value="<?php echo $_formfield['ffTaskID']; ?>">
<td><input type="submit" name="theEdit" value="Submit Changes">
</table>
</fieldset>
</form>
</body>
</html>
The Name and Deadline fields populate appropriately based on the PK value passed from the last page. However, whenever I press the "Submit Changes" button, the update doesn't seem to execute. The page just refreshes and I see the table data remains unchanged in the database.
Solved the problem!
There were several issues that I discovered.
1.) In updateTask.php, I had the second if-statement nested within the first one. So it was running the update query as the page loaded, with no change to the data. So the 'theEdit' button did nothing since since it required the previous if statement's condition to run.
2.) The formfield 'ffTaskID' at the bottom of the form on updateTask.php to be passed on the 'theEdit' button press was typed incorrectly.
$_formfield
..should have been..
$formfield
At this point, the update query functions properly.
3.) The issue with the 'Edit' buttons has been fixed. Though I honestly can't say for certain how it was fixed. It may have been linked with the first part of the problem. So when that was fixed, so was this.
Either way, all seems to be functioning as it should. Thanks again to everyone who commented and helped.

Updating data in PHP

I am using editing file for updating data of mobile no, email details etc, but it is not updating , it shows the results of data so connection is working but no updating of data is there. code:
<?php
include('header.php');
$msg='';
?>
<div class="page-cont1">
<!--heading starts-->
<?php
session_start(); //starts the session
if($_SESSION['user']){ //checks if user is logged in
}
else{
header("location:index.php"); // redirects if user is not logged in
}
$user = $_SESSION['user']; //assigns user value
$id_exists = false;
?>
<body>
<h2>Home Page</h2>
<p>Hello <?php Print "$user"?>!</p> <!--Displays user's name-->
Click here to logout<br/><br/>
Return to Home page
<h2 align="center">Currently Selected</h2>
<table border="1px" width="100%">
<tr>
<th>Id</th>
<th>E-Mail</th>
<th>Mobile No</th>
<th>Details</th>
<th>Extra Information</th>
</tr>
<?php
if(!empty($_GET['id']))
{
$id = $_GET['id'];
$_SESSION['id'] = $id;
$id_exists = true;
$query = mysql_query("Select * from doctor Where id='$id'"); // SQL Query
$count = mysql_num_rows($query);
if($count > 0)
{
while($row = mysql_fetch_array($query))
{
Print "<tr>";
Print '<td align="center">'. $row['id'] . "</td>";
Print '<td align="center">'. $row['your_email'] . "</td>";
Print '<td align="center">'. $row['mobile_no'] . "</td>";
Print '<td align="center">'. $row['detail'] . "</td>";
Print '<td align="center">'. $row['info'] . "</td>";
Print "</tr>";
}
}
else
{
$id_exists = false;
}
}
?>
</table>
<br/>
<?php
if($id_exists)
{
Print '
<form action="edit.php" method="POST">
Enter new E-Mail: <input type="text" name="your_email"/><br/>
Enter new Mobile: <input type="text" name="mobile_no"/><br/>
Enter new detail: <input type="text" name="detail"/><br/>
Enter new Extra Information: <input type="text" name="info"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
else
{
Print '<h2 align="center">There is no data to be edited.</h2>';
}
?>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$field_email = mysql_real_escape_string($_POST['your_email']);
$field_phone = mysql_real_escape_string($_POST['mobile_no']);
$detail = mysql_real_escape_string($_POST['detail']);
$field_message = mysql_real_escape_string($_POST['info']);
mysql_query("UPDATE doctor SET your_email='$field_email', mobile_no='$field_phone', detail='$detail', info='$field_message' WHERE id='$id'") ;
header("location: home.php");
}
?>
<?php
include('footer.php');
$msg='';
?>
</body>
More over header file includes the connect file, and one query form is there problem lie in header file or problem in edit file.
First replace DOCTOR with doctor in update query (as Utharsh has stated).
Second:
You'll have to include the id in your form to be posted.
Print '<form action="edit.php" method="POST">
Enter new E-Mail: <input type="text" name="your_email"/><br/>
Enter new Mobile: <input type="text" name="mobile_no"/><br/>
Enter new detail: <input type="text" name="detail"/><br/>
Enter new Extra Information: <input type="text" name="info"/><br/>
<input type="hidden" name="id" value="'.$id.'">
<input type="submit" value="Update List"/>
</form>';
replace DOCTOR withdoctor in your update query.
If problem persists than try to hard code your query and execute it in phpmyadmin.
put a hidden field in your form with reference to the id as jeff stated
After receiving ans i studied my code in the ans i read about ID so i noticed that in updating there is no ID reference so i changed my code now problem solved my working code is:
<?php
include('header.php');
$msg='';
?>
<div class="page-cont1">
<!--heading starts-->
<?php
session_start(); //starts the session
if($_SESSION['user']){ //checks if user is logged in
}
else{
header("location:index.php"); // redirects if user is not logged in
}
$user = $_SESSION['user']; //assigns user value
$id_exists = false;
?>
<body>
<h2>Home Page</h2>
<p>Hello <?php Print "$user"?>!</p> <!--Displays user's name-->
Click here to logout<br/><br/>
Return to Home page
<h2 align="center">Currently Selected</h2>
<table border="1px" width="100%">
<tr>
<th>Id</th>
<th>E-Mail</th>
<th>Mobile No</th>
<th>Details</th>
<th>Extra Information</th>
</tr>
<?php
if(!empty($_GET['id']))
{
$id = $_GET['id'];
$_SESSION['id'] = $id;
$id_exists = true;
$query = mysql_query("Select * from doctor Where id='$id'"); // SQL Query
$count = mysql_num_rows($query);
if($count > 0)
{
while($row = mysql_fetch_array($query))
{
Print "<tr>";
Print '<td align="center">'. $row['id'] . "</td>";
Print '<td align="center">'. $row['your_email'] . "</td>";
Print '<td align="center">'. $row['mobile_no'] . "</td>";
Print '<td align="center">'. $row['detail'] . "</td>";
Print '<td align="center">'. $row['info'] . "</td>";
Print "</tr>";
}
}
else
{
$id_exists = false;
}
}
?>
</table>
<br/>
<?php
if($id_exists)
{
Print '
<form action="edit.php" method="POST">
Enter new E-Mail: <input type="text" name="your_email"/><br/><br/>
Enter new Mobile: <input type="text" name="mobile_no"/><br/><br/>
Enter new detail: <textarea name="detail" rows="6" id="detail" style="width:200px;"></textarea><br/><br/>
Enter new Extra Information: <textarea name="info" rows="4" id="info" style="width:200px;"></textarea><br/><br/>
<input type="hidden" name="id" value="'.$id.'">
<input type="submit" value="Update List"/>
</form>
';
}
else
{
Print '<h2 align="center">There is no data to be edited.</h2>';
}
?>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$field_email = mysql_real_escape_string($_POST['your_email']);
$field_phone = mysql_real_escape_string($_POST['mobile_no']);
$detail = mysql_real_escape_string($_POST['detail']);
$field_message = mysql_real_escape_string($_POST['info']);
$id = $_SESSION['id'];
mysql_query("UPDATE doctor SET your_email='$field_email', mobile_no='$field_phone', detail='$detail', info='$field_message' WHERE id='$id'") ;
header("location: home.php");
}
?>
<?php
include('footer.php');
$msg='';
?>
</body>

Getting dependant data from two tables

I'm trying to create a page which uses session data to find a user in a database and then sends the events that this user has signed up to. I'm a bit of a newbie and have got very confused with where I am at. I am using two different tables to get the data, and this is where I'm getting confused and where I believe the errors are occurring. Thanks in Advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<?php
$username = $_SESSION['username'];
$email = $_SESSION['user_email'];
$con=mysqli_connect("localhost","emuas","******","EMUAS_signUp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<table>
<tr>
<td> Logged in as:</td>
</tr>
<tr>
<th>" . $username . "</th>
</tr>
<tr>
<td>
<form action='logout.php' method='post'>
<input type='submit' value='Logout' >
</form>
</td>
</tr>
<tr>
<th>Events Attending:</th>
</tr>";
$find = mysqli_query($con,"SELECT * FROM SIGN_UP_TEST WHERE User = '$username'");
while($find_row = mysqli_fetch_array($find)){
//Get Event ID
$eventId = $find_row['EventID'];
//Use Event ID to get Event Name
$result = mysqli_query($con,"SELECT * TEST WHERE EventID = '$eventId'");
//Insert Event Name into table with link from Page Name
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> <a href='http://www.emuas.co.uk/members/sign_up_sheets/S" . $row['PageName'] . ".php'>" . $row["EventName"] . "</a> </td>";
echo "</tr>";
}
}
echo "</table>";
?>
<body>
</body>
</html>

Rows and Columns validation of an Array after form submitted

I have two PHP files:
1) simplearraypost.php (containing the form)
2) echoarraypost.php (the validation of the form)
The form have 3 columns, which are
1) Row Number
2) Item Number
3) Description
Now, if posted, need validation per each cell of rows & columns!
Codes for both pasted here separately.
simplearraypost.php
<html>
<body>
<form name="insertitem" method="post" action="echoarraypost.php">
<table border="1">
<thead>
<tr>
<th>Row No.</th>
<th>Item</th>
<th>Description</th>
</tr>
</thead>
<?php
// Number of rows
$number = 10;
// Create rows
for ($i = 1; $i <= $number; $i++) {
echo ' <tr>' . "\n";
echo ' <td align="right">' . $i . '</td>' . "\n";
echo ' <td><input type="text" name="itemno[]" size="5"></td>' . "\n";
echo ' <td><input type="text" name="description[]" size="50"></td>' . "\n";
echo ' </tr>' . "\n";
}
?>
<tr>
<td colspan="4" align="right"><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
echoarraypost.php
<?php
// store all posted item numbers and descriptions in local arrays
$itemnos = $_POST['itemno'];
$descriptions = $_POST['description'];
// loop through array
$number = count($itemnos);
for ($i = 0; $i < $number; $i++) {
// store a single item number and description in local variables
$itno = $itemnos[$i];
$desc = $descriptions[$i];
// this is where your insert should be (instead of the echo),
// insert the single values in $itnm and $desc
if ($itemnos[$i] <> "") {
echo "Item: " . $itno . " Description: " . $desc . "<p>";
}
else {
echo 'Error in row(s): ' . $i . ', <br>' . "\n"; // <-- How can I make this show the Row ID?
}
/* Un-Comment for checking posted info
// Check POST array
foreach ($_POST as $key => $value) {
echo '<p>'.$key.'</p>';
foreach($value as $k => $v) {
echo $k.'<br/>';
echo $v;
}
}
*/
}
?>
Your help is very much appreciated!
samimi_it
For anyone interested in the same issue,here is the final result I managed to come up with.
Comments and corrections are most welcome.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org /TR/xhtml1 /DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Multiple Adds</title>
</head>
<body>
<?php
// Get todays date fo day of signup entry
$today = date("Y.m.d H:i:s");
// Add one year to date of singup for login validity
$nextyear = date('Y.m.d H:i:s', strtotime('+1 year'));
/*
// Table to create which is used in this demo
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(155) NOT NULL,
`sname` varchar(155) NOT NULL,
`lname` varchar(155) NOT NULL,
`email` varchar(155) NOT NULL,
`dob` varchar(155) NOT NULL,
`date_signup` datetime NOT NULL,
`date_expire` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
*/
// Set LOCALHOST mysql server connection parameters
define('DB_HOST', 'localhost'); // Change to your own
define('DB_USER', 'root'); // Change to your own
define('DB_PASSWORD', ''); // Change to your own
define('DB_DATABASE', 'test'); // Change to your own
// Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
// Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
// Create the Form with multiple rows
echo '<form id="addusers" name="addusers" method="post">';
echo '<table border="1">';
echo '<tr><thead>
<th>RID</th><th>First Name</th>
<th>Second Name</th>
<th>Last Name</th>
<th>eMail</th>
<th>DOB</th>
<thead></tr>';
for($rid=1;$rid <= 10; $rid++)
{
echo '<tr>
<td align="right"><label>'.$rid.'</label></td>
<td><input id="fname[]" name="fname[]" type="text" size="30" /></td>
<td><input id="sname[]" name="sname[]" type="text" size="30" /></td>
<td><input id="lname[]" name="lname[]" type="text" size="30" /></td>
<td><input id="email[]" name="email[]" type="text" size="40" /></td>
<td><input id="dob[]" name="dob[]" type="text" size="10" /></td>
</tr>';
}
echo '<td colspan="6" align="middle"><input name="submit" id="submit" type="submit" value="Add Users"></td>';
echo '</table>';
echo '</form>';
echo '<hr>';
// Check for post errors for each field in each row, and prepare error flag and message for display
$error=false;
$errormsg="<ul><font color='red'><b><u>Please correct the error(s) in row(s): </font></b></u><br><br>";
for($x=0;$x < count($_POST['fname']); $x++){
if(!$_POST['fname'][$x]){
$rowNum = $x+1;
$errormsg.="<li>Row $rowNum: First Name</li>";
$error=true;
}
if(!$_POST['sname'][$x]){
$rowNum = $x+1;
$errormsg.="<li>Row $rowNum: Second Name</li>";
$error=true;
}
if(!$_POST['lname'][$x]){
$rowNum = $x+1;
$errormsg.="<li>Row $rowNum: Last Name</li>";
$error=true;
}
if(!$_POST['email'][$x]){
$rowNum = $x+1;
$errormsg.="<li>Row $rowNum: Email Address</li>";
$error=true;
}
if(!$_POST['dob'][$x]){
$rowNum = $x+1;
$errormsg.="<li>Row $rowNum: Date of Birth</li>";
$error=true;
}
}
if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST'){
if($error){
// Print Errors
$errormsg.= "<br><font color='red'><b><u>Errors, no data
posted!</font></b></u></ul><br>";
echo $errormsg;
echo "<p>Please <a href='javascript:history.back()'><< Go Back</a> and correct!</p>";
}else{
// Print Data submitted and Insert data into DB, but with teration for one time bulk insert of all
$query = "insert into users (fname,sname,lname,email,dob,date_signup,date_expire) values ";
$count = count($_POST['fname']);
for($x=0;$x < $count; $x++)
{
$fname = $_POST['fname'][$x];
$sname = $_POST['sname'][$x];
$lname = $_POST['lname'][$x];
$dob = $_POST['dob'][$x];
$email = $_POST['email'][$x];
echo $fname . $sname . $lname . $dob . $email . '<br>';
$query .= "(
'$fname',
'$sname',
'$lname',
'$email',
'$dob',
'$today',
'$nextyear')";
/* If not last iteration, add a comma and a space */
if ($x < ($count - 1)) {
$query .= ", ";
}
$result = mysql_query($query);
}
if(!$result){
die(mysql_error());
#mysql_free_result($result);
} else {
$totalRID = mysql_affected_rows();
$lastRID = mysql_insert_id()-1;
$q = "SELECT LAST_INSERT_ID() FROM users";
$numRowsInerted = mysql_num_rows(mysql_query($q));
echo "Total of <b>" . $totalRID . " </b> rows/records entered into the table!" . "<br>";
echo "Last record number before this bulk insert was: <b>" . $lastRID .
"</b><br>Last record number after this bulk insert is: <b> " . $numRowsInerted . " </b><br>";
}
}
}
echo '<hr>';
// Remaining code hereafter is to get the Table records for display
//get the number of total rows
$query = "SELECT * FROM users";
$result = mysql_query($query);
// Number of records found
$num_record = mysql_num_rows($result);
echo 'Total number of users: ' . $num_record;
echo '<table border="1">';
echo '<tr><thead>
<th>RID</th><th>First Name</th>
<th>Second Name</th>
<th>Last Name</th>
<th>eMail</th>
<th>DOB</th>
<th>Member Signup Date</th>
<th>Member Renewal Date</th>
<thead></tr>';
//here you do your loop like
while($row=#mysql_fetch_object($result)) {
echo '<tr>
<td align="right">'.$row->id.'</td>'.
'<td>'.$row->fname.'</td>'.
'<td>'.$row->sname.'</td>'.
'<td>'.$row->lname.'</td>'.
'<td>'.$row->email.'</td>'.
'<td>'.$row->dob.'</td>'.
'<td>'.$row->date_signup.'</td>'.
'<td>'.$row->date_expire.'</td>'.
'</tr>';
}
echo '</table>';
?>
</body>
</html>

Categories