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.
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 have 2 tables, one with data and other is blank in same database.
a)- Tables "cusrec" is main and contains data in it.
b)- Tables "order" is empty and I want to insert the data in it.
I tried to fetch data from table "cusrec" and insert it into "order", when I echo, it shows the data of table "cusrec" but it is not inserting into table "order". Both tables are in same database.
Code is:
<?php
mysql_connect("localhost","root","");
mysql_select_db('dobhighat');
if(isset($_GET['search'])){
$srch = $_GET['srch'];
$que=mysql_query("select * from cusrec where custid='$srch' OR mobile='$srch'");
$ftch=mysql_fetch_array($que);
$scustid=$ftch['custid'];
$sname=$ftch['name'];
$smobile=$ftch['mobile'];
$totcloth=$ftch['clothpackage'];
if(isset($_POST['confirm']))
{
$ordernum=$_REQUEST['ordernum'];
$orderdate=date('d/m/y');
$ordercloth=$_REQUEST['ordercloth'];
$clothrem=$totcloth-$ordercloth;
$abc=mysql_query("insert into order(custid,name,mobile,totcloth,orderno,orderdate,ordercloth,clothrem)values('$scustid','$sname','$smobile','$totcloth','$ordernum','$orderdate','$ordercloth','$clothrem')");
}
}
?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<?php $orddate=date('d/m/y'); ?>
<form name="form 1" action="" method="get">
<div align="right"><input type="text" name="srch" placeholder="Search by Id or Mobile" size="25">
<input type="submit" name="search" value="Search"></div>
</form>
<form name="form2" action="" method="post">
<table>
<tr>
<td width="103">Order Date</td>
<td width="94">Customer Id</td>
<td width="53">Name</td>
<td width="71">Mobile</td>
<td width="144">Order No.</td>
<td width="144">No.of Clothes</td>
</tr>
<tr>
<td><?php echo $orddate; ?></td>
<td><?php echo #$ftch['custid']; ?></td>
<td><?php echo #$ftch['name']; ?></td>
<td><?php echo #$ftch['lname']; ?></td>
<td><?php echo #$ftch['mobile']; ?></td>
<td><input type="text" name="ordernum" required></td>
<td><input type="text" name="ordercloth" required></td>
</tr>
<tr><td colspan="8"><center><input type="submit" name="confirm" value="Confirm"></center></td></tr>
</table>
</form>
</body>
</html>
Help is needed
Forget all I said about the forms and the structure of the document (although it could be useful eventually as I don't know how reliable is that GET and POST).
I am a dodo and just realized that your table name is order. ORDER is a reserved keyword in SQL and it's the reason why your SQL statement is incorrect! Just put the name between ` and it will work:
$abc=mysql_query("insert into `order`(custid,name,mobile,totcloth,orderno,orderdate,ordercloth,clothrem)values('$scustid','$sname','$smobile','$totcloth','$ordernum','$orderdate','$ordercloth','$clothrem')");
Or you may want (if possible) to rename the table in order to avoid confusion and future problems.
This doesn't mean that the code is perfect. You should still look at the recommendations by the other users and the list below, and improve it. Specially the security concerns.
Once you fix that, the insert will work; but there are still many things that you need to fix:
You should not use mysql functions and move to mysqli or PDO.
You should sanitize all the values that go to the database or to the page:
Your code is subject to SQL injection (see comments in question).
Your code is subject to XSS (see comments in question).
The doctype in your page is incorrect (if you want html5, it should be <!doctype html> and not <!doctype>.
Names and IDs must not have white spaces in them (read this for name and id notation: http://www.w3.org/TR/html401/types.html#type-name)
As stated in other answers, the SQL statement could be improved. The solution that you have may work fine (I don't find any apparent error) but it is not ideal and may present performance problems and other type of problems (e.g.: if two different users have the same phone number).
And there are probably more things that I didn't notice as I just looked quickly through the code.
Have you thought of doing an insert from select? Something like...
INSERT INTO ORDER
( custid, name, mobile, otherFields, etc... )
SELECT same, ordered, fields, as, theInsert
from custrec where custid='$srch' OR mobile='$srch'
The only issue I see with your select where clause is that you could be getting multiple customers via the OR mobile='%srch' and cause duplicate orders.
You can do it directly from SQL
INSERT INTO order
( custid,
name,
mobile,
totcloth,
orderno,
orderdate,
ordercloth,
clothrem)
SELECT
custid,
name,
mobile,
totcloth,
orderno,
orderdate,
ordercloth,
clothrem
FROM cusrec
WHERE custid='$srch' OR mobile='$srch'"
;
You just need to match the column with from table to to table
I think to insert and fetch the same data we can do it by using the below-mentioned code for PHP MYSQLI.
$id=trim($_POST['id']);
$email=trim($_POST['email'];
$env_name=trim($_POST['env_name'];
$sql="INSERT INTO integration (id,email,env_name) VALUES ($id,$email'$envName')";
if(mysqli_query($conn,$sql)){
$selectSql="SELECT id,email,env_name from integration WHERE id=$id and email='$email'";
$result=mysqli_query($conn,$selectSql){
if($result){
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
return $row;
}
}
}
Hello i'm a newbie in PHP language. So I hope u guys can be simple with me. I need to create like a attendance system for a meeting. Now I was stuck at one part. I need to add a staff from a department for every created meeting event. The staff name was already appear when I click from dropdown menu for every department that retrieve from database. Now I tried to select from the checkbox staff that I want to add with the meeting id. But nothing is happened when I click the submit button after checked the staff name. I want to add to a new table with the meeting id. display.php is code I create to appear the staffname and to check the checkbox and retrieve the record from user table . The checkbox.php is for insert the checked checkbox to a table meetingstaff. Please anyone help me..
Here I attached my PHP code
display.php
<label>Reference No:</label>
<label id="attach"><?php echo $_GET["refno"]; ?></label>
<form action="display.php?refno=<?php echo $_GET["refno"]; ?>" method="post">
<?php do { ?>
<form action="checkbox.php?refno=<?php echo $_GET["refno"]; ?>" method="post">
<tr >
<td><div align="center"><input name="chkl[]" type="checkbox" id="checkbox[]" value="<? echo $row_Recordset4['staffname']; ?>"></td>
<td><div align="center"><?php echo $row_Recordset4['staffname']; ?></div></td>
<td><div align="center"><?php echo $row_Recordset4['staffno']; ?></div></td>
</div></td>
</tr>
<?php } while ($row_Recordset4 = mysql_fetch_assoc($Recordset4));?>
checkbox.php
<label>Reference No:</label>
<label id="attach"><?php echo $_GET["refno"]; ?></label>
<?php
$checkbox1 = $_POST['chkl'];
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($checkbox1);$i++) {
$query="INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."')";
mysql_query($query) or die (mysql_error());
}
echo "Record is inserted";
}
?>
You need to INSERT a second parameter, or remove , staffno from the first part of the INSERT statement. You are passing just one value, but instructing for two columns.
So change your:
INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."')
to either
INSERT INTO meetingstaff (staffname) VALUES ('".$checkbox1[$i]."')
or perhaps
INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."', ".$i.")
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.