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
Related
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))
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.
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);
i had following table and columns
Table Name = users
column = user_id, name, email, password, status, identity
i'm using following query for insert data to table users
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['txtPassword']);
$password = md5($password); //===Encrypt Password
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0')";
$res = mysql_query($query);
header('location:success_register.php');//Redirect To Success Page
}
what i am asking is, i want store last id to column identity also
for example: if last user_id= 10, identity also will be = 10. i mean get last id then store that id to identity column
Result will be look like this
user_id name email password status identity
5 aa aaa#ab.com **** 1 5
6 bbb bbb#ac.com **** 1 6
how to do it,?
In MYSQL, you have alternative possibility to find it, when you think last_insert_id() is not working. You may require to have SELECT privilege on INFORMATION_SCHEMA and its tables.
If you have that privileges, try the following query.
$query = "insert into users( name, email, pasword, status, identity )"
. " values( '$name', '$email', '$password', '1',"
. " ( SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES"
. " WHERE TABLE_NAME='users' and TABLE_SCHEMA=DATABASE() )"
. " )";
And, lastly, suggesting to stop using deprecated API.
Save last insert id like this:
$id = mysql_insert_id();
and use it in next insert
You are looking for:
mysql_insert_id()
mysqli_insert_id(mysqli $link)//for mysqli
PDO::lastInsertId()//for PDO
Other Approach:
if your id column is auto increment and not random then you can select the max id(everytime just after your insert query) from the users table and insert it into whatever column you want.
$id=mysql_result(mysql_query(select max(user_id)
from users),0);
Dont use mysql_ as they are depracated.*
here is what you are looking for. Select max(user_id)+1 and store it in a variable.
Now you need to pass this variable in user_id and identity parameter.
Note that even though user_id is auto increment, it will allow you to insert the new row with specified user_id
i think you can also put it like this
$lastID = MySQLI_insert_id($DBcon); //where Dbcon is your connection to your database
and then
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','$lastID')";
$res = mysql_query($query);
I think you need to insert number of rows in the table after the insert:
It may useful to you
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0',(select COUNT(*)+1 FROM users))";
I recently asked a question about writing to multiple tables: PHP/MySQL insert into multiple data tables on submit
I have now tried out this code and there are no errors produced in the actual code but the results I am getting are strange. When a user clicks register this 'insert.php' page is called and the code can be found below.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$institution = $_POST["institution"];
$conn = pg_connect("database connection information"); //in reality this has been filled
$result = pg_query($conn, "INSERT INTO institutions (i_id, name) VALUES (null, '$institution') RETURNING i_id");
$insert_row = pg_fetch_row($result);
$insti_id = $insert_row[0];
// INSTITUTION SAVED AND HAS ITS OWN ID BUT NO MEMBER OF STAFF ID
$resultTwo = pg_query($conn, "INSERT INTO staff VALUES (NULL, '$username', '$password', '$insti_id'");
$insert_rowTwo = pg_fetch_row($resultTwo);
$user_id = $insert_rowTwo[0];
// USER SAVED WITH OWN ID AND COMPANY ID
// ASSIGN AN INSTITUTION TO A STAFF MEMBER IF THE STAFF'S $company_id MATCHES THAT OF THE
// INSTITUION IN QUESTION
$update = pg_query($conn, "UPDATE institutions SET u_id = '$user_id' WHERE i_id = '$insti_id'");
pg_close($conn);
?>
What the result of this is just the browser waiting for a server response but there it just constantly waits. Almost like an infinite loop I'm assuming. There are no current errors produced so I think it may be down to a logic error. Any ideas?
The errors:
RETURNING clause is missing in the second INSERT statement.
Provide an explicit list of columns for your second INSERT statement, too.
Don't supply NULL in the INSERT statements if you want the column default (serial columns?) to kick in. Use the keyword DEFAULT or just don't mention the column at all.
The better solution:
Use data-moidifying CTE, available since PostgreSQL 9.1 to do it all in one statement and save a overhead and round trips to the server. (MySQL knows nothing of the sort, not even plain CTEs).
Also, skip the UPDATE by re-modelling the logic. Retrieve one id with nextval(), and make do with just two INSERT statements.
Assuming this data model (you should have supplied that in your question):
CREATE TABLE institutions(i_id serial, name text, u_id int);
CREATE TABLE staff(user_id serial, username text, password text, i_id int);
This one query does it all:
WITH x AS (
INSERT INTO staff(username, password, i_id) -- provide column list
VALUES ('$username', '$password', nextval('institutions_i_id_seq'))
RETURNING user_id, i_id
)
INSERT INTO institutions (i_id, u_id, name)
SELECT x.i_id, x.user_id, '$institution'
FROM x
RETURNING u_id, i_id; -- if you need the values back, else you are done
Data model
You might think about changing your data model to a classical n:m relationship.
Would include these tables and primary keys:
staff (u_id serial PRIMARY KEY, ...)
institution (i_id serial PRIMARY KEY, ...)
institution_staff (i_id, u_id, ..., PRIMARY KEY(i_id, u_id)) -- implements n:m
You can always define institution_staff.i_id UNIQUE, if a user can only belong to one institution.