Statement query php / mysql - php

My problem is that the value "Arvin", "Tarrega", "Rizal", "Math", "Male" comes from another table which is "student". The value that I have there in the status and date column field comes from a user input. I want to put a statement query which will combine this two into one. Please help me. Btw, the other table doesn't have the status and date field. Only the attendance table has that 2 fields.
table name: attendance
Here is the code I'm using to get that result:
$sql = "INSERT INTO attendance(date, status) VALUES('$_POST[set_date]', '$_POST[status]');
INSERT into attendance(fname, lname, subject, section, gender) SELECT fname, lname, subject, section, gender from student;";

What I would do is to use the fact that you can "select" string in an sql query.
e.g.:
select 'hello' from any_table
In your case, I would do :
$sql = "INSERT into attendance(date, status, fname, lname, subject, section, gender) SELECT '$_POST[set_date]','$_POST[status]',fname, lname, subject, section, gender from student;";
This way you can have all the information you need to insert in one sql query.

Related

Insert data into table and immediately select ID number of the row

I have a MYSQL table called 'Buyers'. I am taking form data and inserting it into the table on a page called insert.php.
Now, along with the column names for the form fields, I have an Auto-increment ID column in the table. What I want is; once I send the form data to the table, I want to then execute some SQL to get the ID number for the row into which I just inserted the data into.
E.g, I have the SQL:
INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]');
This will create a row in the 'Buyers' table with the data from form fields 'name', 'email' and 'job'.
This row will have an ID number generated by Auto Increment.
How, then, can I then select that exact ID number? Is there some way to select the most recent row in the table, since that is the row which contains the ID number I want?
Mysqli : mysqli_insert_id()
<?php
mysqli_query($con,"INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysqli_insert_id($con);
?>
PDO : PDO::lastInsertId()
<?php
$stmt = $con->prepare("INSERT INTO Buyers (name, email, job) VALUES (?,?,?)");
$stmt->bind_param("sss", $_POST['name'], $_POST['email'], $_POST['job']);
$stmt->execute();
$last_id = $con->lastInsertId();
?>
Assuming $con as connection.
Mysql : mysql_insert_id()
<?php
mysql_query("INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysql_insert_id();
?>
NOTE: [The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead ]
SELECT x.*
FROM messages x
JOIN
( SELECT from_id, MAX(time_sent) time_sent GROUP BY from_id ) y
ON y.from_id = x.from_id
AND y.time_sent = x.time_sent;
The last part of this puzzle is left as an exercise for the reader.
Use mysql_insert_id() to retrive ID. More details - http://php.net/manual/en/function.mysql-insert-id.php

PHP/SQL After insert value to table and set one value as unique, no more values can be inserted

I try to create normalized db.
When I insert values FIRST time, everything is working perfectly, but (I think cause of set values as UNIQUE) it do not want to add.
This is my queries ( I can show database as well if needed )
$query = "INSERT INTO userMore (userEmailG, userGenderG, userAboutG, userBirthdayG, userLanguageG) values ('$userEmailG','$userGenderG', '$userAboutG', '$userBirthdayG', '$userLanguageG');";
$query .= "INSERT INTO userBasic (id_uM, userNameG, userEmailG) values ((SELECT id_uM FROM userMore WHERE userEmailG='$userEmailG'),'$userNameG', '$userEmailG');";
$query .= "INSERT INTO dvlaInfoMore (sixMonthRate, twelveMonthRate, wheelPlan, revenueWeight, typeApproval, taxStatus, taxed, taxDetails, mot, motDetails) values ('$sixMonthRate', '$twelveMonthRate', '$wheelPlan', '$revenueWeight', '$typeApproval', '$taxStatus', '$taxed', '$taxDetails', '$mot', '$motDetails');";
$query .= "INSERT INTO dvlaInfoBasic (id_uDInfoM, plateNumber, make, model, yearOfManufacture, cylinderCapacity, dateofFirstRegistration, co2Emissions, fuelType, colour, vin, transmission)
values (LAST_INSERT_ID(), '$plateNumber', '$make', '$model', '$yearOfManufacture', '$cylinderCapacity', '$dateofFirstRegistration', '$co2Emissions', '$fuelType', '$colour', '$vin', '$transmission');";
$query .= "INSERT INTO userLocation (latitude, longitude, postCode) values ('$latitude', '$longitude', '$postCode');";
$query .= "INSERT INTO userChioce (doWithCar) values ('$doWithCar');";
$query .= "INSERT INTO userStatus (userIdG) values ('$userIdG');";
$query .= "INSERT INTO userMain (userIdG, id_uB, id_uDInfoB, id_uChoice, id_uLoc, id_uStat) values ('$userIdG', (SELECT id_uB FROM userBasic WHERE userEmailG='$userEmailG'), (SELECT id_uDInfoB FROM dvlaInfoBasic WHERE plateNumber ='$plateNumber'), LAST_INSERT_ID(), (SELECT id_uLoc FROM userLocation WHERE postCode='$postCode'),(SELECT id_uStat FROM userStatus WHERE userIdG='$userIdG'))";
So, first time userMore added then userBasic then dvlaInfoMore then dvlaInfoBasic and so one
I set in userBasic column userNameG as UNIQUE, so IF inserted email which already exist, it do not want to go further, BUT if not, everything added correctly.
ALL what I want that it will continue inserting different cars and then by using existing email display result in table userMain.
P.S. if I try to add different car from by using same email address it doesn't work., basically do not add anything.
As you suspected yourself, INSERT with an existing key defined as UNIQUE will fail.
One workaround is to use the REPLACE INTO statement instead of INSERT (see manual).

inserting data from another table and data from textbox and checkbox to create a new record

I have to insert from table 1 into table 2 the values of username, name, lastname, roomnum and dormID.
I have to insert into table 2 the current date of today(it changes everyday), comments(the user wishes to enter- this is a textbox) and the attendance(present, absent, late)(these are the checkboxes).
When trying to click on the submit button the only thing that inserts into the database is the records that I am pulling from table1 into table 2.
When i try to incorporate to also insert the date, latecomments(textbox), and the attendance(checkboxes) it does not store any record.
This are the inserts:
$checkbox1 = $_POST['chk1'];
$latecomment=trim($_POST['latecomment']);
$d=strtotime("today");//todays date
$day=date("Y-m-d", $d);//date format
if($_POST["Submit"]=="Submit"){
for ($i=0; $i < sizeof ($checkbox1); $i++){
$query="Insert into dailyattendance (attendance) VALUES ('".$checkbox1[$i]."')";
mysql_query($query);
$daily=mysql_query("INSERT INTO dailyattendance(username, name, lastname, roomnum, dormID) SELECT user.username, user.name, user.lastname, user.roomnum, user.dormID FROM user WHERE user.role='Student'" );
$otherinfo=mysql_query("INSERT INTO daily attendance set date='".$day."', latecomment='".$latecomment."' WHERE dailyid=''");
}
}
There's a blank in your table name (in your given code):
INSERT INTO daily attendance
There's a WHERE clause in your INSERT statement and you are using UPDATE syntax with SET:
INSERT INTO daily attendance set date='".$day."', latecomment='".$latecomment."' WHERE dailyid=''");
Question: Is there a column named "attendance" in your table?
You should use only one INSERT statement if you want to add one row with all columns.
To clearify it a bit here is a code example you could start with. The SELECT on user is once before the loop because it seems to be same data all the time. You should add a function to escape strings before using them in the SQL statement to avoid errors when quotes are in it. Have a look at PHP or SQL error messages if something went wrong.
if($_POST["Submit"]=="Submit"){
$sql = "SELECT username, name, lastname, roomnum, dormID FROM user WHERE user.role='Student'";
$result = mysql_query($sql);
$student = mysql_fetch_assoc($result);
for($i=0; $i < sizeof ($checkbox1); $i++){
$sql = "INSERT INTO dailyattendance (username, name, lastname, roomnum, dormID, attendance, date, latecomment)";
$sql.= " VALUES ('".$student["username"]."', '".$student["name"]."', '".$student["lastname"]."', '".$student["roomnum"]."', '".$student["dormID"]."'";
$sql.= ", '".$checkbox1[$i]."', now(), '".$latecomment."')";
mysql_query($sql);
}
}

SQL / PHP Insert columns form one table to another

Hi I working on simple newsletter script, I got two groups there with two different tables for each group.
I want to move subscribers from one group to another, I put this query and It works:
$sql = "INSERT INTO newsletter_subscribers2 SELECT * FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";
However after moving some previous subscribers I got error with duplicated entry key, as I supose query is moved with ID, so I want just move, name, lastname and email.
$sql = "INSERT INTO newsletter_subscribers2 VALUES (firstname, lastname, email) SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname, newsletter_subscribers.email FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";
However this part of code doesnt seemst to work as I got syntax error, can anyone help me with this I will be very happy.
Thanks for reply
You have to remove values
$sql = "INSERT INTO newsletter_subscribers2(firstname, lastname, email)
SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname,
newsletter_subscribers.email
FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";
Remove the VALUES
$sql = "INSERT INTO newsletter_subscribers2 (firstname, lastname, email)
SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname,
newsletter_subscribers.email
FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";
Edit: And always use mysql_real_escape_string to prevent SQL-injection:
$sql = "... WHERE id='".mysql_real_escape_string($_GET['nid'])."'";
Try this:
insert into newsletter_subscribers2 (col1, col2, col3, etc) select col1, col2, etc from newsletter_subscribers2 where 1 = 1

MySQL insert from another table where field(s) are not null

I am trying to insert data into a table (table1) based on another (table2), the only problem is that table1 contains fields set to not allow null values. Do I need to create these fields in table2 where I am pulling the data from and populate them with a value?
Example not null field: password
If I do not include this in my query then I get an error and the record is not inserted however if I create the field in table2 then insert into my query it works fine. This seems a bit out of the ordinary. Example query below:
Example 1 (no password field in table 2):
$insert_new_records_query = "INSERT INTO table1 (first_name, last_name, email_address) ".
"SELECT firstname, lastname, email FROM table2";
This generates an error saying that I must include the password field.
Example 2 (password field in table 2):
$insert_new_records_query = "INSERT INTO table1 (first_name, last_name, password,
email_address) ".
"SELECT firstname, lastname, password = 'password1', email FROM table2";
This allows the record to be created. The problem is that I have many more fields that are not null in table 1 and I don't think I need to create them in table 2 as blank fields and insert them into my query with values just to create a record. Is there a better way to do this?
You don't have to create fields, you can simply 'select' default values. Try this instead:
INSERT INTO table1 (first_name, last_name, password, email_address)
SELECT firstname, lastname, 'password1', email FROM table2

Categories