Query Data From Database Using Date Range in PHP/MySQL - php

I am new here is the script index.php of query data from database using date range in PHP/MySQL.
<link rel="stylesheet" type="text/css" href="tcal.css" />
<script type="text/javascript" src="tcal.js"></script>
<form action="index.php" method="get">
From : <input type="text" name="d1" class="tcal" value="" /> To: <input type="text" name="d2" class="tcal" value="" /> <input type="submit" value="Search">
</form>
<table id="resultTable" data-responsive="table" style="text-align: left; width: 400px;" border="1" cellspacing="0" cellpadding="4">
<thead>
<tr>
<th> Birtday </th>
<th> Name </th>
<th> Gender </th>
</tr>
</thead>
<tbody>
<?php
include('connect.php');
if (isset($_GET["d1"])) { $d1 = $_GET["d1"]; } else { $d1=0; };
if (isset($_GET["d2"])) { $d2 = $_GET["d2"]; } else { $d2=0; };
$result = $db->prepare("SELECT * FROM birthday WHERE date BETWEEN :a AND :b");
$result->bindParam(':a', $d1);
$result->bindParam(':b', $d2);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr class="record">
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['gender']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
Now in this script we have 2 calenders for using the date range... Some one here who edit this script make into only 1 calender for selecting date.

PHP stores dates in the format "YYYY-MM-DD". I presume that the input for calendar would return date in the above format.
Rest of the code looks pretty good to me but you need to change this
{ $d1=0; };
To
{ $d1="0000-00-00"; };

If you remove references to d2 and change the query to this, it should work:
$result = $db->prepare("SELECT * FROM birthday WHERE date = :a ");

Related

Can't echo data from phpmyadmin

Am was already created form like this and working perfect but on last two forms not working, it displays warning-Undefined variable: reg_no and cost. Am trying to follow algorithm as previous forms but nothing happen. My goal is to update inserted data and here is my form
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit invoice</title>
<link rel="stylesheet" href="box_style.css" />
</head>
<body>
<?php
include ("db_con.php");
if(isset($_GET['edit_invoice'])){
$edit_i_id = $_GET['edit_invoice'];
$select_invoice = "select * from invoice where i_id='$edit_i_id'";
$run_query = mysqli_query($con, $select_invoice);
while ($row_invoice=mysqli_fetch_array($run_query)){
$i_id = $row_invoice['i_id'];
$reg_no = $row_invoice['reg_no'];
$cost = $row_invoice['cost'];
}
}
?>
<div class='form'>
<form action="" method="post" enctype="multipart/form-data" >
<table width="745" align="center" border="2">
<p style="text-align: center;"><strong><span style="text-decoration: underline;">EDIT INVOICE:</span></strong></p>
<tr>
<td align="right" bgcolor="#dbe5f1"><strong>Registration Number:</strong></td>
<td><input type="text" name="reg_no" id="reg_no" size="35" class="text" placeholder="Registration Number" value="<?php echo $reg_no; ?>" required=""/></td>
</tr>
<tr>
<td align="right" bgcolor="#dbe5f1"><strong>Cost(Tshs):</strong></td>
<td><input type="text" name="cost" id="cost" size="35" class="text" placeholder="Cost" value="<?php echo $cost; ?>" required=""/></td>
</tr>
<tr>
<td colspan="6" align="center" bgcolor="#dbe5f1" ><input type="submit" name="update" class="submit-button" value="SAVE CHANGES"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Remove while loop from your php code since update is for one record based on id
The code will be as :
if(isset($_GET['edit_invoice'])){
$edit_i_id = $_GET['edit_invoice'];
$select_invoice = "select * from invoice where i_id='$edit_i_id'";
$run_query = mysqli_query($con, $select_invoice);
$row_invoice = mysqli_fetch_array($run_query);
$i_id = $row_invoice['i_id'];
$reg_no = $row_invoice['reg_no'];
$cost = $row_invoice['cost'];
}
if isset($_GET['edit_invoice']) is false, your $reg_no is not present in later script (where you want to echo it).
Put $reg_no above your isset($_GET...) check and set it null or empty string.
$reg_no = null;
if (isset($_GET['edit_invoice'])) {
// your code...
}
Edit: Do the same for $cost and $i_id ;)
PLEASE consider Tom Uddings comment with SQL injections!

Best Way to Submit Dynamic Repeating Form

I'm trying to teach myself php and mysql and I'm having trouble with a form I'm working on for a football pool I'm trying to put together. I'm looking for a little help on the best way to submit the data from this form. The form gets data from my database and repeats for the appropriate number of rows. Upon submitting the form each row should be inserted or updated to the database. The data that needs to be submitted is: userid, gameid, pick, and tbPoints.
The form is a little rough as I have not finished it yet. I just cant seem to get the form to submit each row as a new entry to the database, it only submits the last game. I know I have a problem with the loop to submit, but I just can't seem to figure out how to get it. Any help is appreciated!
here is my form:
<?php require_once('Connections/t2016.php'); ?>
<?php
mysql_select_db($database_t2016, $t2016);
$query_gamedays = "SELECT DISTINCT schedule.weekDay, schedule.`date` FROM schedule WHERE schedule.weekNum=1";
$gamedays = mysql_query($query_gamedays, $t2016) or die(mysql_error());
$row_gamedays = mysql_fetch_assoc($gamedays);
$totalRows_gamedays = mysql_num_rows($gamedays);
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post" name="form1">
<table border="2" cellpadding="3" cellspacing="2">
<tr align="center">
<td>Time</td>
<td colspan="3">Matchup</td>
<td>Current Pick</td>
</tr>
<?php do {
$day = $row_gamedays['weekDay'];
$date = $row_gamedays['date'];
?>
<tr wrap="nowrap">
<td colspan="5"><?php echo '<strong>'.$day.'</strong>, '.$date; ?></td>
</tr>
<?php
mysql_select_db($database_t2016, $t2016);
$query_sched = "SELECT * FROM schedule WHERE schedule.weekNum=1 AND schedule.weekDay='$day'";
$sched = mysql_query($query_sched, $t2016) or die(mysql_error());
$row_sched = mysql_fetch_assoc($sched);
$totalRows_sched = mysql_num_rows($sched);
?>
<?php do {
$gameid = $row_sched['gameID'];
$time = $row_sched['time'];
$vteam = $row_sched['visitorID'];
$hteam = $row_sched['homeID'];
mysql_select_db($database_t2016, $t2016);
$query_picks = "SELECT * FROM picks WHERE picks.gameID=$gameid AND picks.userID=1";
$picks = mysql_query($query_picks, $t2016) or die(mysql_error());
$row_picks = mysql_fetch_assoc($picks);
$totalRows_picks = mysql_num_rows($picks);
if($totalRows_picks > 0) {
$pick = $row_picks['pickID'];
$tbp = $row_picks['tiebreakerPoints'];
} else {
$pick = 'No Pick';
$tbp = '0';
}
$vp = '';
$hp = '';
if($pick == $vteam) {
$vp = 'checked';
} elseif($pick == $hteam) {
$hp = 'checked';
}
?>
<tr align="center">
<td><?php echo $time; ?></td>
<td align="right"><?php echo $vteam.'<input type="radio" name="pickID'.$gameid.'[]" value="'.$vteam.'" '.$vp.'>'; ?></td>
<td align="center"> # </td>
<td align="left"><?php echo '<input type="radio" name="pickID'.$gameid.'[]" value="'.$hteam.'" '.$hp.'>'.$hteam; ?></td>
<td><?php echo $pick; ?></td>
</tr>
<?php if($row_sched['is_tiebreaker'] > 0) { ?>
<tr>
<td colspan="4" align="right" wrap="nowrap"><?php echo 'Enter Tiebreaker Points: <input type="number" name="tbpoints[]" min="0" value="'.$tbp.'">'; ?></td>
<td align="center"><?php echo $tbp; ?></td>
</tr>
<?php } ?>
<input type="hidden" name="gameID[]" value="$gameid">
<input type="hidden" name="userID" value="1">
<?php } while ($row_sched = mysql_fetch_assoc($sched)); ?>
<tr>
<?php } while ($row_gamedays = mysql_fetch_assoc($gamedays)); ?>
<td colspan="5" align="right" wrap="nowrap">
<input type="submit" name"submit" value="Submit Picks">
</td>
</tr>
</table>
</form>
<p> </p>
</body>
</html>
<?php
mysql_free_result($sched);
mysql_free_result($picks);
mysql_free_result($gamedays);
?>
again, the form is really rough so please be kind. Thanks for the help
You just loop through these values like a normal array.
$gameID = $_POST['gameID'];
for($x=0; $x<count($gameID); $x++ ) { .... }
As for the radio buttons/check boxes - you need to give each group a unique name. The only thing to remember with these controls is that if that are not set then nothing is submitted to the server. You need to check if they are part of the post values i.e.
if( isset( $_POST['cbPoints'] ) ) { do something }
Otherwise you'll get errors when trying to access them.

Copy data from HTML table to another HTML page

I'm not a complete noob, but I don't have more than a handful of months experience with HTML any help with this will be appreciated. I have a webpage that shows a table with several columns and several rows. I have an Edit link at the end of each row that takes you to another page that is supposed to make the data in the row editable. I can make the first page and the link takes me to another page, but i can't figure out how to get the data from the table row on the first page and put into the table on the second page. I want it to go from a table with 1 row selected to a table with 2 columns and 1 row for each of the columns in the first table.
Here's the page with the table:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Testing PHP</title>
<link rel="StyleSheet" href="StyleSheet.css" type="text/css">
</head>
<body>
<!--h2>This will pull down all the Names from the QDef table</h2-->
<link rel="StyleSheet" type="text/css" href="StyleSheet.css">
<p>4 Results</p>
<table class="tab"id="NameTable">
<thead>
<tr>
<th class="cell">Edit</th>
<th class="cell">TempID</th>
<th class="cell">Name</th>
<th class="cell">CountryCode</th>
<th class="cell">Budget</th>
<th class="cell">Used</th>
</tr>
</thead>
<tbody>
<tr class="row1">
<td>
Edit
</td>
<td contenteditable>1</td>
<td contenteditable>Win Temp</td>
<td contenteditable>TH</td>
<td contenteditable>1000000.000000000</td>
<td contenteditable>60000.000000000</td>
</tr>
</tbody>
<tbody>
<tr class="row">
<td>
Edit
</td>
<td contenteditable>2</td>
<td contenteditable>Test Temp</td>
<td contenteditable>UK</td>
<td contenteditable>100000.000000000</td>
<td contenteditable>5000.000000000</td>
</tr>
</tbody>
<tbody>
<tr class="row1">
<td>
Edit
</td>
<td contenteditable>3</td>
<td contenteditable>Number 3</td>
<td contenteditable>UK</td>
<td contenteditable>1000000.000000000</td>
<td contenteditable>50000.000000000</td>
</tr>
</tbody>
<tbody>
<tr class="row">
<td>
Edit
</td>
<td contenteditable>4</td>
<td contenteditable>Number 4</td>
<td contenteditable>US</td>
<td contenteditable>50000.000000000</td>
<td contenteditable>.000000000</td>
</tr>
</tbody>
</table>
<br/>
</body>
</html>
Here's the Page that is supposed to allow me to edit the data from the table in the first page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>FormToEditMaterial</title>
<link rel="StyleSheet" href="StyleSheet.css" type="text/css">
</head>
<body>
<table id="FormToEditMaterialTable">
<tr>
<th contenteditable="false" >Field Name</th>
<th contenteditable="false">Field to be edited</th>
</tr>
<tr contenteditable>
<td id="TempIDColumn" contenteditable="false">Name of Field</td>
<td>Data to be updated</td>
</tr>
<tr contenteditable>
<td id="NameColumn" contenteditable="false">Name of field 2</td>
<td>Data 2 to be updated</td>
</tr>
<tr contenteditable>
<td id="CountryCodeColumn" contenteditable="false">Name of field 3</td>
<td>Data 3 to be updated</td>
</tr>
<tr contenteditable>
<td id="BudgetColumn" contenteditable="false">Name of field 4</td>
<td>Data 4 to be updated</td>
</tr>
<tr contenteditable>
<td id="UsedColumn" contenteditable="false">Name of field 5</td>
<td>Data 5 to be updated</td>
</tr>
</table>
<br/>
<input type="button" name="SubmitUpdate" class="ok" value="Submit Update"/>
</body>
</html>
I've seen where people use forms and $POST to get the data from one page to another, but I'm not using a form. I'm actually using PHP and this is the resulting HTML and what is being pulled from the SQL server. However, I just need help with getting this working in HTML, I will figure out how to translate it into the PHP. Here is what the files look like that I'm working with:
JSFiddle TestingPHP - First Table
JSFiddle FormToEditMaterial - Second Table
If you need more info let me know and I'll provide what ever I can.
Edit
Here's the updated FormToEditMaterial file, I did not update the JSFiddle:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>FormToEditMaterial</title>
<link rel="StyleSheet" href="StyleSheet.css" type="text/css">
</head>
<body>
<table id="FormToEditMaterialTable">
<tr>
<th contenteditable="false" >Field Name</th>
<th contenteditable="false">Field to be edited</th>
</tr>
<tr contenteditable>
<td id="TempIDColumn" contenteditable="false">Name of Field</td>
<td>Data to be updated</td>
</tr>
<tr contenteditable>
<td id="NameColumn" contenteditable="false">Name of field 2</td>
<td>Data 2 to be updated</td>
</tr>
<tr contenteditable>
<td id="CountryCodeColumn" contenteditable="false">Name of field 3</td>
<td>Data 3 to be updated</td>
</tr>
<tr contenteditable>
<td id="BudgetColumn" contenteditable="false">Name of field 4</td>
<td>Data 4 to be updated</td>
</tr>
<tr contenteditable>
<td id="UsedColumn" contenteditable="false">Name of field 5</td>
<td>Data 5 to be updated</td>
</tr>
</table>
<br/>
<input type="button" name="SubmitUpdate" class="ok" value="Submit Update"/>
<br/>
<br/>
<form>
TempID: <input type="text" name="1"><br>
Name: <input type="text" name="2"><br>
CountryCode: <input type="text" name="3"><br>
Budget: <input type="text" name="4"><br>
Used: <input type="text" name="5"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
EDIT 2
Here's the new FormToEditMaterial.php:
<?php
$servername = "ServerName";
$username = "User";
$password = "Password";
$dbname = "DBName";
$db = new PDO("sqlsrv:server=$servername;database=$dbname", $username,$password);
$row = array();
if (isset($_POST['submit']))
{
$row = $_POST;
$q = 'UPDATE dbo.MyTable SET Name = ?, CountryCode = ?, Budget = ?, Used = ? WHERE TempID = ?';
$sth = $db->prepare($q);
$sth->execute(array($row['Name'], $row['CountryCode'], $row['Budget'], $row['Used'], $row['TempID']));
print_r($db->errorInfo());
echo "<br>";
var_dump($sth);
echo "<br>";
var_dump($row);
if ($sth->rowCount() == 1) header('Location: Index.php');
}
else if (!empty($_GET['id']))
{
$q = 'SELECT TempID, Name, CountryCode, Budget, Used FROM MyTable WHERE TempID = ?';
$sth = $db->prepare($q);
$sth->execute(array($_GET['id']));
$row = $sth->fetch();
}
else
{
// Show error message here
}
?>
<link rel="StyleSheet" href="stylesheet.css" type="text/css">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<p>
<label>TempID:
<input type="text" name="TempID" value="<?php echo $row['TempID']?>"></label>
</p>
<p>
<label>Name:
<input type="text" name="Name" value="<?php echo $row['Name']?>"></label>
</p>
<p>
<label>CountryCode:
<input class="CountryCode" type="text" name="CountryCode" value="<?php echo $row['CountryCode']?>"></label>
</p>
<p>
<label>Budget:
<input type="text" name="Budget" value="<?php echo $row['Budget']?>"></label>
</p>
<p>
<label>Used:
<input type="text" name="Used" value="<?php echo $row['Used']?>"> </label>
</p>
<p>
<input type="submit" name="submit" value="Submit">
</p>
</form>
And here's the Index.php:
<?php
$servername = "ServerName";
$username = "User";
$password = "Password";
$dbname = "DBName";
$db = new PDO("sqlsrv:server=$servername;database=$dbname", $username,$password);
$q = 'SELECT TempID, Name, CountryCode, Budget, Used FROM MyTable';
?>
<link rel="StyleSheet" href="stylesheet.css" type="text/css">
<table>
<thead>
<tr>
<th>Edit</th>
<th>TempID</th>
<th>Name</th>
<th>CountryCode</th>
<th>Budget</th>
<th>Used</th>
</tr>
</thead>
<tbody>
<?php foreach ($db->query($q) as $row) :?>
<tr>
<td>Edit</td>
<td><?php echo $row['TempID']?></td>
<td><?php echo $row['Name']?></td>
<td><?php echo $row['CountryCode']?></td>
<td><?php echo $row['Budget']?></td>
<td><?php echo $row['Used']?></td>
</tr>
<?php endforeach?>
</tbody>
</table>
I've made a quick example:
In index.php:
<?php
$db = new PDO('host', 'username', 'password');
$q = 'SELECT TempID, Name, CountryCode, Budget, Used FROM MyTable';
?>
<table>
<thead>
<tr>
<th>Edit</th>
<th>TempID</th>
<th>Name</th>
<th>CountryCode</th>
<th>Budget</th>
<th>Used</th>
</tr>
</thead>
<tbody>
<?php foreach ($db->query($q) as $row) :?>
<tr>
<td>Edit</td>
<td><?php echo $row['TempID']?></td>
<td><?php echo $row['Name']?></td>
<td><?php echo $row['CountryCode']?></td>
<td><?php echo $row['Budget']?></td>
<td><?php echo $row['Used']?></td>
</tr>
<?php endforeach?>
</tbody>
</table>
In FormToEditMaterial.php:
<?php
$db = new PDO('sqlite:db.sqlite3');
$row = array();
if (isset($_POST['submit']))
{
$row = $_POST;
$q = 'UPDATE MyTable SET Name = ?, CountryCode = ?, Budget = ?, Used = ? WHERE TempID = ?';
$sth = $db->prepare($q);
$sth->execute(
array($row['Name'], $row['CountryCode'], $row['Budget'], $row['Used'], $row['TempID'])
);
if ($sth->rowCount() == 1) header('Location: index.php');
}
else if (!empty($_GET['id']))
{
$q = 'SELECT TempID, Name, CountryCode, Budget, Used FROM MyTable WHERE TempID = ?';
$sth = $db->prepare($q);
$sth->execute(array($_GET['id']));
$row = $sth->fetch();
}
else
{
// Show error message here
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<p>
<label>TempID:
<input type="text" name="TempID" value="<?php echo $row['TempID']?>"></label>
</p>
<p>
<label>Name:
<input type="text" name="Name" value="<?php echo $row['Name']?>"></label>
</p>
<p>
<label>CountryCode:
<input type="text" name="CountryCode" value="<?php echo $row['CountryCode']?>"></label>
</p>
<p>
<label>Budget:
<input type="text" name="Budget" value="<?php echo $row['Budget']?>"></label>
</p>
<p>
<label>Used:
<input type="text" name="Used" value="<?php echo $row['Used']?>"></label>
</p>
<p>
<input type="submit" name="submit" value="Submit">
</p>
</form>
This example doesn't include any error checking whatsoever.
Ajax is a good solution for your problem, because you won't need to jump to a secondary page, not even refresh the page! Next code is an example and it works like this:
Every row in the HTML table has one button to save changes.
The click event of every button calls the ajax function with the data values.
The ajax function calls "update.php" with the data values as POST parameters.
"update.php" gets the data as $_POST values and updates the database record.
"update.php" sends a success message back to the ajax function to display it.
In order to test it, create two files with the given names, copy-paste next codes and run! (You don't need anything else but those codes).
main.php
<html>
<head>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
//--------------------------------------------------
function myAjax ( id )
{ if ( ! confirm( "Save data for id=" + id + " ?" ) )
return;
$.ajax( { type : 'POST',
url : 'update.php',
data : { 'id' : id,
'name' : $("#name"+id).val(), // VALUE FROM EDIT FIELD.
'phone' : $("#phone"+id).val(), // VALUE FROM EDIT FIELD.
},
success : function ( result )
{ alert( result ); },
error : function ( xhr )
{ alert( "error" ); }
}
);
}
//--------------------------------------------------
</script>
</head>
<body>
<table>
<tr><td>NAME</td>
<td>PHONE</td>
<td></td>
</tr>
<?php
//--------------------------------------------------
// SAMPLE DATA.
$database = Array( Array( "id" => "1",
"name" => "Mike",
"phone" => "123" ),
Array( "id" => "2",
"name" => "Midas",
"phone" => "456" ),
Array( "id" => "3",
"name" => "Jay",
"phone" => "789" )
);
$i = 1;
foreach ( $database as $row ) // DISPLAY "DATABASE" ROWS.
{ echo "<tr><td><input type='text' id='name" . $row["id"] .
"' value='" . $row["name"] . "'/></td>\n" .
" <td><input type='text' id='phone" . $row["id"] .
"' value='" . $row["phone"] . "'/></td>\n" .
" <td><button onclick='myAjax(\"" . $row["id"] .
"\")'>Save changes</button></td>\n" .
"</tr>";
$i++;
}
//--------------------------------------------------
?>
</table>
</body>
</html>
update.php
<?php
// CHECK IF VALUES ARE COMING FROM AJAX.
if ( isset( $_POST[ "id" ] ) &&
isset( $_POST[ "name" ] ) &&
isset( $_POST[ "phone" ] ) )
{ // "update my_table set name=$_POST[ "name" ],
// phone=$_POST[ "phone" ]
// where id=$_POST[ "id" ]
echo "Record " . $_POST[ "id" ] . " updated with " .
$_POST[ "name" ] . " and " . $_POST[ "phone" ];
}
?>
Oops! Just fixed one little problem, ready to run!
If you right-click the webpage to see the code, you will notice the input fields have the ids "name1", "name2", ..., and "phone1", "phone2", .... This method gives every textbox a unique id (necessary for ajax function to get the value entered by user and send it to PHP). The code in charge of this is :
id='name" . $row["id"] .
"' value=

Can you update in a div tag

I have a little question about something. I have some forms, where I send the input to a MySQL database. I get the return from the database, out in some div tags. Here I have 2 buttons. Button number 1 can delete the row, and button number 2 should have a function, where I can update a specific row, if I want to change the content of the row. But can I update a div tag? I can see on the net, that a lot of people use tables to do that.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/arrangeTables.css">
</head>
<body>
<?php
include 'connection.php';
if(isset($_POST['addto'])){
// Insert to database
$date = $_POST['date'];
$day = $_POST['day'];
$fromtime = $_POST['fromtime'];
$totime = $_POST['totime'];
$sql = "INSERT INTO addWorkTime(date, day, fromtime, totime) VALUES('$date', '$day', '$fromtime', '$totime')";
$result = mysql_query($sql, $dbhandle) or die(mysql_error($dbhandle));
// Update of the row
if(isset($_POST['update'])){
$hidden = mysql_real_escape_string($_POST['hidden']);
$UpdateQuery = "UPDATE addWorkTime
SET date='$_POST[date]',
day='$_POST[day]',
fromtime='$_POST[fromtime]',
totime='$_POST[totime]'
WHERE p_id='$_POST[hidden]'";
$update = mysql_query($UpdateQuery, $dbhandle) or die(mysql_error($dbhandle));
if($update) {
echo "Succes";
} else {
echo "Der er en fejl";
}
}; // brace for if(isset($_POST['update']))
if($result){
echo "Insert successful.";
}
}; // brace for if(isset($_POST['addto']))
if(isset($_POST['delete'])){
$hidden = mysql_real_escape_string($_POST['hidden']);
$DeleteQuery = "DELETE FROM addWorkTime WHERE p_id=$hidden";
$delete = mysql_query($DeleteQuery, $dbhandle) or die(mysql_error($dbhandle));
if($delete){
echo "Delete successful";
}
}
//Return records from database
$result = mysql_query("SELECT p_id, date, day, fromtime, totime FROM addWorkTime");
?>
<form method="post">
<h3>Add your worktime to database</h3><br>
Date:
<input type="date" name="date"><br><br>
Day
<select name="day">
<option value="Mandag">Mandag</option>
<option value="Tirsdag">Tirsdag</option>
<option value="Onsdag">Onsdag</option>
<option value="Torsdag">Torsdag</option>
<option value="Fredag">Fredag</option>
<option value="Lørdag">Lørdag</option>
<option value="Søndag">Søndag</option>
</select>
From time:
<input type="time" name="fromtime">
To time:
<input type="time" name="totime">
<input type="submit" name="addto" value="submit"><br><br>
<!-- Return from the database -->
<h3>Return from database:</h3><br>
<!-- headers -->
<table>
<tr>
<th class="column0">Primary Key</th>
<th class="column1">Date</th>
<th class="column2">Day</th>
<th class="column3">From</th>
<th class="column4">To</th>
</tr>
</table>
</form>
<!--loop through through the database -->
<?php while($row = mysql_fetch_array($result)): ?>
<form method="post">
<table>
<tr>
<td class="resultcolumn0"><?php echo $row{'p_id'};?></td>
<td class="resultcolumn1"><?php echo $row{'date'};?><br></td>
<td class="resultcolumn2"><?php echo $row{'day'};?></td>
<td class="resultcolumn3"><?php echo $row{'fromtime'};?></td>
<td class="resultcolumn4"><?php echo $row{'totime'};?></td>
<td><input type="hidden" name="hidden" value="<?php echo $row{'p_id'}?>"><?php echo $row{'p_id'}?></td>
<td><input type="submit" name="update" value="Update"></td>
<td><input type="submit" name="delete" value="Delete"></td>
</tr>
</table>
</form>
<?php endwhile; ?>
</body>
</html>
If you want to update your cell table like your recording, you can do a tricky way like this code snippet:
function change1() {
var inp1 = document.getElementById('myTable').rows[1].cells[0];
inp1.innerHTML = "<input type='text' name='inp1'>";
var inp2 = document.getElementById('myTable').rows[1].cells[1];
inp2.innerHTML = "<input type='text' name='inp2'>";
}
function change2() {
var inp1 = document.getElementById('myTable').rows[2].cells[0];
inp1.innerHTML = "<input type='text' name='inp1'>";
var inp2 = document.getElementById('myTable').rows[2].cells[1];
inp2.innerHTML = "<input type='text' name='inp2'>";
}
table, td {
border: 1px solid black;
}
<table id="myTable">
<tr>
<td>column 1</td>
<td>column 2</td>
<td>action</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
<td>
<button onclick="change1()">Update</button>
</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
<td>
<button onclick="change2()">Update</button>
</td>
</tr>
</table>
<button onclick="alert('whatever function to save the edit')">Save</button>
you can improve that to give <form> tag to your <table> tag and save that using another Save button. Or you can use if conditional to your update button for change to textfield and post it to your database.
<form method="post" action='function_to_update_or_delete.php'>
<table>
<tr>
<td class="resultcolumn0"><?php echo $row{'p_id'};?></td>
<td class="resultcolumn1"><?php echo $row{'date'};?><br></td>
<td class="resultcolumn2"><?php echo $row{'day'};?></td>
<td class="resultcolumn3"><?php echo $row{'fromtime'};?></td>
<td class="resultcolumn4"><?php echo $row{'totime'};?></td>
<td><input type="hidden" name="hidden" value="<?php echo $row{'p_id'}?>"><?php echo $row{'p_id'}?></td>
<td><button onclick="<?php echo change($some_information_to_your_cell)?>">Update</button></td>
<td><input type="submit" name="delete" value="Delete"></td>
</tr>
</table>
</form>
And, please try to make a function dynamically each row, don't hardcode it like function change1(), function change2(), function change3(), etc
Hope this will help you out. :)

How to auto-sum column and save to MySQL database?

How can I auto-sum the "Total Hours" data in the tfoot and save to MySQL database and re-display in same area? I've got two examples working, I would like to add the auto-sum functionality to the VizaHours web-app.
Working examples are here:
http://onetimemobile.com/vizahours/index.php
http://onetimemobile.com/autosummer
EDITED 4-2-14 ADDED ALL CODE index.php below:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th> DAY </th>
<th> DAY INFO </th>
<th> HOURS </th>
</tr>
<tfoot>
<tr id="summation">
<td class="total-hours" colspan="2">TOTAL HRS >>>>></td>
<td><span>0</span></td>
</tr>
<tr>
<th colspan="3">BUD HOURS - START WEEK 3-24-14<br />unpaid</th>
</tr>
</tfoot>
</thead>
<tbody>
<?php
include('connect.php');
$result = $db->prepare("SELECT * FROM budsvizahours ORDER BY id DESC");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr class="record">
<td><?php echo $row['fname']; ?><br /><br /><a href="editform.php?id=<?php echo
$row['id']; ?>"> Edit </a></td>
<td><?php echo $row['lname']; ?></td>
<td><?php echo $row['age']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
EDITED 4-2-14 ADDED ALL CODE edit.php below:
<?php
// configuration
include('connect.php');
// new data
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$age = $_POST['age'];
$id = $_POST['memids'];
// query
$sql = "UPDATE budsvizahours
SET fname=?, lname=?, age=?
WHERE id=?";
$q = $db->prepare($sql);
$q->execute(array($fname,$lname,$age,$id));
header("location: index.php");
?>
EDITED 4-2-14 ADDED ALL CODE editform.php below:
<?php
include('connect.php');
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM budsvizahours WHERE id= :userid");
$result->bindParam(':userid', $id);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<form action="edit.php" method="POST">
<input type="hidden" name="memids" value="<?php echo $id; ?>" />
<br>
<input type="hidden" name="fname" value="<?php echo $row['fname']; ?>" /><br>
Update Day Info<br>
<input type="text" name="lname" value="<?php echo $row['lname']; ?>" /><br>
Hours This Day<br>
<input class="record" type="tel" name="age" value="<?php echo $row['age']; ?>" />
<br><br>
<button class="edit-info-button" type="submit" value="Save">Save</button>
</form>
<?php
}
?>
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value); }
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
</body>
</html>
//it work for your code...
//sum query is good but i case you don't want to do it by that way
<script type="text/javascript">
$(document).ready(function() {
var sum = cls_nm_tr = 0;//create variable to null or zero
//making loop for your tr its depends on no of tr you have
$('.record').each(function(i,e){
var cls_nm_tr = $('td:eq(2)', this).html();//getting value from td
sum = parseInt(sum) + parseInt(cls_nm_tr);//adding them in sum varible
});//loops ends here
console.log(sum);//here you got sum of HOURS.//"sum" variable have sum or hours
//$(".yoru_footer_id").html(sum);//here you can put data in tfooter
});
</script>

Categories