Insert INTO queries using WHERE clause - php

I have issue on INSERT INTO query,
In the registration form, when user enter username and select the department/center as bursary,
I want to insert that UserName into table bursary.
What I tried is;
$query14 = "INSERT INTO bursary (UserName) VALUES
('$UserName') WHERE DepartCent='Bursary'";
$result14=mysql_query($query14);
My table name is bursary, and it's look like ;
UserID UserName
1 ( ) <---- I want only UserName that choose department/center as bursary
Please anyone help me to solve this, appreciate that.

INSERT queries imply adding data that isn't there already. If you want to insert a value derived from a query you need to use an actual query to get it. The WHERE clause fails because there no row to examine until you insert one.
There's really not enough info to figure out what you're trying to do, but if we just go on this part of your question:
"I want only UserName that choose department/center as bursary"
Then you are probably looking for an INSERT..SELECT (assumes you have already inserted the data into some other user table 'your_user_table')
INSERT INTO bursary(UserName)
SELECT UserName from your_user_table
WHERE DepartCent='Bursary';

You can either:
insert new rows in a database table
update existing rows in a database table
Only when you are trying to change values of existing rows does it make sense to specify a WHERE clause to let the database know which values you want to change.
EDIT: Could you explain again what it is exactly that you are trying to achieve? Do you want to insert only some users filling out your form? Namely those that choose bursary as their department?
Why don't you change your table structure to something like:
Table DEPARTMENT:
Department Name, Department ID
Table USER:
User Name, Department ID (foreign key to Department)
EDIT Nr. 2: The way to do that is by normalizing your Table structure. Suppose one of the following things happened:
You want to add an additional department later on - you would not want to create a new table for that every time.
You want to change the name of a department - do you want to rename your tables? change your code,... I doubt that
So the way to go is to design your tables in a way that they separate the different "things" in your program. One type of thing you are working with are departments (bursary,...) another type of thing are Users. As a rough starting point try to make a table for each and try to connect the tables with so called foreign keys. Read it like this:
Every department has a unique department ID
Every User is associated to a department by this users Department-ID
You can then later on join these tables to find out all users of department X,...
Select u.userName,d.departmentName from User u INNER JOIN Department d ON
u.departmentId=d.departmentId
This would show you the names of all your users and their associated departmentName

Related

Best approach to add multiple data to a column in MySQL

For example, I have Users and Projects tables.
Multiple users can be members of a project. How do I insert multiple users into the members column of the Projects table?
Do I separate by comma like: "John, Alex, Hanna"?
I'm a beginner in MySQL, sorry if this is a dumb question. Thanks!
You defiantly need another table.
It should look like this
Name: UserProjects
Field: UserId
Field ProjectID
Those 2 fields should be primary keys (dual primary id). If you want to go down the route of 'soft deletes' then add a status column which you'll set to 0 if you delete it. Also look up insert on update for mysql.
Trust me this is the way to go. Using a delimiter field or something will only give you problems later down the line.

Can you make/insert tables inside every row in a table of a database in PHP/MySQL?

Is it possible? If yes, how?
I am using xampp for my database and I wanted to make a database with "students" table, only one column for the list of student IDs, and every student ID has another table inside. (I was considering making tables for every student ID so that it can be done directly but it seems that it PHP/MySQL does not allow integers as table name).
No, you cannot put tables inside a row in SQL. That's not compatible with the concept of a relational database. What you can do is provide a foreign key to another table where you can collect the data you need to link to your first table.
What you need is to have one table with all you want about the students, and add a field with their ID.
So, yo don't have to get the information from student #123 as
SELECT * FROM 123
but
SELECT * FROM students_table WHERE IdStudent = 123

Check if data entered by user in html form already exists in database in php

After entering data in html form while clicking on button to add the data in the database, I want to check whether the user already exists in the database. I am using php v5.3.5 and mysql v5.5.8.
Data is stored in 2 tables simultaneously named person and other and there is no primary key(in both columns) since there is no column which can be treated as primary key
Can any one help me how to do that??
Code is::
$sqlComm="Insert into person(Name,father_name,date_birth,
gender,Res_Address,Mobile_no)
values('$name','$fatherName','$dob',
'$gender1','$resAddress','$mobileNo')";
$sql="insert into other_staff(p_id,employer,off_ph_no)
values('$pId','$employer1','$phOffice')";
Id is automatically generated for each person which is retrieved and stored in other table as p_id.
combination of name,father_name,date_birth,employer can be made unique..
It seems like none of the fields suggested can be a primary key, any of them or a combination of them cannot uniquely identify a person. It's a really strange database design and I urge you to check your database design.
You will have to a search by doing a separate select query to find if the user exists. Also Ensure both the statements are executed inside a transaction.
You will have to think about what makes a person unique for your schema/application. Changing the mobile number probably does not make one a new person, but am i the same as an existing person, if we share the name, father_name, date_birth and gender? If so, make that a unique key and you will have something your database can tell you, that it already exists. Just in case you did not already know: keys can span multiple columns.
Dispite with a bad schema, we can find a way(given below) to check weather a user exist or not. BUT I think you also want to check second table THAT with particular user there is an employer or not. Then here is problem in your database cause there is no column in PERSON or OTHER_STAFF's table which can tell us the Particular employer of a specific user in PERSON table
Solution: But for this condition you can use cross join to get nearly correct result:
if($result=mysql_query("SELECT 1 FROM person p CROSS JOIN other_staff e WHERE p.name='$name' AND p.father_name='$father_name' AND p.date_birth='$dob' AND p.gender='$gender1' AND p.Res_Address='$resAddress' AND p.Mobile_no='$mobileNo' AND e.employer='$employer1' AND e.off_ph_no='$phOff';")){
if(mysql_fetch_array($result)){
//exist
}else{
//not exist
}
}
Suggestion: Next time store auto generated id in PERSON and OTHER STAFF table BUT for this project- If you can store p_id in PERSON table then this query will return 1 on exist, otherwise null(same in above):
$sql="SELECT 1 FROM person p LEFT JOIN other_staff e ON p.p_id=e.p_id WHERE p.name='$name' AND p.father_name='$father_name' AND p.date_birth='$dob' AND p.gender='$gender1' AND p.Res_Address='$resAddress' AND p.Mobile_no='$mobileNo' AND e.employer='$employer1' AND e.off_ph_no='$phOff';";

Inserting an entry in multiple tables in an sql database

I'm creating a game in actionscript that requires the use of an external database to store user details and scores.
This database will contain multiple tables, currently there are two.
My first table contains the headers - ID, email, username, password.
My second table contains the headers - ID, lvl1Score, lvl2Score, lvl3Score.
In my game, when a new user is created it creates an entry in the first table with the ID auto-incrementing.
My question is - Is there anyway to automatically create an entry in my second table with its default values and the same ID when I add to my first table?
I've read about joins, but everything i've read just talks about looking up data over multiple tables.
Also, is my table structure correct in the sence that the ID value can be used using the JOIN keywork to look up an entry from both tables.
I would suggest you to go for triggers.
create or replace trigger trigger_name after
insert on table1
for each row
begin
insert into table2 values(new.id,"value for lvl2score","value for lvl3score");
end
Something like this.
If the tables truly have a one-to-one relation, I would recommend that you simply make one table having all the fields.
Or did you mean this should store multiple scores for each individual user? In this case, you should not insert a default record for the user. Instead, the score.ID field should instead reference user.ID and allow duplicates.
I suggest you to use triggers and for more flexibility create a many-many relationship between "user" and "level", so you will end up with 3 tables:
user
level
user_level (this will contain the foreign keys: user_id, level_id)

Move column into new table in mysql

I'm changing my database structure and I want to do the following thing: I have one table for registered users that holds almost all the information about my site users. There is also one other table that holds information about the amount of points each user have. It has only two columns: user id and points. I want to move the points column in main users table so that the points aren't lost. I know theoretically that I have to join these two colums with user id somehow but I can't guess what would the code look like...
Hope I'm clear.
Can anyone please help?
First, you will have to add the two column names to the structure of the first table... then do a correlated updates something like
UPDATE YourTable, YourOtherTable
SET
YourTable.Points = YourOtherTable.Points,
YourTable.PointsCol2 = YourOtherTable.PointsCol2
WHERE
YourTable.id = YourOtherTable.id

Categories