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.
Related
hey guys i have this problem..
basicly the first query is jsut for inserting and the 2nd query is for copying data from another table via foreign key. have any idea? im newbie.. :D
else if($payment_description == 'Monthly Subscription'){
$payment_amount = '750';
$sql = "INSERT INTO `paymentlog` ( payment_amount,payment_description,date_payment)
VALUES ( '$payment_amount', '$payment_description','$date_payment')";
$query_run = mysqli_query($conn, $sql);
$sql1 = "INSERT INTO paymentlog (member_id, first_name, last_name)
SELECT member_id, first_name, last_name
FROM member
WHERE member_id = $id";
$query_run1 = mysqli_query($conn, $sql1);
echo ("<script LANGUAGE='JavaScript'>
window.alert('Monthly Payment is been added.');
window.location.href='/PROJECT/MEMBERS/members.php';
</script>");}
I don't think your current code does what you want. You are (attempting to) insert two rows, while, as I understand your question, you want to create a single row in payment_log, with the amount, description and date given as input, and member information that needs to be retrieved from another table using another input paramter.
You can use the insert ... select syntax:
INSERT INTO `paymentlog` (
member_id,
first_name,
last_name,
payment_amount,
payment_description,
date_payment
)
SELECT
member_id,
first_name,
last_name,
:payment_amount,
:payment_description,
:date_payment
FROM member
WHERE member_id = :id
Important notes:
Use prepared statements! Do not concatenate variables in the query string, this is both inefficient and unsafe. Recommended reading: How can I prevent SQL injection in PHP
From a database design standpoint, you should not be duplicating information from table members in table payment_log; storing a reference to the primary key of member is sufficient
I am making a car dealership booking form and I need to select a staff member at random to go on the test drive
I've tried mt_rand() but I think I'm putting it in the wrong place
````````````````````````````````````
$sql = "INSERT INTO bookingcars (BookingStart, BookingEnd, BookingDate, MemberReference, ActivityID staffID) VALUES ('$timeStart', '$timeEnd', '$startDate', '$memberReference', '$activity', '$mt_rand(1, 4)staffID'";
````````````````````````````````````
while you could build it in the query, its little cleaner and easier to debug if you do something like:
$staff=rand(1,4).'staffID'; // assume you wanted 1staffID .. ?
//or did you just want $staff=rand(1,4);
$sql = "INSERT INTO bookingcars (BookingStart, BookingEnd, BookingDate, MemberReference, ActivityID, staffID) VALUES ('$timeStart', '$timeEnd', '$startDate', '$memberReference', '$activity', '$staff')";
Another way would be in your query values to add a subquery like ,...) VALUES (..., (SELECT DISTINCT (Id) FROM stalesstafftable order by Rand() limit 1))
Hi I am trying to add records from one table to another, once i have added a 'user' record, the table that is being selected contains rows of available security options, and the table that is being inserted to is the child table for the user, detailing security options.
I cam across this code in an earlier post, which i am sure works nicely, however i am trying to modify it so that the values from statement, includes two parts, one from the select query and one which is the key from the master record.#
This is the original code I found from this site:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
And this is what I am trying to do with it:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('".$keys["UserPk"]."', SELECT ModulePk from Global_Modules)";
CustomQuery($sql);
And this is the error I am getting:
INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('4', SELECT
ModulePk from Global_Modules)
See screenshot for further detail
Obviously I am not concating the from statement properly, but would appreciate any help?
You can insert the $keys["UserPk"] variable as if it were a constant in the SQL:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Do note that $keys["UserPk"] must be escaped before adding it into the query. In PDO, it would look like this:
$keys["UserPk"] = $pdo->quote($keys["UserPk"]);
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Could be a problem related to the double quotes sequence
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
values ('". $keys['UserPk']. "', SELECT ModulePk from Global_Modules)";
but you could use also a select insert
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
SELECT '" . $keys['UserPk']. "' , ModulePk from Global_Modules)";
Adding only new and unique records from one table to another. Limiting is a good idea to prevent it from timeout. It can be run several times until all the records copied.
First, select the latest record ID from the table to be copied:
SET #lastcopied =
(SELECT
IF(MAX(a.exp_inotech_id)>0, MAX(a.exp_inotech_id), 0) AS lastcopied
FROM
kll_export_to a
WHERE exp_tezgah = 'A2015-0056');
Then, select and add the records to the destination table:
INSERT INTO kll_export_to
(SELECT * FROM
kll_export_from f
GROUP BY f.exp_inotech_id
HAVING COUNT(f.exp_inotech_id) = 1 AND exp_tezgah = 'A2015-0056' AND f.exp_inotech_id > #lastcopied
ORDER BY exp_inotech_id
LIMIT 1000);
I have a query that that works fine as long as there exists values in it after the WHERE condition is called. However, in some cases the query is empty because no values = '$project_id'. In this scenario it enters a blank field to the table. I would like to enter 1 by default if no values meet the WHERE condition.
Here is my query
$query =
"INSERT INTO tapp_contact_list
(id, location)
SELECT (MAX(id)+1), '$location'
FROM tapp_contact_list
WHERE meeting_project_id = '$project_id'
";
Any help is gladly appreciated!
Try this.
$query =
"INSERT INTO tapp_contact_list
(id, location)
SELECT COALESCE( (MAX(id)+1), 1 ) , '$location'
FROM tapp_contact_list
WHERE meeting_project_id = '$project_id'
";
For more details check this function.
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce
i have a form where i post the data to mysql. the query should insert the data from the form into table1, but also include data from another table2 where the ID that is send from the form is equal to the ID in table2?
i use the old mysql connection, i know, not the best :-) and php!
hope someone can help, thanks :-)
Martin
think maybe I should give some more info :-)
table1 is called: books
from the form, i have the following value: itemCode, itemQty, ownerID
i have 2 static value: status, type
the values from table2 that must be inserted into table1 is:
title, description, price, frontcover
from table2 the field isbn should be equal to itemCode from form.
here is what i have tried so far:
$bookid=$_POST['itemCode'];
$itemQty=$_POST['itemQty'];
$status='2';
$ownerID = $user->id;
$query="INSERT INTO books (name, description, price, picture, status, ownerID, itemqty, type, studie, isbn) SELECT (title, description, price, frontcover FROM isbnbooks WHERE isbn=$itemCode), $status, $ownerID, $itemQty, '1', '1', $bookid)";
UPDATE:
I have also tried this one here:
$bookid=$_POST['itemCode'];
$itemQty=$_POST['itemQty'];
$status='2';
$ownerID = $user->id;
$data2 = mysql_fetch_array (mysql_query("SELECT * FROM isbnbooks WHERE isbn = $bookid"));
$title = $data2[title];
$description = $data2[description];
$price = $data2[price];
$picture = $data2[frontcover];
$query="INSERT INTO books (name, description, price, picture, status, ownerID, itemqty, type, studie, isbn)
VALUES ($title, $description, $price, $picture, $status, $ownerID, $itemQty, '1', '1', $bookid)";
mysql_query($query) or die("Opps some thing went wrong");
If you have values 'a' and 'b' to go into columns f1 and f2 of table1; and in f3 you want the value of table2.field where table2.id is 123, you can prepare and execute a SQL statement along these lines:
INSERT INTO table1 (f1, f2, f3)
SELECT 'a', 'b', field FROM table2 WHERE id = 123;
Further to seeing the code in your updated question, the problem with your first attempt is that you're trying to mix INSERT ... SELECT with INSERT ... VALUES; sadly they are mutually exclusive. However, you could write instead:
INSERT INTO books (
name,
description,
price,
picture,
status,
ownerID,
itemqty,
type,
studie,
isbn
)
SELECT
title,
description,
price,
frontcover,
:status, -- use prepared statements to prevent SQL injection
:ownerID, -- see http://bobby-tables.com/ for more info
:itemQty,
'1', -- do you really want a string containing a number?
'1',
:bookid
FROM isbnbooks
WHERE isbn=:itemCode;
Your second attempt looks as though it ought to work (although you really should use prepared statements, see above!); what problems are you having with it?
in the absence of code, here's the workflow id recommend:
Form is submitted -> check and sanitize values - > execute lookup query against "table 2" and get your related values -> commit the update query with both form and "table2" data -> on successful update, notify user that their information was processed -> thank them.
Something like this ? :
$data2 = mysql_fetch_array (mysql_query("SELECT * FROM table2 WHERE id2 = '1'"));
$data1 = data2['column2'];
mysql_query("INSERT INTO table1 VALUES('value1','$data2') WHERE id1 = id2);