Sum time from datetime - php

I have an table in sql the type is datetime y m d h i s
and im using mid in php to get the time alone and the date alone like this
mid(tablename,1,10) to get the date only like this 'y m d'
and useing
mid(tablename,12,8) to get the time only like this 'H:i:s'
and this is code explane what i did
<html>
<head>
<title>ss</title>
</head>
<body>
<form method='post' action='<?php $_SERVER['SELF'];?>'>
<input type='submit' name='submit' />
</form>
<?
include("config");
$submit = $_POST['submit'];
$getdata1= mysql_query("select checktime from calls");
if(isset($submit))
{
while($getdata= mysql_fetch_array($getdata1))
{
echo "<input type='text' name='text' value='mid($getdata[1],12,8)'";
}
}
?>
</body>
</html>
now I get the result like this
08:00:00
08:10:00
07:00:51
and so on
What I need to sum the result as
date("d H:i:s",strtotime(all result from fetch array))
so I tried this
<html>
<head>
<title>ss</title>
</head>
<body>
<form method='post' action='<?php $_SERVER['SELF'];?>'>
<input type='submit' name='submit' />
</form>
<?
include("config");
$submit = $_POST['submit'];
$getdata1= mysql_query("select checktime from calls");
if(isset($submit))
{
while($getdata= mysql_fetch_array($getdata1))
{
echo "<input type='text' name='text' value='mid($getdata[1],12,8)'";
for($i=0;$i<5;$i++)
{
$i+= strtotime($getdata[0]);
}
}
echo $i;
}
?>
</body>
</html>
but I have only the last result
so I tried to do it in sql query like this
<html>
<head>
<title>ss</title>
</head>
<body>
<form method='post' action='<?php $_SERVER['SELF'];?>'>
<input type='submit' name='submit' />
</form>
<?
include("config");
$submit = $_POST['submit'];
$getdata1= mysql_query("select unix_timestamp(mid(checktime,12,8)) from calls");
if(isset($submit))
{
while($getdata= mysql_fetch_array($getdata1))
{
echo "<input type='text' name='text' value='mid($getdata[1],12,8)'";
for($i=0;$i<5;$i++)
{
$i+= $getdata[0];
}
}
echo $i;
}
?>
</body>
</html>
and the result I get at not from 1970-1-1, but I get at from mid(checktime,1,10), so what I want is to sum the result thats comes out like this:
H:i:s
from the whole fetch.
I mean, how can I sum the result to come out like this:
08:00:00
08:10:00
07:00:51
in one variable?

If I understand well to you question, here is small example how you can sum up and format time as you required.
$times = ['15:00:00', '08:10:00', '07:00:51'];
$date = new \DateTime;
$alteredDate = new \DateTime;
foreach ($times as $time) {
$parts = explode(':', $time);
$alteredDate->add(new \DateInterval(sprintf('PT%dH%dM%dS', $parts[0], $parts[1], $parts[2])));
}
echo $alteredDate->diff($date)->format('%a %h:%i:%s');

Related

Post data in database without refreshing PHP Page

I am working with two php file. The first file contains a search engine that outputs the results in the second php file. This second php file is displayed in an iframe just underneath the search engine of the first php file. this file also contains data that needs to be submitted using post. I can submit the form and redirect it to a 3rd php file. But I dont want to go away from the current page. So far what I can do is to call an isset function on the same page and fire the insert command to my table. But it refreshes the 2nd php file. Refreshing will reset the search values passed from the 1st php file which is not good. Please help
This is my 2nd php file:
<!DOCTYPE html>
<html>
<head>
<title>RFC System</title>
<script src="jquery-1.12.4.js"></script>
<link rel="stylesheet" type="text/css" href="style2.css">
<link rel="stylesheet" type="text/css" href="modal.css">
</head>
<body>
<?php
require ("../funcs.php"); site_security();
set_error_handler ("my_error_handler");
set_time_limit(0);
date_default_timezone_set ("Asia/Manila");
require("../connmysql.php");
$session_user_id = $_SESSION["USERCID"];
$session_branch = $_SESSION["BRANCHCODE"];
$branchname=$_POST['branchname'];
$empbio=$_POST['empbio'];
$dtrdate_from=$_POST['dtrdate_from'];
$dtrdate_to=$_POST['dtrdate_to'];
##########HELP HERE!
if(isset($_POST['reason'])){
#save to database without refreshing the page
}
#####################
if((empty($branchname)) || (empty($empbio)) || (empty($dtrdate_from)) || (empty($dtrdate_to))){
echo "<font color='#FF0000'><b>Please fill-in all fields to start search</b></font>";
}else{
$startDate = DateTime::createFromFormat("Y/m/d","$dtrdate_from",new DateTimeZone("Asia/Manila"));
$endDate = DateTime::createFromFormat("Y/m/d","$dtrdate_to",new DateTimeZone("Asia/Manila"));
$periodInterval = new DateInterval( "P1D" ); // 1-day, though can be more sophisticated rule
$period = new DatePeriod( $startDate, $periodInterval, $endDate );
$queryname=mysqli_query($conn,"select a.nsemp_fname,a.nsemp_mname,a.nsemp_lname,a.nsemp_sufixname,a.nsemp_empid,a.nsemp_bionum,a.nsemp_brcode from rfc_prf_nsemp a where a.nsemp_bionum=12476")or die();
while($row=mysqli_fetch_array($queryname)){
$fname=$row[0];
$mname=$row[1];
$lname=$row[2];
$suffix=$row[3];
$empid=$row[4];
$bionum=$row[5];
$brcode=$row[6];
}
echo"<hr/>
<h3><b>Name:</b>$fname $mname[0] $lname $suffix<br/>
<b>Employee No:</b> $empid<br/>
<b>Branch:</b> $brcode<br/></h3>
<table class='x'><tr>";
foreach($period as $date){
$x = $date->format("Y-m-d");
$day = date('l', strtotime($x));
if($day=="Sunday"){$background="#00e673";}else if($day=="Saturday"){$background="#ffff99";}else{$background="#ffffff";}
echo"<td height='150px' style='border-style: solid; background:$background'>
<form method='post' action='#'>
<b><font color='#1a1aff'>$x<br/>$day</font></b><br/><br/>";
$query=mysqli_query($conn,"select dtr_time,(CASE in_or_out WHEN 0 THEN 'IN' WHEN 1 THEN 'OUT' END) AS status,datacid from rfc_bio_dtr where dtr_date='$x' and empbio='12476';")or die(mysqli_error());
$check="";
while($row=mysqli_fetch_array($query)){
echo "$row[0] $row[1] <br/>";
$check .=$row[1];
}
if(preg_match('(IN)', $check) && preg_match('(OUT)', $check)) { echo" ";}else{
$queryReason=mysqli_query($conn,"select tk_reason_id,tk_reason_desc from rfc_timekeeping_param;")or die();
echo "<br/><br/>Remarks:<select name='' id=''>";
while($row=mysqli_fetch_array($queryReason)){
echo "<option value='$row[0]'>$row[1]</option>";
}
echo"</select><br/>Notes:<br/><textarea></textarea><input type='submit' value='save' name='reason' id='reason' class='totobutton'>";
}
echo"</form></td>";
}
}
?>
</body>
Here is an updated code using jquery/ajax. There's a problem with the next table data, they dont get submitted. only the first table data gets submitted:
<!DOCTYPE html>
<html>
<head>
<title>RFC System</title>
<script src="jquery-1.12.4.js"></script>
<link rel="stylesheet" type="text/css" href="style2.css">
<link rel="stylesheet" type="text/css" href="modal.css">
<script>
$(function () {
$('#myform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'savetodb.php',
data: $('#myform').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<?php
require ("../funcs.php"); site_security();
set_error_handler ("my_error_handler");
set_time_limit(0);
date_default_timezone_set ("Asia/Manila");
require("../connmysql.php");
$session_user_id = $_SESSION["USERCID"];
$session_branch = $_SESSION["BRANCHCODE"];
$branchname=$_POST['branchname'];
$empbio=$_POST['empbio'];
$dtrdate_from=$_POST['dtrdate_from'];
$dtrdate_to=$_POST['dtrdate_to'];
if((empty($branchname)) || (empty($empbio)) || (empty($dtrdate_from)) || (empty($dtrdate_to))){
echo "<font color='#FF0000'><b>Please fill-in all fields to start search</b></font>";
}else{
$startDate = DateTime::createFromFormat("Y/m/d","$dtrdate_from",new DateTimeZone("Asia/Manila"));
$endDate = DateTime::createFromFormat("Y/m/d","$dtrdate_to",new DateTimeZone("Asia/Manila"));
$periodInterval = new DateInterval( "P1D" ); // 1-day, though can be more sophisticated rule
$period = new DatePeriod( $startDate, $periodInterval, $endDate );
$queryname=mysqli_query($conn,"select a.nsemp_fname,a.nsemp_mname,a.nsemp_lname,a.nsemp_sufixname,a.nsemp_empid,a.nsemp_bionum,a.nsemp_brcode from rfc_prf_nsemp a where a.nsemp_bionum=12476")or die();
while($row=mysqli_fetch_array($queryname)){
$fname=$row[0];
$mname=$row[1];
$lname=$row[2];
$suffix=$row[3];
$empid=$row[4];
$bionum=$row[5];
$brcode=$row[6];
}
echo"<hr/>
<h3><b>Name:</b>$fname $mname[0] $lname $suffix<br/>
<b>Employee No:</b> $empid<br/>
<b>Branch:</b> $brcode<br/></h3>
<table class='x'><tr>";
foreach($period as $date){
$x = $date->format("Y-m-d");
$day = date('l', strtotime($x));
if($day=="Sunday"){$background="#00e673";}else if($day=="Saturday"){$background="#ffff99";}else{$background="#ffffff";}
echo"<td height='150px' style='border-style: solid; background:$background'>
<b><font color='#1a1aff'>$x<br/>$day</font></b><br/><br/>";
$query=mysqli_query($conn,"select dtr_time,(CASE in_or_out WHEN 0 THEN 'IN' WHEN 1 THEN 'OUT' END) AS status,datacid from rfc_bio_dtr where dtr_date='$x' and empbio='12476';")or die(mysqli_error());
$check="";
while($row=mysqli_fetch_array($query)){
echo "$row[0] $row[1] <br/>";
$check .=$row[1];
}
if(preg_match('(IN)', $check) && preg_match('(OUT)', $check)) { echo" ";}else{
$queryReason=mysqli_query($conn,"select tk_reason_id,tk_reason_desc from rfc_timekeeping_param;")or die();
?>
<form id="myform">
<select name="reason" value="reason">
<?php
while($row=mysqli_fetch_array($queryReason)){
echo "<option value='$row[0]'>$row[1]</option>";
}
?></select>
<textarea name="notes" value="notes"></textarea><br>
<input name="submit" type="submit" value="Submit">
</form><?php
}
echo"</td>";
}
}
?>
</body>
Here's savetodb.php
<?php
require("../connmysql.php");
$fname=$_POST['reason'];
$lname=$_POST['notes'];
$queryx=mysqli_query($conn,"insert into test (fname,lname) values ('$fname','$lname');")or die(mysqli_error());
?>
You already have jQuery loaded, so start AJAX from an onclick handler and put the save in a totally different PHP file (one that only outputs "OK" or "ERROR: something." See http://pqxb.qr.ai for a relevant tutorial.

Use a single textbox to keep adding values to array after post

So I'm currently working on a little project that allows a user to input a number into a textbox, after clicking a button that says "add" it should store that value into an array and then allow the user to input another value into that array. There is also a button on the page when the user is finished and wants to sum the values called "Submit". The problem I'm running into is everytime the form posts back, it recreates a new blank array. Any tips?
See the code below:
<html>
<head>
</head>
<body>
<h2>Please Select your title and name:</h2>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method='post'>
<p>
<label for="strFirstname">Type number to add: </label>
<input type='text' name='strNumber' id='strNumber'/>
</p>
<p>
<input type='submit' name='submit' value='Add' />
</p>
<p>
<input type='submit' name='calculate' value='Compute' />
</p>
<?php
$array = array();
if (isset($_POST['submit']))
$num = $_POST['strNumber'];
$array[] = $num;
foreach($array as $num)
echo $num . ' + ';
if(isset($_POST['calculate']))
foreach($array as $num)
echo $num . ' + ';
?>
</form>
</body>
</html>
<?php
session_start();
?>
<html>
<head>
</head>
<body>
<h2>Please Select your title and name:</h2>
<form action='' method='post'>
<p>
<label for="strFirstname">Type number to add: </label>
<input type='text' name='strNumber' id='strNumber'/>
</p>
<p>
<input type='submit' name='submit' value='Add' />
</p>
<p>
<input type='submit' name='calculate' value='Compute' />
<input type='submit' name='clear' value='clear' />
</p>
<?php
if (isset($_POST['submit'])) {
if(!array_key_exists("numbers", $_SESSION)) {
$_SESSION["numbers"] = array();
}
array_push($_SESSION["numbers"], $_POST["strNumber"]);
}
if(isset($_POST['clear'])) {
$_SESSION["numbers"] = array();
}
if(array_key_exists("numbers", $_SESSION)) {
echo implode("+", $_SESSION["numbers"]);
}
if(isset($_POST['calculate'])) {
if(array_key_exists("numbers", $_SESSION)) {
$expression = implode("+", $_SESSION["numbers"]);
eval( '$result = (' . $expression . ');' );
echo "=" . $result;
}
}
?>
</form>
</body>
</html>
Start a session
When the action is "submit"
Check if the session which will store the numbers is initialized
If it's not initialize it as an array
Finally push the number into the array
Check if there is a session initialized if there is print all the numbers ( you can use implode to do that)
if the action is calculate .. just make the calculation ( check eval function )

Date error displaying

Im doing a bit of php. First thing to clarify is that the * is the hidden text I didnt want to show. I was wandering why every time I try and type in a date e.g. 29/11/2013 it would come up on the php page as 0000-00-00. Could someone explain to me where I went wrong and give me a proper explanation on why and how it works, thanks very much.
<html>
<head>
<title>XYZ</title>
</head>
<body>
<h1>Insert into Database <i>XYZ</i> table <i>addressbook</i></h1>
<form method="get" action="********************************************* ">
<b>ID:</b> <input type="text" name="ID"><br>
<b>CARNAME:</b> <input type="text" name="CARNAME"><br>
<b>FUELTYPE:</b> <input type="text" name="FUELTYPE"><br>
<b>TRANSMISSION:</b> <input type="text" name="TRANSMISSION"><br>
<b>ENGINESIZE:</b> <input type="text" name="ENGINESIZE"><br>
<b>DOORS:</b> <input type="text" name="DOORS"><br>
<b>TOTAL:</b> <input type="text" name="TOTAL"><br>
<b>AVAILABLE:</b> <input type="text" name="AVAILABLE"><br>
<b>DATEADDED:</b> <input type="text" name="DATEADDED"><br>
<input type="submit">
</form>
</body>
</html>
<html>
<head>
<title>XYZ</title>
</head>
<body>
<h1>Insert into Database <i>XYZ</i> table <i></i></h1>
<?php
$link = mysql_connect ("**********", "*********", "*********");
mysql_select_db ("***********");
$ID = $_GET["ID"];
$CARNAME = $_GET["CARNAME"];
$FUELTYPE = $_GET["FUELTYPE"];
$TRANSMISSION = $_GET["TRANSMISSION"];
$ENGINESIZE = $_GET["ENGINESIZE"];
$DOORS = $_GET["DOORS"];
$TOTAL = $_GET["TOTAL"];
$AVAILABLE = $_GET["AVAILABLE"];
$DATEADDED = $_GET["DATEADDED"];
$query = "INSERT into CAR values ('$ID', '$CARNAME', '$FUELTYPE', '$TRANSMISSION', '$ENGINESIZE', '$DOORS', '$TOTAL', '$AVAILABLE', '$DATEADDED')";
$result = mysql_query ($query);
$query = "SELECT * from CAR";
$result = mysql_query ($query);
print "<table>";
print "<tr>";
print "<th>ID</th><th>CARNAME</th><th>FUELTYPE</th><th>TRANSMISSION</th><th>ENGINESIZE</th><th>DOORS</th><th>TOTAL</th><th>AVAILABLE</th><th>DATEADDED</th>";
print "</tr>";
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
print "<tr>";
print "<td>$row->ID</td>";
print "<td>$row->CARNAME</td>";
print "<td>$row->FUELTYPE</td>";
print "<td>$row->TRANSMISSION</td>";
print "<td>$row->ENGINESIZE</td>";
print "<td>$row->DOORS</td>";
print "<td>$row->TOTAL</td>";
print "<td>$row->AVAILABLE</td>";
print "<td>$row->DATEADDED</td>";
print "</tr>";
}
print "</table>";
mysql_close ($link);
?>
</body>
</html>
In MySql your data should of format yyyyMMdd so you should first convert it before inserting it
$DATEADDED = $_GET["DATEADDED"];
becomes something like
$DATEADDED = date("Y-m-d", strtotime($_GET["DATEADDED"]));
Check your date format in your database Y/m/d or if it set to date... Else change it to varchar (255) to be able to include any format.

Using Session Tracking for Multipage Form in PHP

I'm trying to display a multiple page form that preserves submitted data from one page to the next using session tracking. $_POST['stage'] determines which form should be displayed. Each form has a hidden input type with a value set to increment the $stage variable by 1 but when I submit the data from the first form, the value of $stage seems to remain the same as I don't see the next form. Sessions is enabled in php.ini.
Here's my example:
<?php
session_start();
//Determine which integer to assign to the stage
if (($_SERVER['REQUEST_METHOD'] == 'GET') || (!isset($_POST['stage']))) {
$stage = 1;
} else {
$stage = (int) $_POST['stage'];
}
//Save any submitted data
if ($stage > 1) {
foreach ($_POST as $key => $value) {
$_SESSION[$key] = $value;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Form Example</title>
</head>
<body>
<?php if ($stage == 1) { ?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
<label for='firstField'>First field:</label>
<input type='text' name='first_field /><br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='submit' value='Next' />
</form>
<?php } else if ($stage == 2) { ?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
<label for='secondField'>Second field:</label>
<input type='text' name='second_field /<br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='hidden' value='Done' />
</form>
<?php } ?>
</body>
</html>
Try adding session_start() at the top of your page. That's the first thing I've noticed.
I discovered a typo on my working script. Hindsight, I should have copied and pasted my entire script. Sorry. This script works fine (with session_start() at the beginning which still doesn't appear after I post the question).
Since you didn't mention what a problem is, which made me to sift and find exactly, I will put more precise answer. The problem is no ending single quote in the lines
<input type='text' name='first_field /><br />
and
<input type='text' name='second_field /<br />
and so my final working script is
<?php
session_start();
$stage = 0;
//Determine which integer to assign to the stage
if (!isset($_POST['stage'])) {
$stage = 1;
} else {
$stage = (int) $_POST['stage'];
}
//Save any submitted data
if ($stage > 1) {
foreach ($_POST as $key => $value) {
$_SESSION[$key] = $value;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Form Example</title>
</head>
<body>
<?php if ($stage == 1) { ?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
<label for='firstField'>First field:</label>
<input type='text' name='first_field' /><br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='submit' value='Next' />
</form>
<?php } else if ($stage == 2) { ?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
<label for='secondField'>Second field:</label>
<input type='text' name='second_field' /<br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='hidden' value='Done' />
</form>
<?php } ?>
</body>
</html>

Form not recognizing post variables

I have a simple html form and some php that input the POST variables into a mysql database. However, I noticed that the form would not input the data when
if (isset($_POST['submit'])){
insert stuff in here
}
was included. I then removed the if statement above and ran the code. All of the variables were imputed except the ones from the form using POST (ex $_POST['var1']). It seems like the POST variables are not being recognized and I dont know what's wrong.
ALL CODE:
<?php session_start(); ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src='http://twitter.github.com/bootstrap/1.4.0/bootstrap-modal.js'></script>
<link rel="stylesheet" href="../css/bootstrap.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/basic.css" type="text/css" media="screen" />
</head>
<body>
<?php include '../css/bar.php'; ?>
<div id='content'>
<?php include '../nav.php';
?>
<?php
if (isset($_POST['submit'])){
include '../connect.php';
$question=mysql_real_escape_string($_POST['question']);
$detail=mysql_real_escape_string($_POST['detail']);
$date=date("d M Y");
$time=time();
$user=$_SESSION['id'];
$put=mysql_query("INSERT INTO questions VALUES ('','$question','$detail','$date','$time','$user','subject','0')");
$result=mysql_query("SELECT * FROM questions WHERE user='$user' AND time='$time'");
while ($row = mysql_fetch_assoc($result)){
$q=$row['id'];
}
}
?>
<form method='POST' action='question.php?q=<?php echo $q ?>'>
<p>Question:</p>
<p><input type='text' name='question' id='question' maxlength='200'></p>
<p>Add some detail (optional):</p>
<p><textarea id='detail' name='detail' ></textarea></p>
<p>Tags:</p>
<p><input type='submit' value='submit' name='submit'></p>
</form>
</div>
<?php include '../footer.php'; ?>
</body>
</html>
TESTPAGE:
<?php
include 'connect.php';
if (isset($_POST['submit'])){
$hhh=mysql_real_escape_string($_POST['hhh']);
$put=mysql_query("INSERT INTO questions VALUES ('','$hhh','','','','','','')");
}
?>
<form action='test.php' method='post'>
<input type='text' name='hhh'>
<input type='submit' name='submit' value='submit'>
</form>
You have two PHP pages - ask.php and question.php. I (guess)think the ask.php is used to store questions and other details and you want to open a question.php with question id.
ask.php
<?php session_start(); ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src='http://twitter.github.com/bootstrap/1.4.0/bootstrap-modal.js'></script>
<link rel="stylesheet" href="../css/bootstrap.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/basic.css" type="text/css" media="screen" />
</head>
<body>
<?php include '../css/bar.php'; ?>
<div id='content'>
<?php
include '../nav.php';
/*--- If submit button is pressed ---- */
if (isset($_POST['submit']))
{
include '../connect.php';
$question=mysql_real_escape_string($_POST['question']);
$detail=mysql_real_escape_string($_POST['detail']);
$date=date("d M Y");
$time=time();
$user=$_SESSION['id'];
/* SELECT column names you want to use with INSERT statement */
$put=mysql_query("INSERT INTO questions
(`question`,`detail`,`date`,`time`,`user`,`subject`,`name_of_last_col` )
VALUES
('$question','$detail','$date','$time','$user','subject','0')");
//for debug purpose
if($put)
{
echo "Record added";
}
else
{
echo "Can't add record " . mysql_error();
}
}
/*----- End submit block -----------*/
/*----List the questions and select it----------*/
$time=time();
$user=$_SESSION['id'];
//I think this wont work. Try to remove time comparison from the SELECT statement.
$result=mysql_query("SELECT * FROM questions WHERE `user`='$user' AND `time`='$time'");
//$result=mysql_query("SELECT * FROM questions WHERE `user`='$user'");
if($result)
{
echo "<table>";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>$row[question]</td>";
echo "<td><a href='question.php?qid=$row[id]'>Show a question</a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No questions!!!";
}
?>
<form method='POST' action="ask.php">
<p>Question:</p>
<p><input type='text' name='question' id='question' maxlength='200'></p>
<p>Add some detail (optional):</p>
<p><textarea id='detail' name='detail' ></textarea></p>
<p>Tags:</p>
<p><input type='submit' value='submit' name='submit'></p>
</form>
question.php should be:
<?php
$qid=$_GET["qid"];
echo "$qid is selected...";
?>
You may split code into two PHP pages - one for save records and another to list and select rows.
addquestion.php
<?php
session_start();
if(isset($_POST['submit']))
{
mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("your_db_name") or die(mysql_error());
$question=mysql_real_escape_string($_POST['question']);
$detail=mysql_real_escape_string($_POST['detail']);
$date=date("d M Y");
$time=time();
$user=$_SESSION['id'];
$put=mysql_query("INSERT INTO questions
(`question`,`detail`,`date`,`time`,`user`,`subject`,`name_of_last_col` )
VALUES
('$question','$detail','$date','$time','$user','subject','0')");
//for debug purpose
if($put)
{
echo "Record added";
}
else
{
echo "Can't add record " . mysql_error();
}
}
?>
<form method='post' action="addquestion.php">
<p>Question:</p>
<p><input type='text' name='question' id='question' maxlength='200'></p>
<p>Add some detail (optional):</p>
<p><textarea id='detail' name='detail' ></textarea></p>
<p>Tags:</p>
<p><input type='submit' value='submit' name='submit'></p>
</form>
questionlist.php
<?php
session_start();
$user=$_SESSION['id'];
mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("your_db_name") or die(mysql_error());
$result=mysql_query("SELECT * FROM questions WHERE `user`='$user'");
if($result)
{
echo "<table>";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>$row[question]</td>";
echo "<td><a href='question.php?qid=$row[id]'>Show a question</a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No questions!!!";
}
?>

Categories