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
Related
I have created a database to store results in a competition along witha php generated web-page that lists all the competitors followed by a textbox in which to record their score.
When I press the submit button I want it to update all of the rows in the table.
I'm new to php and mySQL, I can do it for one of them at a time but I don't want them to have to press 30+ individual submit buttons to handle each row.
The following code generates the form:
<?php
$field_event_id = $sports_day_id = "";
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )
$field_event_id = $_POST["field_event"];
$sports_day_id = $_POST["sportsday"];
$query = "SELECT * FROM student JOIN participants ON student.student_ID = participants.student_ID WHERE `Field_Event_ID`= $field_event_id";
$result = mysqli_query( $dbc, $query ) ;
echo '<body>';
if ( mysqli_num_rows( $result ) > 0 )
{
echo'<header> <h1> Please enter the results below </h1> </header>';
echo '<table align="center" border="1" cellpadding="10px" bgcolor="#DCF8FE">
<tr>
<th>Forename</th>
<th>Surname</th>
<th>Year Group</th>
<th>Score</th>
</tr>
<tr>';
while ( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ))
{
echo '<form action="Add_Scores_Field_Event_Register.php" method="post">
<td> <strong>' . $row['Forename'] .'</strong><br> </td>
<td> <strong>' . $row['Surname'] .'</strong><br> </td>
<td> <strong>' . $row['Year_Group'] .'</strong><br> </td>
<td> <strong> <input type="text" name="notes_input"> </strong><br> </td>
</tr>
</form>';
}
echo '</table>';
echo '<p><input type="submit" value="Enter scores" ></p>';
}
else
{
echo '<p>There are currently no students in this event.</p>' ;
}
{
# Close database connection.
mysqli_close( $dbc ) ;
}
# close body section.
echo '</body>';
# close HTML section.
echo '</html>';
mysqli_close($dbc);
?>
According to this post you can set the name attribute of elements to an array.
<input type="text" name="inputs[]" value="bob">
<input type="text" name="inputs[]" value="jim">
If you submit this through a form. You should be able to access the values like:
$_POST["inputs"][0]; // bob
$_POST["inputs"][1]; // jim
So, if you output your information inside a form and setup the name attributes for the scores properly. When you submit the form, you should be able to grab all the scores (editted or not) and update your database with the values.
You will have to keep track of which record in the database to change.
The code I provided is untested; however, according to the linked post, it should work.
Don't forget to learn about prepared statements as Alex Howansky had commented. These are really important.
If you try this out, you would need to move your form tags to wrap the entire table; instead of, particular rows.
EDIT:
With a little more though I see 2 solutions:
Place the student ID inside a hidden tag and use the name attribute to send it along with the other data.
<input type="hidden" name="studentIds[]" value="<place student id here>">
I would place the input tag in the td for your forename; because, it is the first td and one of the tds that uniquely represents the row.
OR
Use the Student ID as the index for your index and the score as the value.
<input type="text" name="notes_input[<place student id here>]">
You can then iterate through notes_input and get the key and value:
foreach ($array as $key => $value) {
//code
}
See documentation for more information.
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'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 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.