I have troubles making a forum using php and mysql - php

The code below is the program that i have written.
The problem is, even if i press submit, reply or delete, none of the button works.
Can you help me what is wrong with the code that i have written below.
Thank you so much.
<?php
/*共通処理*/
//データベースへの接続
try{
$GLOBALS['db'] = new PDO("mysql:host=localhost; dbname=bbs", "root", "test");
} catch (PDOException $e) {
echo 'connection failed: '.$e->getMessage();
}
//action取得
$action = (isset($_GET['action']) ? $_GET['action'] : $_POST['action']);
//action振り分け
switch($action)
{
//書き込み処理
case "regist":
proc_regist();
break;
//削除処理
case "delete":
proc_delete();
break;
//返信処理
case "res":
proc_res();
break;
//表示処理
default:
proc_default();
break;
}
// 終了処理
/* ここで処理は終了 あとは個別の関数へ */
// 基本の掲示板表示処理
function proc_default()
{
$db = $GLOBALS['db'];
$page_max = 15;
$offset = ( isset($_GET['offset']) ? $_GET['offset'] : 0 );
$limit = $page_max +1;
$stmd = $db->query("select * from message order by no desc limit $limit offset $offset");
$rows = $stmd->fetchAll();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang = "ja">
<head>
<meta http-equiv = "Content-Type" content="text/html; charset = UTF-8">
<title>
</title>
</head>
<body>
<form method = "POST" action = "bbs_new.php">
<input type = "hidden" name = "action" value= "regist">
お名前:<input type="text" name="name"><br>
メール:<input type="text" name="mail"><br>
題 名:<input type="text" name="title"><br>
削除キー:<input type="password" name="delkey" value="<?php print $delkey ?>"><br>
<textarea name="contents" cols="60" rows="5"></textarea><br>
<?php
print "<input type='submit' name='write' value='送信'>\n";
print "<hr>\n";
print "記事番号:<input type='text' name='delno'>\n";
print "削除キー: <input type='password' name='delkey'>\n";
print "<input type='submit' name='delete' value='記事削除'>\n";
print "<input type = 'hidden' name = 'action' value = 'delete'>\n";
?>
</form>
<?php
//ここからデータ表示処理
$sql = 'select * from message order by no desc';
foreach ($db->query($sql) as $row) {
if ($_GET['resno']) {
if ($row['resno'] != $_GET['resno']) continue;
}
if ($_POST['resno']) $resno = $_POST['resno'];
else $resno = $no;
if ($row['no'] != $row['resno']) $res = true; else $res = false;
if ($res) print "<blockquote>";
else print "<hr>";
print "<p>No.".$row['no']." ";
print "<b>{$row['title']}</b> 投稿者:";
if ($row['mail']) print "<a href='mailto:{$row['mail']}'>";
print $row['name'];
if ($row['mail']) print "</a>";
$row['time'] = date("Y/m/d H:i:s");
print " 投稿時間:{$row['time']}";
if (!$res && !$_GET['resno']) {
print " <a href='bbs_new.php?resno={$row['no']}'>返信</a>";
}
print "<br><br>{$row['contents']}</p>";
if ($res) print "</blockquote>";
print "\n";
}
//改ページ
if(count($rows)>$page_max){
$next = $offset+$page_max;
print "[<a href='bbs_new.php?offset=$next'>前のページ</a>]";
}
if ($offset>0){
$prev = $offset-$page_max;
print "[<a href='bbs_new.php?offset=$prev'>次のページ</a>]";
}
//rowに1行ずつ取得したデータが入る
//返信データの有無
$sql2 = 'select * from message order by no desc';
foreach ($db->query($sql2) as $row2) {
//入力フォームの書き出し
if ($_GET['resno']) {
print "<input type='submit' name='write' value='No.{$_GET['resno']} に返信'>\n";
print "<input type='hidden' name='resno' value='{$_GET['resno']}'>\n";
} else {
print "<input type='submit' name='write' value='送信'>\n";
print "<hr>\n";
print "記事番号:<input type='text' name='delno'>\n";
print " 削除キー: <input type='password' name='delkey2'>\n";
print " <input type='submit' name='delete' value='記事削除'>\n";
}
}
}
//header("Location: bbs_new.php");
//データベースへ書き込みを行う処理
function proc_regist(){
// グローバル変数から取り出す
$db = $GLOBALS['db'];
//記事番号
$sql = 'select no from message order by no desc';
$maxno = 0;
$no = $maxno + 1;
$_POST['no'] = $no;
if(!$_POST['resno']){
$_POST['resno'] = $_POST['no'];
}
//データベースへインサート
$sql = 'insert into message values(?,?,?,?,?,?,?,?)';
$st = $db->prepare($sql);
$result = $st->execute(array($_POST['no'], $_POST['resno'],$_POST['name'], $_POST['mail'],$_POST['title'], $_POST['contents'],$_POST['delkey'], $_POST['time']));
}
header("Location: bbs_new.php");
//データベースから削除を行う処理
function proc_delete(){
$db = $GLOBALS['db'];
$sql = 'delete from message where no = ? and delkey = ? ';
$sth = $db->prepare($sql);
$ret = $sth->execute(array($_POST['no'],$_POST['delkey']));
header("Location: bbs_new.php");
}
?>
</body>
</html>

What if you try this?
print "<input type='submit' name='action' value='write'>\n";
print "<hr>\n";
print "記事番号:<input type='text' name='delno'>\n";
print "削除キー: <input type='password' name='delkey'>\n";
print "<input type='submit' name='action' value='delete'>\n";
print "<input type = 'hidden' name = 'action' value = 'delete'>\n"; (remove this line)

Related

PHP rows send 1 mySQLi record to form for edit [duplicate]

I have searched all over this website, but not yet found the answer for this. Pr maybe I am not able to apply it correctly. I have a form that grabs all photos with a certain GALLERY_id attached to it. The backend user can then change the title of the photo and change the tags. After submitting the form the query should update all rows. Here is what I have so far which does not doe anyting:
THE FORM
if(isset($_GET['id']))
{
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM photos WHERE gallery_id = :gallery_id ");
$result->bindParam(':gallery_id', $id);
$result->execute();
echo '<form action="" method="POST">';
echo "<ul id='photos'>";
for ($i = 0; $row = $result->fetch(); $i++)
{
$id = $row['id'];
$title = $row['title'];
$tags = $row['tags'];
$src = $row['src'];
echo "<li><a class='lightbox' href='images/$src'><img src='images/$src' id='$id' alt='$title' /></a><br />";
echo "<input type='text' name='photo_title' value='$title' /><br />";
echo "<input type='text' name='photo_tags' value='$tags' />";
echo "<input type='hidden' name='photo_id' value='$id' />";
echo "</li>";
}
echo "</ul>";
}
?>
<div style="clear:both"></div>
<input type="submit" name="changeTitle" value="Save"/>
</form>
UPDATE QUERY
if (isset($_POST['changeTitle']))
{
foreach ($_POST as $p)
{
$id=$p['photo_id'];
$title=$p['photo_title'];
$tags=$p['photo_tags'];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}
}
Since you have multiple html fields with same names, you have to submit them as an arrays:
echo "<input type='text' name='photo_title[]' value='$title' /><br />";
echo "<input type='text' name='photo_tags[]' value='$tags' />";
echo "<input type='hidden' name='photo_id[]' value='$id' />";
After submitted, loop through any array variable like
foreach ($_POST['photo_id'] as $key => $photo_id) {
$id = $photo_id;
$title = $_POST['photo_title'][$key];
$tags = $_POST['photo_tags'][$key];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}

How do I create an edit-option for each row in a table?

I am using the following code to display certain rows from my database table:
<?php
$searchtype=$_POST['searchtype'];
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchtype || !$searchterm)
{
echo 'Error';
exit;
}
if (!get_magic_quotes_gpc())
{
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
$db = include "connect2db.php";
$query = "select * from notes where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo '<p>Number of rows found: '.$num_results.'</p>';
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<i>';
echo stripslashes($row['date']);
echo '</i><br /> ';
echo '<b>';
echo stripslashes($row['notetitle']);
echo '</b><br /> ';
echo stripslashes($row['note']);
echo '<br /><br /> ';
echo '</p>';
}
$result->free();
$db->close();
?>
Now I would like to display an edit-link for each row displayed, that can open a new page in which it is possible to edit a specific row. I already have the code that lets you edit the row:
<?php
if ($_REQUEST['save']=="Save") { // is data submitted?
// create variables
$noteid = $_REQUEST['noteid'];
$coursename = $_REQUEST['coursename'];
$notetitle = $_REQUEST['notetitle'];
$note = $_REQUEST['note'];
$query = "UPDATE notes SET ";
$query .= "coursename='$coursename', ";
$query .= "notetitle='$notetitle', ";
$query .= "note='$note' ";
$query .= "WHERE noteid='$noteid'";
$result = $db->query($query);
} elseif ($_REQUEST['delete']=="Delete") { // is data to be removed?
$noteid = $_REQUEST['noteid'];
$query="DELETE FROM notes WHERE noteid='$noteid'";
$result = $db->query($query);
}
?>
<div class="formular">
<div class="row1">
<p>Id</p>
<p>Notetitle</p>
<p>Note</p>
</div>
<?php
$query = "SELECT * FROM notes ORDER BY noteid DESC";
$result = $db->query($query);
while ($row = mysqli_fetch_array($result)) {
echo "<form ".$_SERVER['PHP_SELF']." name='edit-form' method='post' class='row1'>\n";
echo "<p class='align_top padding_top'>".$row['noteid']."<input type='hidden' name='noteid' value='".$row['noteid']."' /></p>\n";
echo "<p class='align_top'><input type='text' name='notetitle' value='".$row['notetitle']."' /></p>\n";
echo "<p><textarea name='note' rows='10' cols='50'>".$row['note']."</textarea></p>\n";
echo "<p><input type='submit' name='save' value='Save' /></p>";
echo "<p><input type='submit' name='delete' value='Delete' /></p>";
echo "</form>\n";
}
echo '</div>';
$result->free();
$db->close();
?>
What I am struggling with is how to display an edit-link for each row that lets you open a page where you can edit/delete the content of only that row.
I hope someone can help, I am very new at this.
Thank you!
Add a button next to each row that opens an edit page (or modal) with the id inside, example: <button onclick="edit('randomId')">Edit RandomId </button>
You could implement something different that accepts the unique id of that specific row and open a new page or modal with it.

Creating record in php quotation mark issue

I'm trying to create a user record to input into a phpmyadmin database.
createUserRecord($usersTable, [$r2,"'".$_POST["firstName"]."'","'".$_POST["lastName"]."'","'".$_POST["username"]."'","'".$_POST["password"]."'","'".$_POST["admin"]."'","'".$_POST["email"]."'"]);
I think there is an issue with the quotation marks or concatenation of the $_POST variables.
There is a record created in the phpmyadmin database, but the values are either not there for the text data types or the two integer value are showing up as 0. When I use print_r to print the values of this createUserRecord, it only prints '1'.
This is the code for the signup page that creates user records:
<html>
<body>
<p><h2><strong>Welcome to the Marist Room Reservation Recommender!</strong></h2></p>
<p><h3><strong>Reserve a room below!</strong></h3></p>
<?php
require 'sql_helper3.php';
if ($_POST[submitted] == "submitted") {
$r2 = (rand(11111,99999));
createUserRecord($usersTable, [$r2,"'".$_POST["firstName"]."'","'".$_POST["lastName"]."'","'".$_POST["username"]."'","'".$_POST["password"]."'","'".$_POST["admin"]."'","'".$_POST["email"]."'"]);
header('location:verify3.php');
} else {
echo "<h1>Please enter your details:</h1>";
echo "<form action=verify3.php method=post>\n";
echo "First Name: <input type=text name=firstName placeholder=\"Enter First Name\" required=required>\n<br>";
echo "Last Name: <input type=text name=lastName placeholder=\"Enter Last Name\" required=required>\n<br>";
echo "CWID: <input type=\"text\" name=\"CWID\" placeholder=\"Enter CWID\" required=required>\n<br>";
echo "Class: <select name=\"class\">\n";
echo "<option value=\"1\">Freshman</option>\n";
echo "<option value=\"2\">Sophomore</option>\n";
echo "<option value=\"3\">Junior</option>\n";
echo "<option value=\"3\">Senior</option>\n";
echo "</select>\n<br>";
echo " Gender:\n";
echo " <select option name = \"Gender\">\n<br> ";
echo " <option value = \"None\">Select One...</option>\n<br> ";
echo " <option value = \"Male\">Male</option>\n<br> ";
echo " <option value = \"Female\">Female</option>\n<br> ";
echo " </select>\n<br> ";
$sql = "SELECT name, roomsAvailable FROM $dormTable";
if($result = mysqli_query($conn, $sql)) {
$numRows = mysqli_num_rows($result);
echo " <strong>Residence Areas</strong>\n ";
echo " <select name = dorm> \n";
for ($i = 0; $i < $numRows; $i++){
$aDorm = mysqli_fetch_assoc($result);
$dormName = $aDorm['name'];
$dormAvailable = $aDorm['roomsAvailable'];
if($dormName != 'Select One...' && $dormAvailable != 0){
echo "<option value = \"$dormName\" > $dormName ($dormAvailable)</option>\n";
}
elseif ($dormAvailable == 0 && $dormName != 'Select One...'){
echo "<option value = \"$dormName\" disabled=\"disabled\"> $dormName </option> \n";
}
elseif ($dormName == 'Select One...'){
echo "<option value = \"$dormName\"> $dormName </option> \n";
}
}
echo "</select>\n<br><br>";
}
else {
echo "something is wrong: " .mysqli_error($conn);
echo $result;
die;
}
echo "<input type=checkbox name=specialNeeds value=\"1\">Special Needs?\n<br>";
echo "<input type=checkbox name=laundry value=\"1\">Laundry?\n<br>";
echo "<input type=checkbox name=fullyEquippedKitchen value=\"1\">Kitchen?\n<br><br>";
echo "Username:<input type=text name=username placeholder=\"Enter Username\" required=required><br>\n";
echo "Password:<input type=password name=password placeholder=\"Enter Password\" required=required><br>\n";
echo "Email Address:<input type=email name=email placeholder=\"Enter Email\" required=required><br><br>\n";
echo "<input type=checkbox name=admin value=\"1\">Administrator?\n<br>";
echo "<input type=hidden name=submitted value=submitted>\n<br>";
echo "<input type=\"submit\" value=\"Signup\">\n<br>";
echo "</form>\n";
foreach ($_POST as $k => $v){
echo"<input type = hidden name = $k value = \"$v\"> <?php echo print_r($_POST) ?>";
}
}
?>
</body>
This is the function that is called from another php page:
$table = $usersTable;
function createUserRecord($table, $values) {
echo "<br> in createUserRecord(), table is \"$table\", values are ".print_r($values)."\n<br>";
return insertInto($table, ["id", "firstName", "lastName", "username", "password", "admin"], $values);
var_dump($values);
}
function insertInto($table, $columns, $values) {
$sql = "INSERT INTO $table (`" . implode("`, `", $columns) . "`) VALUES ('" . implode("', '", $values) . "')";
return query($sql);
}
This is the results page:
<?php
//Take user selection from verify
require 'sql_helper3.php';
date_default_timezone_set('America/New_York');
$date = date('m/d/Y h:i:s a', time());
$dorm = $_POST["dorm"];
$sql = "SELECT * FROM $dormTable WHERE name = '$dorm'";
if ($result = mysqli_query($conn, $sql)) {
$dormRecord = mysqli_fetch_assoc($result);
}
$reservationsTable = "Reservations";
$r1 = (rand(11111,99999));
// SQL query to fetch information of registered users and finds user match.
$username=$_POST['username'];
$password=$_POST['password'];
$sql = "SELECT * FROM $usersTable WHERE password = \"$password\" AND username = \"$username\"";
echo "Running SQL $sql\n<br>";
$result = mysqli_query($conn,$sql);
$_SESSION['login_user']=$username; // user is logged in now
// echo "Initializing session...";
$aUser = mysqli_fetch_assoc($result);
//print_r($aUser);die;
$_SESSION['user_firstname'] = $aUser['firstName'];
$_SESSION['user_lastname'] = $aUser['lastName'];
$_SESSION['user_email'] = $aUser['email'];
$_SESSION['user_class'] = $aUser['class'];
$_SESSION['user_gender'] = $aUser['Gender'];
$_SESSION['user_kitchen'] = $aUser['fullyEquippedKitchen'];
$_SESSION['user_laundry'] = $aUser['laundry'];
$_SESSION['user_specialneeds'] = $aUser['specialNeeds'];
$_SESSION['user_admin'] = $aUser['admin'];
$_SESSION['user_id'] = $aUser['id'];
createReservationRecord($reservationsTable, [$r1, $date, "'".$usersTable[id]."'", "'".$dormRecord[id]."'", "'".$_POST[CWID]."'", "'".$_POST[firstName]."'", "'".$_POST[lastName]."'", "'".$_POST['class']."'", "'".$_POST[gender]."'", "'".$_POST[fullyEquippedKitchen]."'", "'".$_POST[laundry]."'", "'".$_POST[specialNeeds]."'"]);
//Update the record where the dorm id is used and set the roomsAvailable to -1 for that dorm
$sql = "UPDATE $dormTable SET roomsAvailable = ".--$dormRecord[roomsAvailable] ." WHERE id = $dormRecord[id]";
query($sql);
//Update the record where the dorm id is used and set the roomsreserved to +1 for that dorm
$sql = "UPDATE $dormTable SET roomsReserved = ".++$dormRecord[roomsReserved] ." WHERE id = $dormRecord[id]";
query($sql);
echo"<br>This is the users table ".print_r($usersTable)."<br>";
?>
<html>
<body>
<h1>Reservation Confirmation </h1>
</table>
Confirmation Number: <?php echo "$r1"; ?> <br>
Date: <?php echo "$date";?><br>
First Name: <?php echo $_POST["firstName"];?><br>
Last Name: <?php echo $_POST["lastName"]; ?><br>
CWID: <?php echo $_POST["CWID"]; ?><br>
Gender: <?php echo $_POST["Gender"]; ?><br>
Class: <?php
if($_POST["class"] == 1){
echo "Freshman";
}
elseif($_POST["class"] == 2){
echo "Sophomore";
}
else{
echo "Junior/Senior";
//or we could do upperclassman
}
; ?><br>
Residence Area: <?php echo $_POST["dorm"]; ?><br>
Special Needs: <?php
if ($_POST["specialNeeds"]){
echo "Yes";
}
else{
echo "No";
} ?><br>
Laundry: <?php if (isset($_POST["laundry"])){
echo "Yes";
}
else{
echo "No";
}
?><br>
Fully Equipped Kitchen: <?php
if (isset($_POST["fullyEquippedKitchen"])){
echo "Yes";
}
else{
echo "No";
}
if ($aUser["admin"]) {
echo "<br><br><a href=admin_main.php>Click here</a> to go to the admin landing page.\n<br>";
//header("location: admin_main.php"); // redirecting to admin landing page
}
else {
echo "<br><br><a href=reservations.php>Click here</a> to go to the reservations page.\n<br>";
// header('Location: profile.php'); // Redirecting To Students Landing page
}
?>
<br>
</body>
The output for this results page is:
Running SQL SELECT * FROM Users WHERE password = "bbb" AND username = "kk"
Warning: Illegal string offset 'id' in /home/ubuntu/workspace/Project_Three/results3.php on line 42 Call Stack: 0.0003 241480 1. {main}() /home/ubuntu/workspace/Project_Three/results3.php:0 Users
This is the users table 1
Reservation Confirmation
Confirmation Number: 19843
Date: 11/29/2016 01:28:30 pm
First Name: k
Last Name: b
CWID: 18738783
Gender: Female
Class: Freshman
Residence Area: Leo Hall
Special Needs: No
Laundry: No
Fully Equipped Kitchen: No
Click here to go to the reservations page.

Refresh previous form table after submit button

How do I refresh the table when I click EDIT NOW Button? or this is easier, how do I make refresh button to refresh the table? I have no knowledge on JSP to auto refresh. However, I manage to make an onchange event so when I choose menu, it will refresh upon changing. When I edit a data and submit, it does not refresh. How do I re-execute the echo of table? Thanks!
<?php
$selected='';
function get_options($select)
{
$conn = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$result = $conn->query("select * from students");
$options='';
while ($row = $result->fetch_assoc())
{
$LRN = $row['LRN'];
$Last = $row['Last_Name'];
$First = $row['First_Name'];
if($LRN == $_GET['Students'])
{
$options.='<option value="'.$LRN.'" selected>'.$Last.', '.$First.'</option>';
}
else
{
$options.='<option value="'.$LRN.'">'.$Last.', '.$First.'</option>';
}
}
return $options;
}
if (isset($_GET['Students'])) {
$conn = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$result = $conn->query("select * from students");
$lrn = $_GET['Students'];
$stmt = $conn->prepare("SELECT Last_Name, First_Name, Level, Q1, Q2, Q3, Q4, FINAL FROM english WHERE LRN = ?");
$stmt->bind_param('i', $lrn);
$stmt->execute();
$stmt->bind_result($last, $first, $level, $q1, $q2, $q3, $q4, $final);
$stmt->fetch();
echo "<table><tr><th>LRN</th><th>Name</th><th>Level</th><th>Q1</th><th>Q2</th><th>Q3</th><th>Q4</th><th>Final</th></tr>";
echo "<tr><td>$lrn</td><td>$last, $first</td><td>$level</td><td>$q1</td><td>$q2</td><td>$q3</td><td>$q4</td><td>$final</td></tr></table>";
}
echo "<html>";
echo "<body>";
echo "<form method=GET>";
echo "<select name=Students onchange=this.form.submit();>";
echo get_options();
echo "</select>";
echo "</form>";
echo "<form method=POST>";
///////////EDIT DATA
echo "Edit Data: ";
echo "<select name = 'Edit'>";
echo '<option value=Q1>Q1</option>';
echo '<option value=Q2>Q2</option>';
echo '<option value=Q3>Q3</option>';
echo '<option value=Q4>Q4</option>';
echo '<option value=FINAL>FINAL</option>';
echo '<input type="number" max="100" name="editdata" required>';
echo "</select>";
echo "<input type='submit' name='submit2' value='Edit Now'>";
if (isset($_POST['Edit'])) {
$conn2 = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$upd = $_POST['Edit'];
$txt = $_POST['editdata'];
$now = "UPDATE english SET $upd='$txt' WHERE LRN='$lrn'";
$res = $conn2->query($now);
if (!$conn2->error) {
echo "Errormessage: $conn->error";
}
echo $now;
}
echo "</form>";
echo "</body>";
echo "</html>";
?>
I would use 2 pages view.php and edit.php. View would display the data with link to edit. When you click edit it would open edit.php to load the form to edit data and save it to db. Then issue the command
header("Location: view.php");
to reload the view.php and display the new data
I have uploaded the scripts I use as a basis for databases so you can see if this is what you want - feel free to amend any data it is just a test database. If you want more code just ask
www.cambodia.me.uk/php/view.php
Edited to include scripts as requested - sorry it is old code and mysql not mysqli
Connect script
<?php
/*
CONNECT-DB.PHP
Allows PHP to connect to your database
*/
// Database Variables (edit with your own server information)
$server = 'server';
$user = 'user';
$pass = 'pass';
$db = 'database';
// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>
View script
<?php
include('remote-connect.php');
$result = mysql_query("SELECT * FROM stats")
or die(mysql_error());
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>date</th> <th>Home Team</th> <th></th><th></th><th>Away Team</th> <th></th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['date'] . '</td>';
echo '<td>' . $row['hometeam'] . '</td>';
echo '<td>' . $row['fthg'] . '</td>';
echo '<td>' . $row['ftag'] . '</td>';
echo '<td>' . $row['awayteam'] . '</td>';
echo '<td>Edit</td>';
//echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
Edit script
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
function renderForm($id, $hometeam, $awayteam, $error)
{
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="hometeam" value="<?php echo $hometeam; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="awayteam" value="<?php echo $awayteam; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
include('remote-connect.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['id']))
{
$id = $_POST['id'];
$hometeam = mysql_real_escape_string(htmlspecialchars($_POST['hometeam']));
$awayteam = mysql_real_escape_string(htmlspecialchars($_POST['awayteam']));
if ($hometeam == '' || $awayteam == '')
{
$error = 'ERROR: Please complete all mandatory fields!';
renderForm($id, $hometeam, $awayteam, $error);
}
else
{
mysql_query("UPDATE stats SET hometeam='$hometeam', awayteam='$awayteam' WHERE id='$id'")
or die(mysql_error());
// Go back to view page and redisplay the edited data
header("Location: view.php");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM stats WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$hometeam = $row['hometeam'];
$awayteam = $row['awayteam'];
renderForm($id, $hometeam, $awayteam, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
</body>
</html>
It's so easy. If you fetch your table's values after edit or delete operation, sql will bring fresh data.

Issue with array formula and parsing array into database

i am creating a form to do billing and i had a fatal error on the total_amt_array. Also, how do i parse an array of items into database? The form is in the Create Invoice and the invoicesubmit is where it adds all the arrays into the database. Anyone can explain to me why i can't make a total sum of the discount, amount and quantity array.
Also, does anyone have an easier way to calculate all of the total_amt_array. I've searched stackoverflow and others find the final total amount by adding the entire cost column to get the final total cost amount.
Create Invoice
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var count = 0;
function addTextArea(){
count= count+1;
var div = document.getElementById('name');
div.innerHTML += "<div> <input type='text' name='name[]' value='' "+"id=name"+count+"> </div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('quantity');
div.innerHTML += "<div><input type='text' name='quantity[]' value ='' "+"id=quantity"+count+"></div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('amount');
div.innerHTML += "<div><input type='text' name='amount[]' value ='' "+"id=amount"+count+"></div>";
div.innerHTML += "\n<br />";
var div = document.getElementById('discount');
div.innerHTML += "<div><input type='text' name='discount[]' value ='' "+"id=discount"+count+"></div>";
div.innerHTML += "\n<br />";
}
function removeTextArea(){
document.getElementById("name"+count).remove();
document.getElementById("quantity"+count).remove();
document.getElementById("amount"+count).remove();
document.getElementById("discount"+count).remove();
count = count-1;
}
</script>
</head>
<body>
<form action="invoicesubmit.php" method="POST">
<?php
echo "<table border='2'>\n";
echo "<tr>\n";
echo "<th>Description</th>\n";
echo "<th>Quantity</th>\n";
echo "<th>Amount($)</th>\n";
echo "<th>Discount(%)</th>\n";
echo "</tr>";
echo "<tr>";
echo "<td>"?><input type='text' size="50" name='name[]' value='Examination and Consultation' readonly/><?php "</td>";
echo "<td>"?><input type='text' size="50" name='quantity[]' value='' /><?php "</td>";
echo "<td>"?><input type='text' size="50" name='amount[]' value='' /><?php "</td>";
echo "<td>"?><input type='text' size="50" name='discount[]' value='' /><?php "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>"?><div id="name"></div> <?php "</td>";
echo "<td>"?><div id="quantity"></div> <?php "</td>";
echo "<td>"?><div id="amount"></div> <?php "</td>";
echo "<td>"?><div id="discount"></div> <?php "</td>";
echo "</tr>";
?>
<br />
<input type="button" value="Add Description" onClick="addTextArea();">
<input type="button" value="Remove Description" onClick="removeTextArea();">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
invoicesubmit
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php
if (isset($_POST['submit'])) {
// Process the form
$name_array = $_POST['name'];
$quantity_array = $_POST['quantity'];
$amount_array = $_POST['amount'];
$discount_array = $_POST['discount'];
$total_amt_array = ($amount_array - ($amount_array * ($discount_array/ 100))) * $quantity_array ;
for ($i =0; $i < count($name_array); $i++) {
$name = $name_array[$i];
$quantity = $quantity_array[$i];
$amount = $amount_array[$i];
$discount = $discount_array[$i];
$total_amt = $total_amt_array[$i];
echo $name;
echo "<br />";
echo $quantity;
echo "<br />";
echo $amount;
echo "<br />";
echo $discount;
echo "<br />";
echo $total_amt;
}
}
/*
//validations
$required_fields = array("name", "quantity", "amount", "discount");
validate_presences($required_fields);
$fields_with_max_lengths = array("name" => 200);
validate_max_lengths($fields_with_max_lengths);
if (!empty($errors)) {
$_SESSION["errors"] = $errors;
redirect_to("create_invoice.php");
}*/
/*
// 2. Perform database query
$query = "INSERT INTO invoicesub (";
$query .= " description, quantity, amount, discount, total";
$query .= ") VALUES (";
$query .= " '{$name}', '{$quantity}', '{$amount}', '{$discount}', '{$total}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Subject created.";
redirect_to("confirm_invoice.php");
}
else {
// Failure
$_SESSION["message"] = "Subject creation failed.";
redirect_to("create_invoice.php");
}
} else {
// This is probably a GET request
redirect_to("create_invoice.php");
} */
?>
<?php
if (isset($connection)) { mysqli_close($connection); }
?>
First you have:
echo "<td>"?><input type='text' size="50" name='amount[]' value='' /><?php "</td>";
^^---create an array in $_POST
Then:
$amount_array = $_POST['amount'];
^^^^^^^^^^^----this is now an array
Then:
$total_amt_array = ($amount_array - ($amount_array * ($discount_array/ 100))) * $quantity_array ;
This code boils down to:
$total_amt_array = Array - (Array * (Array / 100))) * Array;
You cannot multiply/divide arrays in PHP.

Categories