I'm new to this site, and I need some help with my record system. I need to insert the grades of the students into the grades table, which has the columns: gradeid (PK, auto_increment), studentid (FK), courseid (FK), midterm, endterm, final, remark.
The studentid (FK) gets the number from the studentid (PK) of addrec table.
The courseid (FK) gets the number from the courseid (PK) of course table.
Here are the codes that I have experimented (for the umpteenth time) but still got no results:
<?php
$host="localhost";
$username="root";
$password="";
$db_name="studentrec";
$studentid = $_GET['id'];
$sql1="SELECT studentid FROM addrec WHERE studentid='$studentid'";
if(mysql_query($sql1))
{
$courseid = $_GET['courseid'];
$sql2 = "SELECT courseid FROM course WHERE courseid='$courseid'";
if (mysql_query ($sql2))
{
$sql3="INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`, remark`) VALUES ('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]' )";
}
if (mysql_query($sql3))
{
// Success
}
else
{
die('Error on query 2: ' . mysql_error($con));
}
}
?>
There are no errors whenever I hit the Submit button, but the data I put in the text boxes won't insert into the grades table. Help, please? Or suggestions? I'm still studying stuff about PHP. Thank you. :)
youre not connecting to the mySQL : http://www.php.net/manual/en/function.mysql-connect.php
also you might notice the big red box on php.net, you should move to PDO or MySQLi.
Query contains error. Try this
INSERT INTO grades(studentid,courseid,midterm,endterm,final,remark) VALUES ('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]' );
do your db connection first than select db and than
try to replace
$sql3="INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`, remark`) VALUES ('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]' )";
with
$sql3="INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`, remark`) VALUES('$studentid','$courseid','".$_POST['midterm']."','".$_POST['endterm']."','".$_POST['final']."','".$_POST['remark']."' )";
You actual query is like
INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`,remark`)
VALUES
('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]' );
You need to put opening ` (tild) before column remark, so your query will looks like
INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`,`remark`)
VALUES
('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]');
Related
I have 4 mySQL tables with the following entries:
user
-user_id PK,AI
-user_name
-user_mobil
-user_passw
-user_email
bookingdetails
-booking_id PK,AI
-booking_date
-booking_time
-person_number
booking
-booking-_id FK
-restaurant_id CK
-user_id CK
restaurant
-restaurant_id PK
-restaurant_name
-restaurant_address
-restaurant_description
I would like to make a booking, I insert all the bookingdetails data, which gives me a AI booking_id, and after I would like to make my booking table and insert the restaurant_id and the user_id With the same booking_id which was given by the bookingdetails table.
I made the following code for achieve that in php on a localserver:
$booking_date=$_POST["booking_date"];
$booking_time=$_POST["booking_time"];
$number_of_place=$_POST["number_of_place"];
$customer_id=$_POST["customer_id"];
$restaurant_id=$_POST["restaurant_id"];
$res;
$sql_query = "INSERT INTO bookingdetails(booking_date, booking_time, number_of_place) VALUES ('$booking_date','$booking_time', '$number_of_place')";
$sql_query2 = "INSERT INTO `booking`(`booking_id`, `customer_id`, `restaurant_id`) SELECT booking_id, '$customer_id', '$restaurant_id' FROM bookingdetails ORDER BY booking_id DESC LIMIT 1 ;";
if(mysqli_query($con,$sql_query))
{
}
else
{
}
if(mysqli_query($con,$sql_query2))
{
}
else
{
}
?>
Is that a legit solution on a server which joining to an Android app? Is there any case, that i don't get the good id on the second query? What would be a better solution?
Answer given in comment by #Mark Ng
Use last insert id, criteria is that your pk has to be AI.
The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) used in the last query.
Source: w3schools.com/php/php_mysql_insert_lastid.asp
To elaborate
you have to execute the query from which you need the last inserted id, then you can access that by using
$last_id = $conn->insert_id;
which in turn you can use for your following query.
Note:
I see you use a query to use the results for your insert query, but your syntax is incorrect (your missing values)
I have a database of Users and another table for Teachers. Teachers have all the properties as a user but also an e-mail address. When inserting into the DB how can I insert the info, ensuring that the ID is the same for both?
the ID currently is on automatic incrament.
this is what I have at the moment:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$sqlQuery = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result=mysql_query($sqlQuery);
thank you!
use MYSQL function LAST_INSERT_ID()
OR php mysql http://ro1.php.net/manual/en/function.mysql-insert-id.php
why to use separate table for teachers. instead, you can have email field with in user table and additional field with flag (T ( for teacher) and U (for user). Default can be a U. This have following Pros.
Will Not increase table size as email would be varchar
Remove extra overhead of maintaining two tables.
Same Id can be used
If you want to have that as separate table then answer you selected is good one but make sure last insert id is called in same connection call.
After the first insert, fetch the last inserted id:
$last_id = mysqli_insert_id(); // or mysql_insert_id() if you're using old code
Or you could expand your second query and use mysql's integrated LAST_INSERT_ID() function:
$sqlQuery = "INSERT INTO teacher(id, email) VALUES ((SELECT LAST_INSERT_ID()), '$myEmail')";
Try this:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$id = mysql_insert_id();
$sqlQuery = "INSERT INTO teacher(id, email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
Insert data into two tables & using the same ID
First method
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($conn, $sqlQuery1);
$lastID = mysqli_insert_id($conn);
$sqlQuery2 = "INSERT INTO teacher(email, lastID) VALUES ('$myEmail', 'lastID')";
$result2 = mysqli_query($conn, $sqlQuery2);
If the first method not work then this is the second method for you
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($sqlQuery1);
$sqlQuery2 = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result2 = mysqli_query($sqlQuery2);
You can set the Foreign Key in your database table (phpMyAdmin/ MySQL Workbench) to let the Foreign Key follow the Primary Key (ID). Then the data after insert will auto-follow the Primary Key ID.
Example here,
Teachers table set ID - Primary Key
Users table set UserID - Foreign Key (will follow the Teachers table ID)
if you're using MySQL WorkBench, you can refer to this link to set a foreign key.
https://dev.mysql.com/doc/workbench/en/wb-table-editor-foreign-keys-tab.html
Hope I can help any of you.
Though you can use the LAST_INSERT_ID() function in order to get the last insert id, the best approach in this case is to create a column reference to user id table.
teacher
id | user_id | email
So the teacher.id could be anyting, but the user_id column is the real reference to user table.
If you use InnoDB table, you can make the database consistent using Foreign keys
You Should Use A Transaction In MySQL. First insert In One Table And GET LAST_INSERT_ID().
Insert LAST_INSERT_ID() In Second Table.
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$sqlQuery = "INSERT INTO teacher(LAST_INSERT_ID(), email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
im having trouble inserting my data's from textbox into postgresdb.
my insert into tbl_ingredients is working fine but my insert into tbl_item is having a troubles can't figure it out how and where?
Connect();
$sql="INSERT INTO tbl_item VALUES('$itemname', '$highthreshold', '$lowthreshold', '$Qpunit', '$description', '$date');";
$iteminfo = pg_query($sql);
$sql1="SELECT MAX(itemid) as newid FROM tbl_item;";
$iden_new = pg_query($sql1);
$fetched_row = pg_fetch_row($iden_new,NULL,PGSQL_BOTH);
$newid=$fetched_row['newid'];
$sql2="INSERT INTO tbl_ingredient VALUES('$newid', '$Brandname');";
$ingredients = pg_query($sql2);
CloseDB();
if(!$sql)
{
$sucmsg = "Successfully added new Item, ".ucfirst($itemname)."!";
echo $sucmsg;
}
else
{
echo "error in saving data";
}
table structure:
tbl_item
itemid>itemname>highquantitythreshold>lowquantitythreshold>qntyperunit>Itemtype>description>dateadded
tbl_ingredient
itemid>brandname
im getting wamp "Warning: pg_query(): Query failed: ERROR: invalid input syntax for integer: "Strawberry" LINE 1: INSERT INTO tbl_item VALUES('Strawberry', '6', '3', '1300gra... ^ in D:\Wamp\wamp\www\Php\CTea\AddItem.php on line 247"
can someone lend me a helping hand thanks!.
You either need to use NULL ->
$sql="INSERT INTO tbl_item VALUES(NULL, '$itemname', '$highthreshold', '$lowthreshold', '$Qpunit', '$description', '$date');";
OR
You need to specify the columns you are inserting into ->
$sql="INSERT INTO tbl_item (itemname, highquantitythreshold, lowquantitythreshold, qntyperunit, description, dateadded) VALUES('$itemname', '$highthreshold', '$lowthreshold', '$Qpunit', '$description', '$date');";
Without the NULL or column name, the database does not know that you are skipping the first column - itemid - so it will try to insert the 1st value into that column.
from the manual - http://www.postgresql.org/docs/9.1/static/sql-insert.html
The target column names can be listed in any order. If no list of
column names is given at all, the default is all the columns of the
table in their declared order; or the first N column names, if there
are only N columns supplied by the VALUES clause or query. The values
supplied by the VALUES clause or query are associated with the
explicit or implicit column list left-to-right.
Each column not present in the explicit or implicit column list will
be filled with a default value, either its declared default value or
null if there is none.
This question already has answers here:
How to get the last field in a Mysql database with PHP?
(5 answers)
Closed 9 years ago.
I am working on a register user form and I have two tables in mysql. What I want to do is when a new user has registered, take the id (which primary key) of that user and insert it into another table. What is the best way to do that?
Thanks in advance.
You need to use mysql_insert_id for this purpose. Here is an example:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
First insert the user details into users table and get inserted user id using mysql_insert_id. and use that user id to insert into another table.
AS ON GETTING IT ON PHP
GET LAST INSERT ID HERE
BUT IF YOU INTEND TO GET IT USING MYSQL QUERY
use stored procedure to store last insert id to a variable then generete your second query
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
SET #last_id_in_T1 = LAST_INSERT_ID();
INSERT INTO T2 (col1,col2) VALUES (#last_id_in_T1,val2);
or direct insert after your first insert
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
INSERT INTO T2 (col1,col2) VALUES (LAST_INSERT_ID(),val2);
Use any of transaction query for writing:
Following is in CI pattern:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('AN SQL QUERY...');
if(!$this->db->trans_complete()){
$this->db->trans_rollback();
}
$query1= "INSERT INTO employee ( username, email,...)
VALUES ('".$_POST["username"]."', ...)";
if($result1 = mysql_query($query1))
{
$emp_id = mysql_insert_id(); // last created id by above query
$query2= "INSERT INTO dept ( emp_id, dept_name, ...)
VALUES ('".$emp_id."', '".$_POST["dept_name"]."',...)";
if($result2 = mysql_query($query2))
{
//success msg
}
}
Another neat way to do it at do it at Database level itself is to used Stored Procedure
Look at this solution to see an example of how to do it. You will have to check how Stored procedures work in your specific database to get the specific syntax. This makes it error free even if someone refactors or moves around the code and more efficient.
Using trigger the Mysql on database-level. For example, I have two tables:
user(id int primary key, nombre varchar(50));
replication(id_r int primary key, nombre_r varchar(50));
Using the trigger:
create trigger user_r after insert on user
for each row
insert into replication(id_r, nombre_r)
select u.id, u.nombre
from user u
where u.id=NEW.id and u.nombre=NEW.nombre;
I am working on an events calendar using PHP and MySQL (V5.1) where the admin would add an event, and then an attendance list for that event would be created as well. I have three tables: events, attendance and members. So far I can create the event using information that is entered thorugh a PHP form. I'm trying to update the attendance table by inserting the event id from the event that has just been created, as well as pulling in the list of members (using their member ID) from the members table. Nothing is being added to attendance the table though. Can someone let me know what I should I be doing differently?
Some of the fields I am using in the tables:
Events: event_ID (Primary key, auto-increment), name, location, date
Attendance: attendance_ID (Primary key, auto-increment), event_ID, member_ID, attending
Members: member_ID (Primary key, auto-increment), name, email
enter code here
Here is the code:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT LAST_INSERT_ID(), members.member_ID FROM members");
if ($query1 and $query2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
You could use mysql_insert_id()
$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");
$insert_id = mysql_insert_id() ;
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT {$insert_id}, members.member_ID FROM members") ;
A couple of important points. First, if you getting your last insert ID you should execute LOCK and UNLOCK queries first:
LOCK TABLES events WRITE;
UNLOCK TABLES
Second, you can use the mysqli_insert_id() method to get the ID of the last insert. This means that you must have an AUTO_INCREMENT field in the table you are inserting.
Put VALUES into $query2 to form a correct SQL-statement:
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) **VALUES (**SELECT LAST_INSERT_ID(), members.member_ID FROM members");