I use HTML form to insert data to a database table. What I want to do is to display the data I inserted using the HTML form. I use associative arrays to get the right data from the database. But I can only display only one row from the table. I don't know why my code doesn't display the other data I inserted.
Here is my code:
<?php
$part_insert_message = "";
enter code here
session_start();
$inserted_parts = array();
$part_inserted_id;
if(isset($_POST['submit'])) {
require "/Basics/Mysql_Connect/mysql_connect.php";
$sql="INSERT INTO Parts (SKU, Part, Description, Quantity, Price)
VALUES
('$_POST[sku]', '$_POST[categories]', '$_POST[description]', '$_POST[quantity]', '$_POST[price]')";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
$part_inserted_id = mysqli_insert_id($con);
$inserted_parts[$part_inserted_id] = $part_inserted_id;
// store session data
$_SESSION['views']= $inserted_parts;
$part_insert_message = "ID: " . $part_inserted_id . " Part: " . $_POST['sku'];
mysqli_close($con);
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
if(isset($_SESSION['views'])){
$inserted_parts = $_SESSION['views'];
}
if(!empty( $inserted_parts )) {
require "/Basics/Mysql_Connect/mysql_connect.php";
foreach($inserted_parts as $key => $value){
$sql = "SELECT * FROM Parts WHERE PartID='$key'";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
$productCount = mysqli_num_rows($result); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($result)){
$partID = $row["PartID"];
$sku = $row["SKU"];
$part = $row["Part"];
$description = $row["Description"];
$quantity = $row["Quantity"];
$price = $row["Price"];
$product_list .= "Product ID: $partID - <strong>$sku</strong> - $$price - <em>Part $part</em> <a href='Add_Delete_Part.php?deleteid=$partID'>delete</a><br />";
}
}else {
$product_list = "You have no products listed in your store yet";
}
}
mysqli_close($con);
}
?>
<?php
require "/Basics/Mysql_Connect/mysql_connect.php";
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = "DELETE FROM Parts WHERE PartID='$id_to_delete'";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
// unlink the image from server
// // Remove The Pic -------------------------------------------
// $pictodelete = ("../inventory_images/$id_to_delete.jpg");
// if (file_exists($pictodelete)) {
// unlink($pictodelete);
// }
header("location: Add_Delete_Part.php");
exit();
}
mysqli_close($con);
?>
<html>
<body>
<div>
<h2>Part</h2>
<form action="Add_Delete_Part.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
SKU#: <input type="text" name="sku"><br>
Part: <select name="categories">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select><br>
Description: <input type="text" name="description"><br>
Quantity: <input type="text" name="quantity"><br>
Price: <input type="text" name="price"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php echo $part_insert_message; ?>
<h3>Fits:</h3>
<?php echo $product_list; ?>
<!--<form action="Add_Images.php" method="post">
Select images: <input type="file" name="img" multiple><input type="submit" value="Upload">
</form>
-->
</div>
</body>
</html>
Related
I'm not sure how to describe it, so here's a video where I explain my problem.
I tried rearranging some of the code, as I do believe nothing is faulty, attempting to make sure that the table refreshes with the new data inside it, however every time I tried to place my code in a different order (executing the queries in different orders), it either functions differently than how I want it to function or it doesn't function at all.
Both queries do function separately, I'm just unsure why they're not working together.
Searchbar has the value seen inputted in the homepage on both my Search page and this page in question. However it was left blank for this page, which gave me the result of having the full table display which is what I wanted to happen. I'm just not sure how I can edit my code so, when submitted, it will display the newly added data.
My PHP:
<?php
$find = $_POST['searchbar'];
$host = "localhost";
$username = "FFF";
$pword = "L3FhqJNey8Op2qJY";
$database = "Project";
include 'includes/db.inc.php';
$Name2 = $_POST['Name'];
$YearOfRelease2 = $_POST['YearOfRelease'];
$Studio2 = $_POST['Studio'];
$Age2 = $_POST['Age'];
$Score2 = $_POST['Score'];
?>
My HTML:
<html>
<head>
<title>Add a Film - Films! Films! FILMS!</title>
</head>
<body>
<h1>Films! Films! FILMS!</h1>
<h2>Add a Film</h2>
<p>If you wish to add a film to our database, feel free to add data relating to the film in the respective boxes below. You should then refresh the page.</p>
<p>Add Film:</p>
<form method="POST" action="AddFilm.php">
<p>Name of Film: <input type="text" name="Name"></p>
<p>Year of Release: <input type="text" name="YearOfRelease"></p>
<p>Name of Studio: <input type="text" name="Studio"></p>
<p>Age Rating: <select name="Age" size="1">
<optgroup label="Select Age Rating">
<option value="U">U</option>
<option value="PG">PG</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="18">18</option>
</optgroup>
</select></p>
<p>Review Score: <input type="text" name="Score"></p>
<p><input type="submit" name="submit" value="Submit and Refresh"></p>
</form>
<?php
echo "<h2>$output</h2>";
$query_string = "SELECT * FROM movies WHERE Name LIKE '%$find%' OR YearOfRelease LIKE '%$find%' OR Studio LIKE '%$find%' OR Age LIKE '%$find%' OR Score LIKE '%$find%'";
$query_string2 = "INSERT INTO movies (Name, YearOfRelease, Studio, Age, Score) VALUES ('$Name2', '$YearOfRelease2', '$Studio2', '$Age2', '$Score2');";
if ($result = $mysqli->query($query_string2)) {
$output2 = $Name2 ." has been added to the database.";
echo "<p>$output2</p>";
} else {
echo ("Error performing query: " . $mysqli->error() );
}
$result->close();
if ($result = $mysqli->query($query_string)) {
echo "<table border='1'>";
echo "<tr><th>FilmID</th><th>Name</th><th>YearOfRelease</th><th>Studio</th><th>Age</th><th>Score</th></tr>";
while ($row = $result->fetch_object())
{
$FilmID = $row->FilmID;
$Name = $row->Name;
$YearOfRelease = $row->YearOfRelease;
$Studio = $row->Studio;
$Age = $row->Age;
$Score = $row->Score;
$output ="<tr><td> $FilmID";
$output = $output . "<td> $Name";
$output = $output . "<td> $YearOfRelease";
$output = $output . "<td> $Studio";
$output = $output . "<td> $Age";
$output = $output . "<td> $Score </tr>";
echo "<p>$output</p>";
}
echo "</table>";
echo "<hr>";
echo '<p>Back to Home Page</p>';
$result->close();
} else {
echo ("Error performing query: " . $mysqli->error() );
}
$mysqli->close();
?>
</body>
</html>
I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.
So I have a form to add a new item to database with a checkbox as follows
So my difficulty is the checkbox. I can easily enough create the array for all items checked but I need an ID for them along with it. I've tried to think of many ways and searched a lot but I just can't think of a way to get the ID in a way that is then useable to me along with the name of the feature (checklist). Since I have to get each feature item and add it to the table houses_has_features.
<?php
$title = 'Add a new house';
require_once 'header.php';
require_once 'nav.php';
require_once 'mysqli-con.php';
$conn = new MYSQLI($hn, $un, $pw, $db);
// If house name and type is set then add them into the database
if( !empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
$house_name = $conn->real_escape_string($_POST['h_name']);
$house_type = $conn->real_escape_string($_POST['h_type']);
//show names added
echo '<b>House name: </b>'.$house_name . '<br><b> House type:</b> ' . $house_type;
$query = "INSERT INTO `house_names` (`id`, `name`) VALUES (NULL, '$house_name')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
global $house_name_id;
$house_name_id = $conn->insert_id;
$query = "INSERT INTO `house_types` VALUES ('$house_name_id', '$house_type')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
} else {
global $house_name_id;
$house_name_id= NULL;
}
//Start container for page content
echo '<div class="container">';
//Display an error message if house name is filled in but not house type
if ( !empty($_POST['h_name']) && empty($_POST['h_type']) || empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
echo "<p class='error-text'>* Please fill in both the house name and house type *</p>";
}
$query_feat = $conn->query('SELECT * FROM features');
$rows = $query_feat->num_rows;
$features_list = $_POST['check_list'];
$feature_id = $_POST['feature_id'];
//display checked boxes.
if(isset($_POST['check_list'])) {
for ($i=0; $i<sizeof($features_list); $i++){
//echo '<br>House name id:' . $house_name_id . '<br> $_POST[] = ' . "$features_list[]";
print_r($features_list); echo '<br>';
print_r($feature_id);
}
}
// Add house form
echo <<<_END
<h1>Add a house</h1>
</div>
<div class="container">
<form action="add.php" method="post">
<p>House Name: <input type="text" name="h_name"></p>
<p>House type: <input type="text" name="h_type"></p>
<b>features:</b>
<ul class="list-group">
_END;
for ($c = 0 ; $c < $rows ; ++$c){
$query_feat->data_seek($c);
$feat = $query_feat->fetch_array(MYSQLI_NUM);
echo '<li><input type="checkbox" name="check_list[]" value="' .$feat[1]. '">'.$feat[1].'</li>';
}
echo <<<_END
<ul>
<input class="btn-primary" type="submit" value="Submit">
</form>
</div>
_END;
require_once 'footer.php';
I'm really lost on this one any help would be greatly appreciated :)
change your value of checkbox to id or anything you want.
<li><input type="checkbox" name="check_list[]" value="' .$feat[0]. '">'.$feat[1].'</li>
$feat[1] => $feat[0] or else
Hello my name is Patrick and this is my first question, i'm sorry but i'm not very good in PHP. probably there are more improvements but this post is for the questions. (but improvements are also welcome)
Question:
You can choose a team of 2 monsters // The monster are selected form database
The question is: if you choose 1 monster how can i fix that you can't choose the same monster on option 2?
PHP CODE:
Action of the 2 sumbit buttons
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if (isset($_POST['save'])) {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if($Result){
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5'){
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if($Result){
echo 'Team is aangepast!';
}
}
echo '';}
?>
Get the monsters form database and put it in a select list
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option4 = '';
while($row = mysql_fetch_assoc($get))
{
$option4 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
Show the selected item
<?php
$k4 = mysql_query("
SELECT user_team.m_keuze4, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze4=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row4 = mysql_fetch_assoc($k4))
{
$k4_1 = ''.$row4['m_keuze4'].' - '.$row4['monster'].' - '.$row4['type'].' - '.$row4['attack'].' - '.$row4['defense'].'';
}
?>
Option 5 is the same code as 4:
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option5 = '';
while($row = mysql_fetch_assoc($get))
{
$option5 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
<?php
$k5 = mysql_query("
SELECT user_team.m_keuze5, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze5=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row5 = mysql_fetch_assoc($k5))
{
$k5_1 = ''.$row5['m_keuze5'].' - '.$row5['monster'].' - '.$row5['type'].' - '.$row5['attack'].' - '.$row5['defense'].'';
}
?>
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form>
<form action="team.php" method="post">
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
In php the best you can do check the option once its posted:
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST,'option4') == filter_input(INPUT_POST,'option5')){
echo "Sorry. You can't select the same monster twice";
}else{
//your db insert logic goes here
}
}
It would be a good idea to also include some javascript to alert the user before they submit the form. This example uses jQuery
$('[name="option4"],[name="option5"]').change(function(){
if ($('[name="option4"]').val() == $('[name="option5"]').val()){
alert('you already chose that monster, please choose another');
}
});
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form> <!-- remove this line-->
<form action="team.php" method="post"> <!-- and this line-->
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$('[name="option4"],[name="option5"]').change(function () {
if ($('[name="option4"]').val() == $('[name="option5"]').val()) {
alert('you already chose that monster, please choose another');
}
});
});
</script>
Action of the 2 sumbit buttons
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST, 'option4') == filter_input(INPUT_POST, 'option5')) {
echo "Sorry. You can't select the same monster twice";
} else {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if ($Result) {
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5') {
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if ($Result) {
echo 'Team is aangepast!';
}
}
}
}
Edit again,
Demo Fiddle of js
I want to create a book inventory with Create, Read, Update and Delete. I got it all going except for the Update query. Here is my code. First is the proj.php
<html>
<body>
<b>BOOK INVENTORY</b>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Title: <input type="text" name="title">
Subtitle: <input type="text" name="subtitle">
Author: <input type="text" name="author">
Genre/Type: <select name="genre">
<option value="Business">Business</option>
<option value="Family">Family</option>
<option value="Romance">Romance</option>
<option value="Education">Education</option>
<option value="Self-help">Self-help</option>
<option value="Spiritual">Spiritual</option>
<option value="Music">Music</option>
</select>
Publish Date: <input type="date" name="publishdate">
Publisher: <input type="text" name="publisher">
Series: <input onkeypress="return isNumberKey(event)" type="text" name="series">
ISBN: <input type="text" name="isbn">
Pages: <input onkeypress="return isNumberKey(event)" type="text" name="pages">
Price: <input type="text" value="$" name="price">
<input type="submit" value="Create" name="submit">
</form>
<!--create new book entry-->
<?php
include 'connection.php';
if (!isset($_POST['submit'])) {
// form not submitted
}
else {
// get form input
// check to make sure it's all there
// escape input values for greater safety
$title = empty($_POST['title']) ? die ("ERROR: Enter a Title") : mysql_escape_string($_POST['title']);
$subtitle = empty($_POST['subtitle']) ? die ("ERROR: Enter an Subtitle") : mysql_escape_string($_POST['subtitle']);
$author = empty($_POST['author']) ? die ("ERROR: Enter an Author") : mysql_escape_string($_POST['author']);
$genre = empty($_POST['genre']) ? die ("ERROR: Enter a Genre/Type") : mysql_escape_string($_POST['genre']);
$publishdate = empty($_POST['publishdate']) ? die ("ERROR: Enter a Publish Date") : mysql_escape_string($_POST['publishdate']);
$publisher = empty($_POST['publisher']) ? die ("ERROR: Enter a Publisher") : mysql_escape_string($_POST['publisher']);
$series = empty($_POST['series']) ? die ("ERROR: Enter a Series") : mysql_escape_string($_POST['series']);
$isbn = empty($_POST['isbn']) ? die ("ERROR: Enter an ISBN") : mysql_escape_string($_POST['isbn']);
$pages = empty($_POST['pages']) ? die ("ERROR: Enter a Pages") : mysql_escape_string($_POST['pages']);
$price = empty($_POST['price']) ? die ("ERROR: Enter a Price") : mysql_escape_string($_POST['price']);
// create query
$insert = "INSERT INTO books (Title, Subtitle, Author, Genre, Publishdate, Publisher, Series, ISBN, Pages, Price)
VALUES ('$title', '$subtitle', '$author', '$genre', '$publishdate', '$publisher', '$series', '$isbn', '$pages', '$price')";
// execute query
$result = mysql_query($insert) or die ("Error in query: $insert. ".mysql_error());
// print message of the new book inserted
//echo "New book record created entitled "."$ ";
}
if (!isset($_POST['submit'])) {
}
$query = "SELECT * FROM symbols";
?>
<!------------><!------------><!------------><!------------><!------------>
<!------------><!------------><!------------><!------------><!------------>
<!--Delete Record-->
<?php
// set server access variables
$host = "localhost";
$user = "root";
$pass = "";
$db = "david";
// create mysqli object
// open connection
$mysqli = new mysqli($host, $user, $pass, $db);
// check for connection errors
if (mysqli_connect_errno()) {
die("Unable to connect!");
}
// if id provided, then delete that record
if (isset($_GET['id'])) {
// create query to delete record
$query = "DELETE FROM books WHERE id = ".$_GET['id'];
// execute query
if ($mysqli->query($query)) {
// print number of affected rows
echo $mysqli->affected_rows." row(s) affected";
}
else {
// print error message
echo "Error in query: $query. ".$mysqli->error;
}
}
// query to get records
$query = "SELECT * FROM books";
// execute query
if ($result = $mysqli->query($query)) {
// see if any rows were returned
if ($result->num_rows > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = $result->fetch_array()) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>Delete</td>";
echo "<td>More...</td>";
echo "</tr>";
}
}
// free result set memory
$result->close();
}
else {
// print error message
echo "Error in query: $query. ".$mysqli->error;
}
// close connection
$mysqli->close();
?>
<?php
include 'edit.php';
if (!isset($_POST['submit'])) {
}
?>
And here is my edit.php where I get the error undefined index : id at line 5
<?php
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db("david") or die(mysql_error());
$UID = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM books WHERE 'id' = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$title = $row['title'];
$subtitle = $row['subtitle'];
$author = $row['author'];
$genre = $row['genre'];
$publishdate = $row['publishdate'];
$publisher = $row['publisher'];
$series = $row['series'];
$isbn = $row['isbn'];
$pages = $row['pages'];
$price = $row['price'];
}
?>
<form action="update.php" method="get">
<input type="hidden" name="id" value="<?=$UID;?>">
Title: <input type="text" name="ud_title" value="<?=$title?>"><br>
Subtitle: <input type="text" name="ud_subtitle" value="<?=$subtitle?>"><br>
Author: <input type="text" name="ud_author" value="<?=$author?>"><br>
Genre: <input type="text" name="ud_genre" value="<?=$genre?>"><br>
Publish Date: <input type="text" name="ud_publishdate" value="<?=$publishdate?>"><br>
Publisher: <input type="text" name="ud_publisher" value="<?=$publisher?>"><br>
Series: <input type="text" name="ud_series" value="<?=$series?>"><br>
ISBN: <input type="text" name="ud_isbn" value="<?=$isbn?>"><br>
Pages: <input type="text" name="ud_pages" value="<?=$pages?>"><br>
Price: <input type="text" name="ud_price" value="<?=$price?>"><br>
<input type="Submit">
</form>
<?php
}else{
}
?>
and here is my update.php with the update query
<?php
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db("david") or die(mysql_error());
$ud_ID = (int)$_POST["id"];
$ud_title = mysql_real_escape_string($_POST["ud_title"]);
$ud_subtitle = mysql_real_escape_string($_POST["ud_subtitle"]);
$ud_author = mysql_real_escape_string($_POST["ud_author"]);
$ud_genre = mysql_real_escape_string($_POST["ud_genre"]);
$ud_publishdate = mysql_real_escape_string($_POST["ud_publishdate"]);
$ud_publisher = mysql_real_escape_string($_POST["ud_publisher"]);
$ud_series = mysql_real_escape_string($_POST["ud_series"]);
$ud_isbn = mysql_real_escape_string($_POST["ud_isbn"]);
$ud_pages = mysql_real_escape_string($_POST["ud_pages"]);
$ud_price = mysql_real_escape_string($_POST["ud_price"]);
$query="UPDATE books
SET title = '$ud_title', subtitle = '$ud_subtitle', author = '$ud_author', genre = '$ud_genre', publishdate = '$ud_publishdate',
publisher = '$ud_publisher', series = '$ud_series', isbn = '$ud_isbn', pages = '$ud_pages', price = '$ud_price'
WHERE id='$ud_ID'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($ud_ID) Record Updated<p>";
}else{
echo "<p>($ud_ID) Not Updated<p>";
}
?>
Please kindly help me get rid of this error:
undefined index: id at edit.php.
I'm shocked by the terrible formating and not able to read the code.
But according to your description, you get undefined index: id because you either did not include the id field in the form, or you include it in the url but use $_POST instead of $_GET.
EDIT:
If this is exactly the code you have, then the problem should be the last few lines in proj.php.
include 'edit.php' is not the correct way to call edit page, but you should use a link tag which links to edit.php?id=some_id, just like you did with show.php