SQL / PHP Insert columns form one table to another - php

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

Related

PHP MySQL Insert Query From Multiple Tables into two tables

I've table like this :
tb_users
id, name, pin_number
tb_attendance
pin, date_time, user_id
i've created simple query for tb_attendace like this :
$sql = "INSERT INTO tb_attendance
( pin, date_time)
values
('$PIN', '$DateTime')";
i want to insert colum user_id from tb_users where tb_users.pin_number = tb_attendance.pin
in mysql command i've success run this :
INSERT INTO tb_attendance (pin, date_time, entry_by)
SELECT pin, date_time, tb_users.id
FROM tb_attendance , tb_users
WHERE tb_attendance.pin = tb_users.pin_number
but i don't know how to create this query into php script.
can some one help me to complete the php script ?
I'm not sure why you need both the pin and user id, if you can just use JOIN to get the PIN.
The query that you want looks something like this:
INSERT INTO tb_attendance (pin, date_time, entry_by)
SELECT $PIN, $DATE_TIME, u.id
FROM tb_users u
WHERE u.pin_number = $PIN;
I would advise you to use query parameters, and not to insert the parameter values directly into the SQL string. That is dangerous -- both in terms of creating a SQL syntax error and in terms of security.

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).

Statement query php / mysql

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.

Make an insert with the values returned by another query directly (PHP)

Im doing a PHP script for insert in the table A values recovered from the table B (A and B are in different databases).
Table A Columns
[index(autoincrement),timestamp(currenttimestamp),col1,col2,.....col15]
and I have the query for retrieve the values from B:
$query= "select count(*) as col1, XXX as col2.....ZZZ as col15 from B";
so having the
$row=$mysql_fetch_array($result)
where
$result=mysql_query($query)
how can I make an
insert into A (col1,col2.....col15) values ($row['col1'],....$row['col15'];
easily without write all the code? Thanks
Insert into db1.A (col1, col2, col3) SELECT col1, col2, col3 FROM db2.B
If you have to transfer the data across databases on different servers, you can use sprintf and implode to generate your query.
$query = sprintf('INSERT INTO table_name (%s) VALUES ("%s")', implode(', ', array_map('mysql_escape_string', array_keys($row))), implode('", "',array_map('mysql_escape_string', $row)));

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