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
}
Related
I am trying to make a rating system using multi-select dynamically generated from rating text on the database. The final result should look like this: Rating Service but now I need to save selected option after save is clicked.
in the database there is two table the first one have 2 column the first is the id and the second is the text of the rate
the second table is where i wont to save the selection that the user chose using php
page code
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>About</th>
<th>Provider</th>
<th>Rating</th>
</tr>
</thead>
<?php
$query_rate_text = "SELECT * FROM rateing_text";
$selecting_rates = mysqli_query($con,$query_rate_text);
$i = 0;
while($row_rate = mysqli_fetch_assoc($selecting_rates)){
$rate_id= $row_rate['rate_id'];
$rate_text= $row_rate['rate_text'];
$i++
?>
<form name="rating_form">
<tbody>
<tr>
<td><?php echo $i ?></td>
<td> <?php echo $rate_text ?></td>
<td><span class="badge badge-danger">
<?php echo $provider_name ?></span></td>
<td>
<select name="p<?php echo $i ?>">
<option value="1">Very Bad</option>
<option value="2">Bad</option>
<option value="3">Good</option>
<option value="4">Very Good</option>
<option value="5">Excelent</option>
</select>
</td>
</tr>
</tbody>
<?php } ?>
<tfoot>
<tr>
<td colspan="3"><button type="submit" name="save_rate"> Save </button> </td>
</tr>
</tfoot>
`enter code here`
</form>
</table>
How can I get info form the select and save them to the database ?
Radio button is much better than <select>.
The rate id and selected value must be passed as a key=>value
You need to stop using Word Press syntax.
Learn to use Herdoc Syntax
Using SELECT * is a poor standard practice.
Fetch array and assign values with a list
This code is untested.
<?php
echo <<<EOT
<form name="rating_form" action="#">
<table class="table table-striped">
<tr><th>#</th><th>About</th><th>Provider</th><th>Rating</th></tr>
EOT;
$query_rate_text = "SELECT `rate_id`,`rate_text` FROM rateing_text WHERE 1 ORDER BY `rate_id`";
$selecting_rates = mysqli_query($con,$query_rate_text);
$i = 0;
while(list($rate_id, $rate_text) = mysqli_fetch_array($selecting_rates)){
$i++;
echo "<tr><td>$i</td><td>$rate_text</td><td>$provider_name</td><td>5<input type="radio" name=\"$rate_id\" value=\"5\" /> 4<input type="radio" name=\"$rate_id\" value=\"4\" /> 3<input type="radio" name=\"$rate_id\" value=\"3\" /> 2<input type="radio" name=\"$rate_id\" value=\"2\" /> 1<input type="radio" name=\"$rate_id\" value=\"1\" /></td></tr>\n";
}
echo '</table><button type="submit" name="save_rate"> Save </button></form>';
?>
UPDATE
thank you very much that's helped to understand new way's,one more
thing how can i get the data out from this radio 5 buttons to insert
them to the database to the table named rating which have let's say 3
column id and provider name and the rate it self , again thank you for
helping
The radio input type is a more user friendly way then the cumbersome select.
The way I setup the radio buttons with the rate_id as the "name" so the selected "value" is passed as a key=>value pair to the form's action script.
Your select name should also contain the rate_id
The problem your code has is, the action script will receive will receive keys of sequential numbers that have no meaning and difficult to know how many were posted by the form.
To pass the provide name add a hidden input type:
<input type="hidden" name="provider" value="$provider_name" />
And I would remove the provider from the table td.
Not knowing your rate_id convention I could not improve the radio button naming convention.
The way I would do it is when passing key=>value pairs I would begin the key "name" with a unique character where no other "name" in the form would start with that character.
For example if the rate_id is a numeric value I may prepend a 'k' to the numeric key value.
So instead of
name=\"$rate_id\"
I would use
name=\"k$rate_id\"
The in the receiving action script I would get the key=>values like this
$provider_name = $_GET['provider']
foreach($_GET as $key => $value)){
if(substr($key,0,1) == 'k'){
$rate_id = intval(substr($key,1));
$rating = intval($value);
$sql = "INSERT INTO `table` (`rate_id`, `provider_name`, `rating`) VALUES ($rate_id, '$provider_name', $rating)";
mysqli_query($link,$sql);
}
}
if i inserted rows and i want to update one column value of this rows inserted in this immediately process without update this one column value of older rows inserted in previous process
you can see my code and understand more clearly:
<?php
session_start(); ?>
<form action="" method="post" name="data_table">
<tbody >
<?php
require_once("dbconfig.php");
error_reporting(0);
$id=$_POST['id'];
$class=$_POST['class'];
$d = new DateTime('now', new DateTimeZone('Asia/Baghdad'));
$date=$d->format('Y-m-d H:i:s');
$q="select * from students WHERE class='$class'";
$qq=mysql_query($q)
or die(mysql_error());
echo "<table border='2'>
<tr>
<th>الأسم</th>
<th>الحضور</th>
</tr><tr>";
while($row=mysql_fetch_array($qq)){
?>
<input type="hidden" name="class" value="<?php echo $row['class']; ?>" >
<td><input type="checkbox" value="<?php echo $row['id']; ?>" name="id[]" ></td>
<td><b><?php echo $row['username']; ?></td>
<tr>
<?php } ?>
</table>
<?php if (isset($_POST['submit']))
{if(empty($id) || $id==0)
{ echo " please check ";
}
else
{
$impid=implode(", ",$id);
$qdel=mysql_query("INSERT INTO attendees SELECT * FROM `students` WHERE class='$class'");
$qdel=mysql_query("UPDATE attendees set datetime='$date'");
if (isset($qdel)){
echo "<h2> done </h2>";}
}
} ?>
</tbody>
</form>
the problem is the update query updating the value of datetime column in all rows inserted now and before now so my question is how can i make the update query work with each inserting process as separated from previous one
anyone can help please ? thanks
Doing an update right after an insert is inefficient. It also isn't a good idea to rely on the columns of two different tables to always match.
You can insert a static string in your query.
INSERT INTO attendees (column1, column2, column3, datetime)
SELECT column1, column2, column3, '$date' FROM students WHERE class='$class'
However, this breaks a normalization standards of RDBMS. The best way to do this is not duplicate data into attendees, but reference a foreign key to the student ID in attendees. You shouldn't have to update two tables to updates a student's information. I suggest you read up on database normalization before designing a database.
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 seem to have an issue inserting the post values into my database, and i don't see the error in the coding. I've been looking at it for a while now and to me everything looks right, however when i use the form and submit the data the page reload but no data get inserted into the database.
It would be much appreciated if someone could help me identify the error in the coding.
If you have any questions feel free to ask!
Kind regards Jim
FORM
<?php
//Show the form if the user is a Admin
if(isset($_SESSION['username'])){
$username == $_SESSION['username'];
$results = $mysqli->query("SELECT authority FROM users WHERE username='$username' LIMIT 1");
while($row = $results->fetch_object()){
$aut = $row->authority;
}
}
if($aut == 1){
?>
<form action="index.php" method="post">
<table>
<tr>
<td> Title: </td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td valign="top"> News: </td>
<td><textarea name="information"></textarea></td>
</tr>
<tr>
<td> <input type="hidden" value="news"> </td>
<td><input type="submit"></td>
</tr>
</table> <hr>
</form>
MYSQLI
<?php
}
//Insert into the database
if(isset($_POST['news'])){
$title = $_POST['title'];
$information = $_POST['information'];
$mysqli->query("INSERT INTO `news` (`title`, `information`) VALUES ( '".$title."', '".$information."')");
}
<input type="hidden" value="news"> should be <input type="hidden" name="news">
That's why isset($_POST['news']) will never be true.
Beside that silly typo problem your code suffers from two real disasters.
You have no error reporting, which renders you helpless against such silly mistakes
You are adding your data directly into query, while ought to use placeholders for that.
I am not sure what was intended with the backticks and periods in your original query. In my limited experience my queries take the form of:
$mysqli->query("INSERT INTO news(title, information) VALUES ('$title', '$information')");
I would say that priority #1 is getting some debugging information in the form of return values for your php functions or access to php error logs.
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.