So I'm doing a register page for teams. So the user who creates a team will be inserted into a database table called alcs_teams. That's not the problem. Then I'd like to insert them into another table called alcs_member_teams. That keeps track of the members on each team.
So I do an insert query into the alcs_teams which works fine. Then I try to select the team id from the data that was just inserted a few lines below. Does this work? I can't get it to work, it just puts 0 in that field in the database.
$member = mysql_query("Select * from members where id=$_SESSION[tid]");
$member = mysql_fetch_array($member);
mysql_query("INSERT into alcs_team (teamid, name, leader, email) VALUES('', $_POST[name]', '$member[name]','$member[email]')");
$teamid = ("Select * from alcs_team where leader=$member[name]");
$row = mysql_fetch_array($teamid);
mysql_query("INSERT into alcs_member_teams (id, alcs_teamid, alcs_memberid, member_name) VALUES ('', '".$row[teamid]."' , '".$member[id]."', '".$member[name]."')");
You should look into using parametrized queries whenever possible
Example:
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$params = array($name, $email);
$sql = 'INSERT INTO CustomerTable (Name, Email) VALUES (?, ?)';
$stmt = sqlsrv_query($conn, $tsql, $params);
This prevents SQL Injection, which can cause a lot of trouble on your site.
Related
$sql3 = "INSERT INTO users_addresses (ua_user_id,ua_address_id) VALUES ('','')";
I am new in php and my hint is to link 2 tables id's in in another one called users_addresses.When a user is registered in my database i want the user_id and address_id to clone in users_addresses(ua_user_id,ua_address_id)
My tables
$sql = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}', '{$_SESSION['userinfo']['mname']}', '{$_SESSION['userinfo']['lname']}', '{$_SESSION['userinfo']['login']}', '{$_SESSION['userinfo']['email']}', '{$_SESSION['userinfo']['phone']}')";
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
$sql2 = "INSERT INTO notes (note_text)
VALUES ('{$_SESSION['noteinfo']['note']}')";
These are my others SQL codes for adding session's data in DB.
Just need get user_id from first sql. If you are using mysqli function, do this
// run your first sql: insert user
mysqli_query($con, $sql);
$user_id = mysqli_insert_id($con); // or mysqli::$insert_id
Next, you have $user_id variable with user id.
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ($'{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
mysqli_query($con, $sql);
$address_id = mysqli_insert_id($con); // or mysqli::$insert_id
$sql3 = "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES ($user_id, $address_id)";
mysqli_query($con, $sql);
Use mysqli_insert_id() to get the unique ID of the insert table, this example uses Procedural style:
<?php
include 'connection.php';
......
$InsertSQL = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}',
'{$_SESSION['userinfo']['mname']}',
'{$_SESSION['userinfo']['lname']}',
'{$_SESSION['userinfo']['login']}',
'{$_SESSION['userinfo']['email']}',
'{$_SESSION['userinfo']['phone']}')";
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
$UserID = mysqli_insert_id($conn); // <-- get the UserID
$InsertSQL = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}',
'{$_SESSION['addressinfo']['adr2']}',
'{$_SESSION['addressinfo']['zip']}',
'{$_SESSION['addressinfo']['city']}',
'{$_SESSION['addressinfo']['provinciq']}',
'{$_SESSION['addressinfo']['durjava']}')";
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
$AddressID = mysqli_insert_id($conn); // <-- get the AddressID
$InsertSQL = "INSERT INTO user_addresses (ua_user_id,ua_address_id)
VALUES ($UserID,$AddressID)"; // <-- INSERT INTO user_address
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
?>
You should also look into SQL Injection vulnerability, check out prepared statements.
Hope that helps.
This question already has answers here:
Insert_id is null when used directly in next prepared statement
(2 answers)
Closed last year.
I want to do more than one database queries in the same file:
Create a user, select the UID of that newly created user, and assign to that same user a specific role.
After I get the UID from the newly created user I save that value into the $userID variable, but at the end of the file, the variable value gets lost.
Why? (PS: I'm not taking into account security at the moment).
//Create User
$email = strip_tags($_POST['email']);
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$query = "INSERT INTO usuarios
(userEmail)
VALUES
('$email')";
$insertarBase = mysqli_query($conectar,$query);
mysqli_close($conectar);
//look for the UID of the newly created user
$conectar2 = mysqli_connect(HOST, USER, PASS, DATABASE);
$buscarUsuario = "SELECT userID, userEmail
FROM usuarios
WHERE userEmail='$email'
";
$resultadoBusqueda = mysqli_query($conectar2,$buscarUsuario);
$row = mysqli_fetch_array($resultadoBusqueda);
$userID = $row['userID'];
mysqli_close($conectar2);
//assign a role to the newly created user
$conectar3 = mysqli_connect(HOST, USER, PASS, DATABASE);
$asignarRol = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
('$userID', 'registered')
";
$asignarRolenBase = mysqli_query($conectar3,$asignarRol);
mysqli_close($conectar3);
echo $userID; //Here the content of $userID is gone, nothing gets printed out
Edited:
For some weird reason, $userID = mysqli_insert_id($conectar); returns zero.
The creation of the usuarios table statement is this:
CREATE TABLE usuarios(
userID int unsigned not null auto_increment primary key,
userEmail char(50) not null);
Also, echo $asignarRol; returns:
INSERT INTO rolesUsuarios (userID, nombreRol) VALUES ('0', 'noAutorizado')
i tried to tidy up your code and delete superfluous code.
//Create User
$email = $_POST['email']; // you have to verify if this is an email or html etc.
$conectar = new mysqli(HOST, USER, PASS, DATABASE);
$query = "INSERT INTO usuarios
(userEmail)
VALUES
(?)";
$stmt = $conectar->prepare($query);
$stmt->bind_param('s',$email);
$stmt->execute();
$userID = $stmt->insert_id;
$stmt->close();//close statement
//assign a role to the newly created user
$query = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
(?, 'registered')";
$stmt = $conectar->prepare($query);
$stmt->bind_param('i',$userID);
$stmt->execute();
$stmt->close();
$conectar->close();
echo $userID; //Here the content of $userID
First of all , you don't have to create a new db-connection for each statement.
Second: please prepare your statements - for security purposes.
If $userID is empty, make an error_log($userID); after you $userID gets it value, if it's empty , there might be something else wrong.
First as other said to you use prepared statement for SQL injection and second the SQL connection not need to repeat so many time. Too many code and select not need please check the follow.
<?php
$conn = new mysqli(HOST, USER, PASS, DBNAME);
$insert_usuarios = $conn->prepare(" INSERT INTO usuarios ( userEmail ) VALUES ( ? ) ");
$insert_usuarios->bind_param( "s", $userEmail);
$insert_rolesUsuarios = $conn->prepare(" INSERT INTO rolesUsuarios ( userID, nombreRol ) VALUES ( ?, ? ) ");
$insert_rolesUsuarios->bind_param( "is", $userID, $nombreRol);
if(isset($_POST['email'])) {
$userEmail = $_POST['email'];
if (!$insert_usuarios->execute()) { // ERROR
echo('Error'); // OR ACTION THAT YOU LIKE
} else { // SUCCESS
$userID = $insert_usuarios->insert_id; // LAST ID INSERT
$nombreRol = 'REGISTERED';
if (!$insert_rolesUsuarios->execute()) { // ERROR
echo('Error'); // OR ACTION THAT YOU LIKE
} else { // SUCCESS
echo('Done!');
}
}
}
?>
Cheers!!!
Yet another cleanup of your code, following your code style and convention =)
//Create User
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$email = strip_tags($_POST['email']);
$query = 'INSERT INTO usuarios (userEmail) VALUES (?)';
$stmt = mysqli_prepare($conectar, $query);
mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt); //execute query
$userID = mysqli_insert_id($conectar);
//assign a role to the newly created user
$query = "INSERT INTO rolesUsuarios (userID, nombreRol) VALUES (?, 'registered')";
$stmt = mysqli_prepare($conectar, $query);
mysqli_stmt_bind_param($stmt, 's', $userID);
mysqli_stmt_execute($stmt); //execute query
var_dump($userID);
tell me, what did you will get in the end?
Ok .. Here is the thing. I want to list users logged on and change their status when logged out. This works perfect. I created a table for that called tblaudit_users. The existing users I SELECT from a tbl_users table.
What I want, is that if an user already exists in the tblaudit_users table it will UPDATE the LastTimeSeen time with NOW(). But instead of updating that record, it creates a new record. This way the table will grow and grow and I want to avoid that. The code I use for this looks like:
+++++++++++++++++++
$ipaddress = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' AND active = '1' LIMIT 1");
$query->execute();
foreach($query->fetchAll(PDO::FETCH_OBJ) as $value){
$duplicate = $value->username;
}
if($duplicate != 1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($duplicate = 1){
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE username = '{$username}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
I am lost and searched many websites/pages to solve this so hopefully someone here can help me? Thanks in advance !!
UPDATE:
I've tried the below with no result.
+++++
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
Ok. I altered my query and code a little:
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' LIMIT 1");
$query->execute();
if($query){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
} else {
header('Location: index.php');
die();
}
}
I also added a UNIQUE key called pid (primary id). Still not working.
Base on http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html, don't use 'set' in update syntax
example from the page:
INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;
Several issues:
You test on $query, but that is your statement object, which also will be valid even if you have no records returned from the select statement;
There can be issues accessing a second prepared statement before making sure the previous one is closed or at least has all its records fetched;
There is a syntax error in the insert statement (set should not be there);
For the insert ... on duplicate key update to work, the values you provide must include the unique key;
SQL injection vulnerability;
Unnecessary split of select and insert: this can be done in one statement
You can write your test using num_rows(). To get a correct count call store_result(). Also it is good practice to close a statement before issuing the next one:
$query = $db->prepare("SELECT * FROM tblaudit_users
WHERE username = '{$username}' LIMIT 1");
$query->execute();
$query->store_result();
if($query->num_rows()){
$query->close();
// etc...
However, this whole query is unnecessary when you do insert ... on duplicate key update: there is no need to first check with a select whether that user actually exists. That is all done by the insert ... on duplicate key update statement.
Error in INSERT
The syntax for ON DUPLICATE KEY UPDATE should not have the word SET following it.
Prevent SQL Injection
Although you use prepared statements (good!), you still inject strings into your SQL statements (bad!). One of the advantages of prepared statements is that you can use arguments to your query without actually injecting strings into the SQL string, using bind_param():
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district,
gemeente, ipaddress, LastTimeSeen, status)
VALUES (?, ?, ?, ?, ?, ?, NOW(), '1')
ON DUPLICATE KEY UPDATE LastTimeSeen = NOW(), status = '1'
");
$insert->bind_param("ssssss", $userId, $username, $achternaam,
$district, $gemeente, $ipaddress);
$insert->execute();
This way you avoid SQL injection.
Make sure that user_id has a unique constraint in the tblaudit_users. It does not help to have another (auto_increment) field as primary key. It must be one of the fields you are inserting values for.
The above code no longer uses $query. You don't need it.
I found the issue
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE user_id = '{$userId}' LIMIT 1");
$query->execute();
if($query->rowcount()<1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($query->rowcount()>0) {
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE user_id = '{$userId}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
Instead of using $username in my query, I choose $userId and it works.
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
$fname = addslashes($fname);
$lname = addslashes($lname);
$dob = addslashes($dob);
$email = $_POST['email'];
$sql =
"INSERT INTO subscriber
(fname, lname, dob)
VALUES
('".$fname."', '".$lname."', '".$dob."')
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");
I am getting error in sql query "insertion error". Query is inserting data into DB after removing WHERE statement. What is the error.
You can't use where in an insert statement. You might be thinking of an update instead?
$sql = "update subscriber set fname='".$fname."', lname = '".$lname."', dob = '".$dob."' WHERE email='".$email."'";
If your email is a unique value, you can also combine an insert with an update like this:
insert into
subscriber (fname, lname, dob, email)
values ('".$fname."', '".$lname."', '".$dob."', '".$email."')
on duplicate key update set fname='".$fname."', lname='".$lname."', dob='".$dob."'
This second syntax will insert a row if there isn't one with a matching email (again, this has to be set to a unique constraint on the table) and if there is one there already, it will update the data to the values you passed it.
Basically INSERT statement cannot have where. The only time INSERT statement can have where is when using INSERT INTO...SELECT is used.
The only syntax for select statement are
INSERT INTO TableName VALUES (val1, val2, ..., colN)
and
INSERT INTO TableName (col1, col2) VALUES (val1, val2)
The other one is the
INSERT INTO tableName (col1, col2)
SELECT col1, col2
FROM tableX
WHERE ....
basically what it does is all the records that were selected will be inserted on another table (can be the same table also).
One more thing, Use PDO or MYSQLI
Example of using PDO extension:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
?>
this will allow you to insert records with single quotes.
Oops !!!! You cannot use a WHERE clause with INSERT statement ..
If you are targeting a particular row then please use UPDATE
$sql = "Update subscriber set fname = '".$fname."' , lname = '".$lname."' , dob = '".$dob."'
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");