My table looks like this:
check_in_id | amount | date | user_id (foreign key of user table )
In the interface it asks user to enter amount, date, username, password. When running the insert into query, how do I get user_id from that user table to insert into this table?
I suppose you have one main table (say: tbl_login ) to store username, password, user_id (primary key).
So, You first retrieve user_id with username and password like:
SELECT user_id FROM tbl_login WHERE username = '$username' AND password = 'password';
Where $username and $password is your entered username and password from interface.
So after getting user_id , now you have all needed values, so you can easily insert these in your given table.
Since the information in you query is incomplete, I will try to give an answer with certain assumptions.
check_in_id: an auto increment id in
You want to insert into table only if username and password matches.
The variables with '$' are the user inputs
insert into <your table>
(check_in_id, amount, date, user_id)
select null, $amount, $date, user_id from user
where username = $username and password = $password
Related
I want to complete user sign up.
firstly user will write username and password, table called users, I have id as primary key.
secondly user will write address, phone number and zipcode, table called userdata, I have userid as index(key).
I have did a relation between id from table user and userid from table userdata.
So now I want to insert data from php code I did two forms one for user and it has two input for username and password it works well and data inserted.
in the second form I have select option has id from table users and it works well.
then in the same form I have three inputs phone number, address and zipcode.
so the question is how I can insert the data to userdata by the same to the same id. so userid in table user will be the same id in table userdata.
I need sql code.
I used that :
"INSERT INTO userdata(address, phone, zipcode) VALUE (:address, :phone, :zip) SELECT 'id' FROM 'users';"
First :
$q = "NSERT INTO users(username, password) VALUE ('Adam', '12345678')";
$r = $connect->query($q);
//get the last id u inserted
$last_id = mysqli_insert_id($connect);
Second :
$q = "NSERT INTO userdata(address, phone, zipcode,user_id) VALUE ('California', '12345678', '1111','$last_id')";
$r = $connect->query($q);
and if you want to make the (id) not the (userid) the same just :
$q = "NSERT INTO userdata(id, address, phone, zipcode) VALUE ('$last_id','California', '12345678', '1111')";
$r = $connect->query($q);
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 have a problem with this query and hope someone will help me to fix this. I am trying to check username and email address are available to register when registering a new user to my site. username is coming from login table and email address is coming from contact table. Now I need to make a query to check given username and email by new users are available to register. If those are not available I want to print error messages. I am trying to make this query something like this but its not working as I expect.
$q = "SELECT username, email FROM login
INNER JOIN contact
WHERE login.username = '$username' OR contact.email = '$email'";
Then I am checking this query in PHP like this
$r = mysqli_query ($dbc, $q);
// Get the number of rows returned:
$rows = mysqli_num_rows($r);
if ($rows == 0) { // No problems!
// register new user
} else { // The email address or username is not available.
if ($rows == 2) { // Both are taken.
$reg_errors['email'] = 'This email address has already been registered.1';
$reg_errors['username'] = 'This username has already been registered.2';
} else { // One or both may be taken.
// Get row:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
if( ($row[0] == $_POST['email']) && ($row[1] == $_POST['username'])) { // Both match.
$reg_errors['email'] = 'This email address has already been registered.3';
$reg_errors['username'] = 'This username has already been registered with this email address.4';
} elseif ($row[0] == $_POST['email']) { // Email match.
$reg_errors['email'] = 'This email address has already been registered.5';
} elseif ($row[1] == $_POST['username']) { // Username match.
$reg_errors['username'] = 'This username has already been registered.6';
}
} // End of $rows == 2 ELSE.
my problem is PHP script always going to this code. query not checking individually username and email. I trying something like this.. username not available and email available, email not available and username available. But always going to this
if ($rows == 2) { // Both are taken.
$reg_errors['email'] = 'This email address has already been registered.1';
$reg_errors['username'] = 'This username has already been registered.2';
}
EDIT: Table structure..
# --------------
# Login Table
# --------------
CREATE TABLE login (
login_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(80) NOT NULL,
password VARBINARY(32) NOT NULL,
PRIMARY KEY (login_id),
UNIQUE(username)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
# --------------
# Contact Table
# --------------
CREATE TABLE contact (
contact_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
telephone VARCHAR(60) DEFAULT NULL,
mobile CHAR(10) NOT NULL,
email VARCHAR(80) DEFAULT NULL,
PRIMARY KEY (contact_id),
UNIQUE (email)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
You must provide ON clause which define the relationship on how the two tables are related with each other.
SELECT username, email
FROM login
INNER JOIN contact
ON login.colname = b.colName // change to your orignal colName
WHERE login.username = '$username' OR
contact.email = '$email'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
An alternative way to do this without checking on the value on the tables is by enforcing UNIQUE constraints on column of the table, ex
ALTER TABLE login ADD CONSTRAINT tb_uq UNIQUE (username);
ALTER TABLE contact ADD CONSTRAINT tb_uq1 UNIQUE (email);
when the two alter statements has been successfully executed,you cannot insert value if it already exists on that column.
UPDATE 1
SELECT COUNT(*)
FROM
(
SELECT userName as Value FROM Login
UNION
SELECT email as Value FROM contact
) s
WHERE VALUE IN ('$username','$email')
if the query above will return greater than 0, it means that value(s) already exists.
UPDATE 2
SELECT *
FROM
(
SELECT userName, NULL AS email FROM Login
UNION
SELECT NULL AS username, email FROM contact
) s
WHERE username = '$username' OR email = '$email'
Currently, your query selects every row from both tables as long as there is a single match for one or the other. You can get matching rows from both tables simultaneously:
SELECT username FROM login WHERE username = '$username'
UNION ALL SELECT email FROM contact WHERE email = '$email'
...and also with separate queries.
Your queries are vulnerable to SQL injection.
You are really checking 2 different things. A single query doesn't make sense, at least not a join. I suggest union instead:
select 'username' as exists from login
where username = '$username'
union all
select 'email' as exists from contact
where email = '$email'
This will return a table with a column called exists and a row for each element that exists. Here is what you would get back if both username and email exist:
EXISTS
username
email
Where you run this query, you already know what the username and email they entered are, so there is no point in returning those values from the table.
As others have pointed out, you have a big security hole if $username and $email are being passed in directly from the user. You definitely have to handle that somehow.
Every Inner join clause needs to have a predicate or "ON" condition to specify the rule or rules to be enforced when Joining the two tables...
the query needs an "ON" clause after the Inner Join. I'm not sure what that condition should be, but, as an example....
$q = "SELECT username, email FROM login
INNER JOIN contact
On contact.username = login.userName
WHERE login.username = '$username' OR contact.email = '$email'";
your join have a problem , because you should determine column wich you want join on it!
for example
NNER JOIN contact
On contact.id= login.contactId
I'm trying to do a MySQL Query that adds information to a database in a format that doesn't overwrite it's current value, but instead appends it as in the friends column would have friend1, friend 2, friend 3 ... etc.
First I am unsure if INSERT INTO is right:
$username = $_SESSION['username'];
mysql_query("INSERT INTO members (friends) WHERE username = $username
VALUES ('$friendtoadd')");
What I want to do is have this do two things
1) Add the friend in a format mentioned so that it can later be called out that if the $username set in session is active then the results posted on the page are only from those other users contained in their friends column.
2) If the $friendtoadd already exists in their column for friends then it does nothing.
UPDATE members SET friends = CONCAT_WS(', ', friends, '$friendtoadd') where username = '$username'
I hope $friendtoadd as well as $username are sanitized through mysql_real_escape_string
Also, this design isn't very good. You should have a seperate friends table
so
table friend
id (auto increment), userID, name)
then do
Insert into friend SET userID = $userID, name = '$friendName'
Below I have a $_POST variable for the teacher's firstname and surname:
if (isset($_POST['teacherforename'])) {
$_SESSION['teacherforename'] = $_POST['teacherforename'];
}
if (isset($_POST['teachersurname'])) {
$_SESSION['teachersurname'] = $_POST['teachersurname'];
}
Now the problem I have is that I want to insert this into the database but I don't want the firstname and surname to be inserted into the database, I want the teacher's username to be inserted into the database.
For example: John May has a username T1, Ben Watts has a username T2 and Jean Smart has a username T3.
So how can I get it so that it looks up the teacher's firstname and surname, find the teacher's username from that (field for username is TeacherId) and then insert the username in the 'TeacherId' field in the "Session" Table?
I have connection to database and all that. I just want to how to code it so that it finds a teacher's username (TeacherId) by its full name then insert it into the database?
Do you want Teacherid (like T1,T2,T2) by looking username which is obtained by selecting surname and forename??
SELECT TeacherId FROM (SELECT Username from teachers where forename='forename' and surname='surname')
Why not query database with WHERE name='$name' (combination of firstname.' '.lastname)
And use the returned ID in your script?