I am building a simple web-database connection but when i assign a foreign key to my table than i am not able to insert data through html-php.
can anyone check my code and give me any suggestion/idea:
person table Primary key is ID
foreign key : KEY boardname (boardname),
KEY depname (depname)
board Table Primary key is boardname
deparment table Primary key is depname
Person table
CREATE TABLE IF NOT EXISTS `person` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
`surname` varchar(10) NOT NULL,
`boardname` varchar(10) NOT NULL,
`bsdate` date NOT NULL,
`budate` date NOT NULL,
`depname` varchar(10) NOT NULL,
`desdate` date NOT NULL,
`deudate` date NOT NULL,
PRIMARY KEY (`id`),
KEY `boardname` (`boardname`),
KEY `depname` (`depname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;
board Table
CREATE TABLE IF NOT EXISTS `board` (
`boardname` varchar(10) NOT NULL,
`boarddesc` text NOT NULL,
PRIMARY KEY (`boardname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Depament table
CREATE TABLE IF NOT EXISTS `deparment` (
`depname` varchar(10) NOT NULL,
`depcomment` text NOT NULL,
PRIMARY KEY (`depname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
now im using this simple script to insert data in the database and it not working i dont know why, but when i remove the foreign keys from person table it is working. any sugestion, i have to keep the foreign keys.
below is html php code:
HTML FORM
<body>
<h1>New Student</h1>
<form action="insert_student.php" method="post">
<table border="1">
<tr>
<td>ID</td>
<td><input type="text" name="id" maxlength="30" size="13"></td>
</tr>
<tr>
<tr>
<td>First Name</td>
<td><input type="text" name="name" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="surname" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Board Member From/Until</td>
<!--<td><input type="text" name="boardid" maxlength="7" size="7"></td>-->
<td><input type="date" name="bsdate" value="ICS" /><!--FSR-->
<input type="date" name="budate" value="Infor" />
</td>
</tr>
<tr>
<td>Department From/Until</td>
<!-- <td> <input type="text" name="depname" maxlength="30" size="30"></td>-->
<td><input type="date" name="desdate" value="ASE" />
<input type="date" name="deudate" value="WEB" />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
</form>
</body>
PHP Insert
<?php
# $db = new mysqli('localhost', 'e_kolori', 'kolori1515', 'e_color');
if (mysqli_connect_errno())
{
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "INSERT INTO person (name, surname, bsdate, budate, desdate, deudate) VALUES
('$_POST[name]', '$_POST[surname]', '$_POST[bsdate]', '$_POST[budate]', '$_POST[desdate]', '$_POST[deudate]')";
$result = $db->query($query);
if ($result)
echo $db->affected_rows.' student inserted into database.';
$db->close();
?>
Your table specifies that all the fields are required.
Your insert statement is missing values for 'depname' and 'boardname'.
Also, (may not be relevant but worth checking) there must be the associated entries in your 'board' and 'department' tables before you insert a record that references them.
Yepp Correct by removing the Not Null option in php myadmin I am able to insert data from the form but when i updated the form with those two fields boardname and departmentname which are the foreign keys in my main table now i am not able to asign the boardname and depratmentname:
by removing null working fine
and this is how my form looks like:
Insert Form looks like
Should i make any change to my code somewhere i have no idea at the moment i have tried everything till now.
this is my new query in php:
$query = "INSERT INTO person (name, surname, boardname, bsdate, budate, depname, desdate, deudate) VALUES
('$_POST[name]', '$_POST[surname]', '$_POST[boardname], '$_POST[bsdate]', '$_POST[budate]', '$_POST[depname]', '$_POST[desdate]', '$_POST[deudate]')";
Related
I am attempting to create a website in which an admin can view details about customers who shop at the store. The homepage lists the names of all of the customers, and when clicked, each name is directed to a page called CustomerDetails.php which provides more details about that particular customer. I am attempting to write some code which allows the admin to add notes to a particular customer. The two tables are as follows:
CREATE TABLE PHPNotes(
NoteID INT,
NoteContent VARCHAR(100) NOT NULL,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES CustomerEnrolment(CustomerID),
PRIMARY KEY(NoteID))ENGINE=InnoDB;
CREATE TABLE CustomerEnrolment(
CustomerID INT,
Name VARCHAR(30),
Email VARCHAR(30),
PhotoURL VARCHAR(30),
PRIMARY KEY(CustomerID)) ENGINE=InnoDB;
I am attempting to take data from a form (shown below) and insert this particular data into the database. However I am told there are errors with the code that I have written.
<?php
$Name = $_GET['Name'];
$CustomerID = $_GET['CustomerID'];
$sql1 ="SELECT * FROM CustomerEnrolment WHERE CustomerID='$CustomerID'";
$sql2 ="SELECT c.*, e.CustomerID FROM CustomerNotes c, CustomerEnrolment e WHERE e.CustomerID=n.CustomerID AND Name='$Name'" ;
if(! get_magic_quotes_gpc() ) {
$NoteContent = addslashes ($_POST['NoteContent']);
}
else {
$NoteContent = $_POST['NoteContent'];
}
$NoteID = $_POST['NoteID'];
$sql = "INSERT INTO CustomerNotes ". "(NoteID,NoteContent,CustomerID) ". "VALUES('$NoteID','$NoteContent','$CustomerID')";
$result = mysql_query($sql);
if(! $result ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
?>
<p> Add New Customer Record </p>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table id="Add Record">
<tr> <td> Note ID </td>
<td> <input name = "NoteID" type="text" id="NoteID"></td>
<td> <input name = "NoteContent" type="text" id="NoteContent"></td> </tr>
<tr> <td> <input type="hidden" name="CustomerID" value="$CustomerID"></td> </tr>
<tr> <td> <input name = "Add Customer Note" type = "submit" id = "Add Customer Note" value = "Add Customer Note"> </td> </tr>
</table>
</form>
The errors are :
Notice: Undefined index: CustomerID
Notice: Undefined index: NoteContent
Notice: Undefined index: NoteID
Could not enter data: Duplicate entry '0' for key 'PRIMARY'
Some advice as to where I am going on would be great!
One thing - your query has issues - it should be :
$sql = "INSERT INTO CustomerNotes (NoteID,NoteContent,CustomerID) VALUES('".$NoteID."','".$NoteContent."','".$CustomerID."')";
and the same could be said for your first 2 queries as well.
And you are mixing php and html and not in a good way :))
<tr>
<td>
<input type="hidden" name="CustomerID" value="$CustomerID">
</td>
</tr>
should be :
<tr>
<td>
<input type="hidden" name="CustomerID" value="<?php echo $CustomerID; ?>">
</td>
</tr>
Also you are not closing your inputs - they should be like?
<input name = "NoteID" type="text" id="NoteID" />
and also - given that noteID is your primary key - you should consider having this autoincrement and therefore you wouldn't need to have any input called "noteID" - cos without autoincrementation you need a validation mechanism to check that there is not already a note in there with that id.
Use POST function,
$Name = $_POST['Name'];
Your form is used POST method.
1) Change
$sql = "INSERT INTO CustomerNotes ". "(NoteID,NoteContent,CustomerID) ". "VALUES('$NoteID','$NoteContent','$CustomerID')";
To
$sql = "INSERT INTO CustomerNotes(NoteID,NoteContent,CustomerID) VALUES('$NoteID','$NoteContent','$CustomerID')";
2) Change
<input type="hidden" name="CustomerID" value="$CustomerID">
To
<input type="hidden" name="CustomerID" value="<?php echo $CustomerID;?>">
Another issue you may have:
<tr> <td> <input type="hidden" name="CustomerID" value="$CustomerID"></td> </tr>
If you want to display the var $CostumerID you should use php tags <?php $CostumerID ?> or <?= $CostumerID ?>.
I have a table for documents and part of that is the docs being assigned to a category. The table for doc_list looks like this:
CREATE TABLE `doc_list` (
`doc_id` int(11) NOT NULL,
`doc_title` varchar(50) NOT NULL,
`doc_content` text NOT NULL,
`doc_created` datetime NOT NULL,
`doc_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
`cat_no` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=122 ;
I am having to manually assign the cat_no (which is the category ID) but want it to be apart of my doc form submission:
<form action="actions/newDocAdd.php" method="post" id="rtf" name="">
<input type="text" name="doc_title" id="doc_title" required="required" placeholder="Document Title"/><br />
<?php
try{
$results = $dbh->query("SELECT * FROM cat_list ORDER BY cat_title ASC ");
}catch(Exception $e) {
echo $e->getMessage();
die();
}
$docs = $results->fetchAll(PDO::FETCH_ASSOC);
foreach($docs as $docs){
echo '
<input type="checkbox" name="cat_no" value="2" id="cat_no">'.$docs["cat_title"].'<br><br>
';}
?>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" style="width:100%; height: 600px;"></iframe>
<br><br>
<input onclick="formsubmit()" type="submit" value="Create Document" name="submit"/>
</form>
Now it shows me the categories and displays them as checkboxes but because some documents can be apart of more than one category i want to tick the boxes and submit them to the database.
Here is the category table:
CREATE TABLE `cat_list` (
`cat_id` int(11) NOT NULL,
`cat_title` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=5 ;
Assuming documents can have multiple categories:
First you need to group the checkboxes into an array. You can do this by using the same name with brackets.
<input type="checkbox" name="cat_no[]" value="1" />
<input type="checkbox" name="cat_no[]" value="2" />
<input type="checkbox" name="cat_no[]" value="3" />
Now when you submit the form, $_POST['cat_no'] will be an array containing the checked values.
For proper database normalization, you need a new table called something like 'doc_category'. In this table, you would have a composite key of 'doc_id' and 'cat_id':
doc_id | cat_id
1 | 1
1 | 2
1 | 3
This signifies that doc_id 1 belongs to the categories 1, 2, and 3.
The relationship from documents to categories is called a many-to-many relationship which in databases, requires a third table (intermediate).
I would like to ask how to insert an ID to the child table when I add a string value to the php table. Like for example:
I have a database called db and its corresponding tables:
CREATE TABLE IF NOT EXISTS `test1` (
`id1` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id1`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `test1` (`id1`, `fname`) VALUES
(1, 'Mary');
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `test2` (
`id2` int(11) NOT NULL AUTO_INCREMENT,
`id1` int(11) DEFAULT NULL,
PRIMARY KEY (`id2`),
KEY `id1` (`id1`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
ALTER TABLE `test2`
ADD CONSTRAINT `test2_ibfk_1` FOREIGN KEY (`id1`) REFERENCES `test1` (`id1`);
Table test1 contains the existing data, and table test2 is the child table wherein added datas are to be stored from the php.
And also the php code, assume its connected to the database:
<body>
<div style="text-align: center">
<form action="test2.php" method="POST">
<?php
include('connect.php');
$query = "SELECT fname FROM test1";
$result = mysql_query($query);
?>
<select name="select1">
<?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['fname']; ?>">
<?php echo $line['fname'];
?>
</option>
<?php }
?>
</select>
<input type="submit" value="Save" id="secret" />
</form>
<table border="1" width="200" id="sample" align="center">
<thead>
<tr>
enter code here
<th> ID </th>
<th> Name </th>
</tr>
</thead>
<tr class="record" height="100">
<td></td>
<td></td>
</tr>
</table>
</div>
</body>
test1.php
In my php code example, I have the dropdown menu containing data from the table test1 in the database and a button on the right side. If I select a data from the dropdown menu and save it, the data will be displayed to the php table and the id of the selected data will be stored in the child table test2 of the database. The problem is, how?
Please do help me with this problem.
Thank you.
I can't seem to really find a way around this problem.
I have a file named validateLogin.php as follows:
<html>
<head>
<title>Login Validation</title>
<link rel="stylesheet" type="text/css" href="CSS Files/indexstyle.css" />
</head>
<body>
<div id="middle" align="center">
<?php
if ( isset($_POST["phone"]) )
{
$phone=($_POST['phone']);
include "connect.php";
$query = mysqli_query($mysqli, "SELECT * FROM customer WHERE phone='".$phone."'");
if(mysqli_num_rows($query) > 0)
{
if (!isset($_SESSION))
session_start();
$phone=($_POST['phone']);
$_SESSION['phone']=$phone;
$_SESSION['timeout']=time();
if ($stmt=$mysqli->prepare("SELECT m.sname,m.size,m.price from sandwich s inner join menu m where s.sname=m.sname "))
{
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3);
echo'<form name="form" action = "orderUpdate.php" method="POST">
<center>
<table border cellpadding=3>
<tr>
<th style="background-color: #FFFF00;"> Sandwich Name </th>
<th style="background-color: #FFFF00;"> Size </th>
<th style="background-color: #FFFF00;"> Price </th>
</tr>';
$count1=1;
while ($stmt->fetch()) {
echo '
<tr border="1px solid black" >
<td border="1px solid black" width="30%" id="col1" name="col1">'.$col1.'</td>
<td border="1px solid black" width="10%" id="col2" name="col2">'.$col2.'</td>
<td border="1px solid black" width="20%" id="col3" name="col3">'.$col3.'</td>
<td><input type="radio" name="sandwich" value="'.$count1.'"></td>
</tr>
';
$count1=$count1+1;
}
echo '<tr> <td> <input type="submit" value="submit"/> </td></tr>';
echo'</form>';
}
}
else
{
echo '<script type="text/javascript">
alert("Sorry. Customer does not exist.");
window.location.href="index.php";
</script>';
}
}
?>
</div>
</body>
</html>
Now from the output that is generated in the table form, a user will select a particular radio button that associates a row. I need to insert this data into my mysql database table. I am however not sure how to access the appropriate col1, col2 and col3 that needs to be inserted using based on the users selection.
Schema
customer
(
phone char(10) primary key,
building_num int,
street varchar(20),
apartment varchar(20)
);
sandwich
(
sname varchar(20) primary key,
description varchar (100)
);
menu
(
sname varchar(20),
size varchar (20),
price decimal(4,2),
primary key (sname, size),
foreign key (sname) references sandwich(sname)
);
orders
(
phone char(10),
sname varchar(20),
size varchar(20),
o_time datetime,
quantity int,
status varchar(10),
primary key (phone, sname, size, o_time),
foreign key (phone) references customer(phone),
foreign key (sname, size) references menu(sname, size)
)
Short Answer:
Your problem has to do with this line:
<td><input type="radio" name="sandwich" value="'.$count1.'"></td>
You should change $count1 to the variable that contains the sandwich name. For reasons described below, you shouldn't do this (but it'll probably work, as long as you treat the strings appropriately).
This field will become $_POST['sandwich'] and will have whatever value was selected.
$sname = $_POST['sandwich'];
$query = "INSERT INTO orders (sname, ...) VALUES ('{$sname}', ...)";
(of course, you should be using prepared statements and sanitizing the input appropriately).
Long Answer
- Your table syntax is all over the place. You can't have the same id for multiple elements, there is no name attribute for <td>, and <th> should be nested inside <thead>, not a <tr>. I've updated it to give the cells a class name instead, which will let you apply consistent styling with CSS (instead of ugly inline statements), and access the data conveniently through javascript if you ever need to do so.
I'm not entirely sure what's going on with this query:
SELECT m.sname,m.size,m.price
FROM sandwich s
INNER JOIN menu m
WHERE s.sname = m.sname
But it looks like your problem stems from lack of a unique identifier for each sandwich. The names are okay, but typically it's preferable to use a unique ID to associate with each sandwich. Use mysql's auto_increment to generate this automatically.
CREATE TABLE sandwiches (
sid int(5) not null auto_increment,
primary key(sid),
sname varchar(255)....
This way, you can pass the ID as a form value and positively associate each record with that ID. It looks like it's what you're trying to do with $counter1, but it just takes that extra step out.
<input type="radio" name="sandwich_id" value="<?=$sid;?>" id="sid_<?=$id;?>">
<label for="<?=$sid;?>"><?=$sandwich_name;?></label>
Once all those radio buttons are selected, you'd do something like:
<?php
$sid = (int)$_POST['sandwich_id'];
$phone = preg_replace("/[^0-9]/",'', $_POST['phone']; // Strips all non-numeric chars out
$query = "INSERT INTO orders (sandwich_id, customers_phone) VALUES ({$sid}, '{$phone}')";
Of course, you should use the prepared statements - that's just an example. By inserting the sandwich ID in the orders table, you can JOIN to the sandwiches table to generate receipts or order screens.
I have two MySQL tables that I created like this:
CREATE TABLE book(id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY, title VARCHAR(256),
book_id INT, author VARCHAR(128), year INT, httplink VARCHAR(256)) ENGINE MyISAM;
and
CREATE TABLE excerpt(id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY, book_id INT, excerpt_title
VARCHAR(256), year INT, measure VARCHAR(256), page VARCHAR(128)) ENGINE MyISAM;
So there's a table of books...and a table of excerpts from each book...they're linked by book_id. Each unique book has a book_id...and every excerpt from that book has the same book_id.
Now, I have a php form that allows to users to edit a entry after they've searched for it:
<p>Edit Record</p>
<form method="post">
<p>Title:
<input type="text" name="title" value="$n"></p>
<p>Author:
<input type="text" name="author" value="$e"></p>
<p>Year:
<input type="integer" name="year" value="$p"></p>
<p>Mirlyn link:
<input type="text" name="link" value="$l"></p>
<p>Excerpt name:
<input type="text" name="excerpt" value="$ex"></p>
<p>Page numbers
<input type="text" name="page" value="$s"></p>
<input type="hidden" name="id" value="$id">
<p><input type="submit" value="Update"/>
When the user hits the edit button next to the link, the following fields autopopulate with the record the user chose to edit: title, author, year.
If the user does not change the title, but changes (or doesn't change) the other fields, what is the correct MySQL statement to update the record? I believe I'd only have to update the 'excerpt' table.
BUT...if the user edits title...how do I manage that? I'd have to check if the title exists in the 'book' table. If it does, I'd have to change the book_id for the excerpt. If it doesn't, I'd have to add it to the 'book' table with a unique book_id and then change the record appropriately in the excerpt table. Help?
Thanks!