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.
Related
I'm developing a simple student information system, for now i have 300 students and six subjects, so when i want to add marks obtained by each student i use html form and php script to add those marks, for each student i add marks for six subjects that is one subject at a time, so i'm asking if there is the way where by php can allow me retrieve one student and add all the marks for the six subjects at once and then take another and so on. Also i want to calculate total marks for each student and store those total in another table with respective student id so that i can know who is the first student and who is the last by using that total marks of each student.
here is the way i'm doing right now
<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<html>
<body>
<div>
<div>
<form action="connmarks.php" method="post">
<table>
<tr><td colspan="6"> </td></tr>
<tr><td><p>Adding Student Results</p></td></tr>
<tr>
<td width="9%">Student Code<?php echo $mstudentcode;?></td>
<td width="17%"><input name="student_code" type="text" size="30" value="<?php echo $studentcode;?>" /></td></tr>
<tr>
<td width="10%">Subject Code<?php echo $msubjectcode;?></td>
<td width="18%"><input name="subject_code" type="text" size="30" value="<?php echo $subject_code;?>"/></td></tr>
<tr>
<td width="12%">Marks<?php echo $mmark;?></td>
<td width="34%"><input name="mark" type="text" size="30" value="<?php echo $mark;?>"/></td>
</tr>
<td> </td>
<td>
</td>
</tr>
<tr><td colspan="4"> </td></tr>
<tr><td colspan="6"> </td></tr>
<tr>
<td> </td><td colspan="6"><input type="submit" name="save" value="Add Marks" /></td>
</tr>
<tr><td colspan="6"><?php echo $sms1.$sms.$sms2;?></td></tr>
</table>
</form>
</div>
<div id="footer">Copyright <?php echo date("Y", time()); ?></div>
</div>
</body>
</html>
<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<?php
session_start();
if(isset($_POST['save']))
{
// validating student code
if(empty($_POST['student_code']))
{
$mstudentcode='<font color="red"><b>**</b></font>';
}
else
{
$student_code=$_POST['student_code'];
}
// validation for kiswahili subject
if(empty($_POST['subject_code']))
{
$msubjectcode='<font color="red"><b>**</b></font>';
}
else
{
$subject_code=$_POST['subject_code'];
}
// validating english subject
if(empty($_POST['mark']))
{
$mmark='<font color="red"><b>**</b></font>';
}
else
{
$mark=$_POST['mark'];
}
// checking if there is any error message, if no error proceed, if there is error, display the error
// Then exit the script and redirect at the same page
if($mstudentcode||$msubjectcode||$mmark||$sms)
{
$sms1='<font color="red"><b>Error found,please check **</b></font><br/>';
include 'addmarks.php';
exit;
}
// if there is no error include connection file
if($student_code&&$subject_code&&$mark)
{
// include 'mysqli_connect.php';
require_once ('../../mysqli_connect.php');
$addmarks= "insert into result(student_code,subject_code,mark) values ('".$student_code."','".$subject_code."','".$mark."')";
$k = mysqli_query($dbc, $addmarks);
if ($k)
{
$sms1='<font color="green"><b>Student Marks Submitted Successfully</b></font><br/>';
include 'addmarks.php';
exit;
}
else
{
$sms1='<font color="red"><b>Failed To Add Student Marks</b></font><br/>';
include 'addmarks.php';
exit;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<!-- Displays all users in database in a select option -->
<select name="students">
<option>Student 1</option>
<option>Student 2</option>
<?php
//This code below is what you will need to use for yours to pull values out of the database(changing the values to suit yours obviously).
// $query = "SELECT * FROM students ORDER BY student_name ASC";
// $result = mysqli_query($conn,"$query");
// while($row = mysqli_fetch_assoc($result)){
// echo "<option>" . $row['student_name'] . "<br></option>";
// }
?>
</select><br>
<!-- All the different input fields for maths, english and science -->
<input type="text" name="eng_grade" value="" placeholder="Enter English Grade"><br>
<input type="text" name="math_grade" value="" placeholder="Enter Maths Grade"><br>
<input type="text" name="science_grade" value="" placeholder="Enter Science Grade"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
//If submit is pressed
if (isset($_POST['submit'])) {
//this gets the value of the student name from the select box and stores it as $student
$student = $_POST['students'];
//These gets the values stored in the inputs above and store them in the 3 vairables
$english = $_POST['eng_grade'];
$maths = $_POST['math_grade'];
$science = $_POST['science_grade'];
//this is a mysql query that updates the data with whatever you put into the database(to add to existing tables you will have to dig abit deeper and create your
//database with all the correct fields!
$query = "UPDATE students SET maths_grade = '$maths', $english_grade = '$english', science_grade = '$science' WHERE student_name = '$student'";
$update = mysqli_query($conn, "$query"); //<-- this inserts the values into the database, changing the current #null value (null means nothing is in it)
}
?>
</body>
</html>
Create 2 tables, one for student and other for marks.
In one table, just insert student name and id(unique), and in other table student all 6 subject marks i.e. 6 columns for 6 sub, 1 for student id, and other one as auto increment id column.
So using that student id you can retrieve all the subject marks of a particular student.
Edit: Just noticed this question is 3 years old w00t!?
Drafting tables would be something like
student table:
id primarykey integer
name notnullable nvarchar(255)
subject table
id primarykey integer
name notnullable nvarchar(255)
student_subject table
id primarykey integer
student_id foreignkey notnullable unique integer
subject_id foreignkey notnullable unique integer
mark notnullable double(2,2)
E.g. Select the marks of a subject
Select student.name, subject.name, subject_student.mark from subject_student
inner join student on student.id = subject_student.student_id
inner join subjecton subject.id = subject_student.subject_id
where student_id = X; // X is the id of the student you want
Any calculation should be based on query, you don't want to store results in the database. You want data in the database and since it's volatil data (can be changed anytime), it's easier and faster to calculate whenever required. Sum, GroupBy, there are a ton of basic sql keywords that can help you. student_subject table is the table where it combines that Many students in Many subjects with a certain mark. If you want to save a student's mark, you just Insert into this table the id's and the mark value.
Since it's a school project, this should be suffice for you to work it out.
In the future, take a look at prepared statements
http://php.net/manual/en/book.pdo.php
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 have three tables :
Table 1 is called "card" . The fields that are important are:
"state_id" - This table has 3 values (1,2,3)
"associated_driver" - called "referred_as" on driver table
"referred_as" - called "associated_card" on driver table
Table 2 is called "driver". The fields that are important are:
"ID" - The auto incremented value of the table
"associated_card" - Has a value , normally some number e.g 123555
"referred_as" - The name of the driver () called "associated_driver" on card table
Forgot to add this table :
Table 3is called "card_driver". The fields that are important are:
"driver_id" - The id from the driver table that links to the card
"card_id" - The id from the card table that links to the driver
What i want to happen :
When a user enters their id from the driver table, it will compare a field that both tables have i.e the 'associated card' field. From there the original query from (bellow) will take over, although that needs to be modified as well.
I don't really know how to do sql queries .
I need to change this part :
$sql ="SELECT * FROM card WHERE id = '$id'" ;
Thanks
Original Code :
$id = $_POST['id'];
$sql ="SELECT * FROM card WHERE id = '$id'" ;
mysql_select_db('damp');
$result = mysql_query( $sql, $conn );
$row = mysql_fetch_assoc($result);
switch($row['state_id'])
{
case "1":
echo "<strong><font color=\"green\">Authorisation Granted!</font></strong>";
break;
case "2":
echo "<strong><font color=\"red\">Your card has expired and authorisation is denied</font></strong>";
break;
case "3":
echo "<strong><font color=\"red\">Your card has been cancelled and authorisation is denied</font></strong>";
break;
default:
echo "<strong><font color=\"red\">The Card ID does not exist</font></strong>";
}
//echo $_GET['here']; // Prints the name of the page content
//echo $class_obj_id; // Prints the id number of the selected row
?>
<?php } ?>
<div id="auth">
<form method="post" action="<?php $_PHP_SELF ?>">
<table id="auth" width="150" >
<tr>
<td colspan="2"><h2>Check Card Authorisation</h2></td>
</tr>
<tr>
<td width="50" align="center">ID</td>
<td><input name="id" type="text" id="id" value="" /></td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="check" type="submit" id="check" value="Check">
</td>
</tr>
</table>
</form>
</div>
$sql ="SELECT * FROM card c JOIN driver d ON c.referred_as=d.referred_as WHERE d.ID='$id'";
$sql = "SELECT * FROM driver INNER JOIN card ON driver.associated_card = card.associated_card WHERE id = '$id'";
Join the driver and card tables where the associated card id matches up, then you can just call your $row['state_id'] from this
I have 2 tables: reservations_client and tables_clients
The reservation_client has 3 fields:
id, name_client, date, table
The table_clients has 2 fields:
id, name_table
When a client wants to reserve they put his name, the date, and choose a table, but there is a problem: 2 clients cant use the same table.
What I need is it to only insert data into the database when the date is different. If the date is the same (i.e., someone's already using the table), it should send an error;
I tried using an unique key but it sends me an error even if the date is different.
My PHP code:
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO reservations_clients (user, number_person, table, date) VALUES (%s, %s, %s, %s)",
GetSQLValueString($_POST['user'], "text"),
GetSQLValueString($_POST['number_person'], "int"),
GetSQLValueString($_POST['table'], "int"),
GetSQLValueString($_POST['date'], "text"),
mysql_select_db($database_conexionbdd, $conexionbdd);
$Result1 = mysql_query($insertSQL, $conexionbdd) or die(mysql_error());
mysql_select_db($database_conexionbdd, $conexionbdd);
$query_table = "SELECT * FROM tables";
$table = mysql_query($query_table, $conexionbdd) or die(mysql_error());
$row_table = mysql_fetch_assoc($table);
$totalRows_tables = mysql_num_rows($table);
And the form clients fill out:
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table align="center">
<tr valign="baseline">
<td nowrap align="right">Number_person:</td>
<td><input type="text" name="Number of persons" value="" size="32"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">table:</td>
<td><select name="numero_mesa">
<?php
do {
?>
<option value="<?php echo $row_table['idtable']?>" <?php if (!(strcmp($row_tables['idtable'], $row_table['idtable']))) {echo "SELECTED";} ?>><?php echo $row_table['name_table']?></option>
<?php
} while ($row_table = mysql_fetch_assoc($table));
?>
</select></td>
<tr>
<tr valign="baseline">
<td nowrap align="right">date:</td>
<td><input type="text" name="fecha" size="32" id="datepicker" /></td>
</tr>
<tr>
<td nowrap align="right"> </td>
<td><input type="submit" value="Enviar"></td>
</tr>
</table>
<input type="hidden" name="user" value="<?php echo $row_user['user']; ?>">
<input type="hidden" name="MM_insert" value="form1">
</form>
<p> </p>
I'm confused about how you're using your database setup; seems the only issue is with the reservation_client table.
It looks like when you set the unique constraint, you only included table as a unique key instead of both table and date. One sets a unique key on one column, one sets it on the combination of columns. This combination as opposed to one column is extremely important. To fix this, go to the database you're working in, remove any unique keys in the reservation_client and :
ALTER TABLE `reservation_client` ADD UNIQUE (`table`, `date`);
Essentially what this does is say that in order to insert an entry, there can't be any row that has the same table and date values. It essentially sets a unique combination instead of a unique key. You're going to want to make sure you handle the error that's returned, whether that means catching it within your PHP or setting some kind of ON DUPLICATE KEY action in your query. I'm not sure the exact circumstances, so you'll have to play around with that.
You can just query first if the table and date is present in the database.
Select * From reservation_clients Where Date = $date And table = $table
if the result is empty then you can proceed to insert the data.
Why don't you use where condition like this
$q_num = mysql_query('select * from reservations_client where date = "the date the client chose" and table = "the table the client chose"');
$r_num = mysql_num_rows($q_num);
and make a condition if $r_num is > 0 then send error, else insert data
if you are using php, get the date to the server side. Then, if you need second by second accuracy you can just compare those as strings
if($dateFromDB==date("Y-m-d H:i:s"))
{
// go ahead and do your business
}
if you are looking to have 2 different days however, you can use the following
$today=explode(" ",date("Y-m-d H:i:s"));
$today=$today[0];
$dateFromDB=explode(" ",$dateFromDB);
$dateFromDB=$dateFromDB[0];
if($dateFromDB==$today)
{
// go ahead and do your business
}
See php code below:
I have built the html form and the dropdown menu in the html form using <<<_END _END tags in php. also I added the following php code at the top of the htmlform that I had believed would allow me to enter a student name, student ID and select a course from the dropdown menu in the form. once those 3 values were entered in the form, the info should be added to the table enrolment in my mysql database. but i have had no luck figuring this out...
//connect3.php--login information to my mysql database//
<?php
define ('HOST', 'localhost');
define ('USER', 'root');
define ('PASS', '******');
?>
// html form and connection code//
<?php
include 'connect3.php';
$link = mysql_connect (HOST, USER, PASS) or die(mysql_error());
mysql_select_db ('milleruniversity', $link);
// Added mysql_real_escape() to protect against SQL-Injection
$code = mysql_real_escape( $_POST['code'] );
$uid = mysql_real_escape( $_POST['uid'] );
$studentname = mysql_real_escape( $_POST['studentname'] );
// Insert a row of information into the table "enrolment"
$query = "INSERT INTO enrolment (code, uid, studentname) VALUES('$code', '$uid', '$studentname')";
if(mysql_query($query)){
echo "inserted";}
else{
echo "fail";}
echo <<<_END
<table border='1'cellpadding="10">
<tr>
<td>
<h4>Miller University Registration Form</h4>
<p>Please Register as a new Student or current student for the following courses below.</p>
</td>
</tr>
<form action="draft5.php" method="post"><pre>
<tr>
<td>
Student Name <input type="text" name="studentname" maxlength="30"/>
</td>
</tr>
<tr>
<td>
Student ID <input type="text" name="uid" maxlength="11"/>
</tr>
</td>
<tr>
<td>
Select a course <select name="code" size="1">
<option value="DC-00040">Digital Communications</option>
<option value="VC-00030">Visual Culture</option>
<option value="WP-00080">World Politics</option>
</select>
</tr>
</td>
<tr>
<td>
<input type="submit" value="Submit to Register" />
</tr>
</td>
</pre></form>
</table>
_END;
mysql_close($link);
?>
It seems to me that you use this draft5.php page to display the form and to insert a row in your database. In that case the problem may come from the missing isset() around the $_POST data. (the first time you load the page the POST values are not set).
You could use this code :
if( (isset($_POST['code']) AND (isset($_POST['uid']) AND (isset($_POST['studentname']){
//process the data base treatment and display an acknoledgment of the insert
// Check if these new code, uid and studentname respect the primary key constraint
}
else{
// Display your form
}
You could also consider using backticks ` around the names of your tables and colomns.
If you want to prevent the same student to register twice in the same course you need to add primary keys in your tables. But this is not enough, indeed if you perform the insert request with a contraint violation on the primary key MySql will return an error. What you can do is check if the key exists prior to the insert request, if yes notify the user, if no perform the insert request.