$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");
Related
My project is a simple attendance record for my small school. I am submitting entry and exit logs through an online form, and writing them to a database with this query:
$sql = "INSERT INTO table_one (first_name, last_name, location)
VALUES ('$first_name', '$last_name', '$location')";
It works fine - so far so good.
At the same moment I would like to write some of this submitted information to another table in the same database. This query works fine by itself when standing alone:
$sql = "UPDATE another_table SET location='$location' WHERE first_name='$first_name'";
However my problem is how to make them both happen, in sequence. Just listing them successively doesn't work:
$sql = "INSERT INTO table_one (first_name, last_name, location) VALUES
('$first_name', '$last_name', '$location')";
$sql = "UPDATE personnel_table SET location='$location' WHERE
first_name='$first_name'";
What is the most effective (and safest) way to combine both commands so that they execute together?
You need to use transaction so that if one query fail, both should fail. Only if both query success that it will add/update the database.
$db= new PDO('mysql:host=localhost; dbname=test', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$db->beginTransaction();
$sh = $db->prepare("INSERT INTO table_one (first_name, last_name, location) VALUES (?, ?, ?)");
$sh->execute([$first_name, $last_name, $location]);
$sh = $db->prepare("UPDATE personnel_table SET location=? WHERE first_name=?");
$sh->execute([$location, $first_name]);
$db->commit();
} catch ( Exception $e ) {
$db->rollBack();
}
for this problem you must use trigger option in database (forEx mysql).
trigger is like an event. when insert in on table automate update second table. forEx:
mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));
Query OK, 0 rows affected (0.03 sec)
mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account
FOR EACH ROW SET #sum = #sum + NEW.amount;
Query OK, 0 rows affected (0.01 sec)
this trigger that is a object for account table. update #sum variable and then use for update second table
You can create a trigger like below:
delimiter #
create trigger after_ins_trig after insert on first_table
for each row begin
UPDATE second_table
SET new.location=old.location
WHERE new.first_name=old.first_name end#
delimiter ;
You can check id in where clause.
Why not this:
Table: teraz
Create Table: CREATE TABLE `teraz` (
`col` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
//
<?php
$last_name = 77;
$conn = new mysqli('localhost','root','','shopping');
$sql = "INSERT INTO teraz VALUES ('{$last_name}')";
$sql2 = "SELECT * FROM teraz";
$conn->query($sql);
$result = $conn->query($sql2);
$x = $result->fetch_assoc() ;
echo $x['col'];
?>
?
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.
So I have 3 tables: donor, blood_type, user_account. I am trying to populate the donor table which contains user_id and blood_id, but there is no join between the blood_group and the user_account table so I tried this, but it didn't work. Can someone please tell what I am doing wrong? I am very new to php and databases.
<?php
if(isset($_POST['submit'])) {
$conn = mysqli_connect("localhost", "root" , "");
if(!$conn) {
die("Cannot connect: ");
}
mysqli_select_db($conn,"blood_bank_project");
$sql = "INSERT INTO user_account(username, password) VALUES ('$_POST[user]', '$_POST[psw]');";
$sql .="INSERT INTO donor(first_name,last_name,email_add,gender, birthday, telephone, city, last_donation,user_id, blood_id)VALUES('$_POST[fname]', '$_POST[lname]', '$_POST[email]', '$_POST[gender]', '$_POST[Birthday]', '$_POST[Telephone]', '$_POST[city]', '$_POST[lastdonation]')";
$sql .="UPDATE donor SET blood_id = (SELECT blood_id from blood_type where blood_group= '$_POST[bloodgroup]');";
$sql .="UPDATE donor SET user_id = (SELECT user_id from user_account where username= '$_POST[user]')";
if(mysqli_multi_query($conn, $sql)){
echo'executed';
}
}
?>
You can use a SELECT clause to produce the values for an INSERT. In this case, you can use that to select the appropriate values from the other tables.
INSERT INTO donor (user_id, blood_id, first_name,last_name,email_add,gender, birthday, telephone, city, last_donation)
SELECT u.user_id, b.blood_id,
'$_POST[fname]', '$_POST[lname]', '$_POST[email]', '$_POST[gender]', '$_POST[Birthday]', '$_POST[Telephone]', '$_POST[city]', '$_POST[lastdonation]'
FROM user_accounts AS u
CROSS JOIN blood_type AS b
WHERE u.username = '$_POST[user]' AND b.blood_group= '$_POST[bloodgroup]'
I also strongly recommend you use prepared queries instead of substituting $_POST variables, as the latter subjects you to SQL-injection. I also recommend against using mysqli_multi_query -- it's rarely needed and only makes checking for success harder. If you insert into user_accounts using a separate query, you can then use mysqli_insert_id($conn) to get the user_id assigned when you inserted into user_accounts, instead of using the above JOIN. You can also use the MySQL built-in function LAST_INSERT_ID() to get it.
$stmt = mysqli_prepare($conn, "INSERT INTO user_account(username, password) VALUES (?, ?);") or die("Can't prepare user_account query: " . mysqli_error($conn));
mysqli_stmt_bind_param($stmt, "ss", $_POST['user'], $_POST['psw']);
mysqli_execute($stmt);
$stmt2 = mysqli_prepare($conn, "
INSERT INTO donor (user_id, blood_id, first_name,last_name,email_add,gender, birthday, telephone, city, last_donation)
SELECT LAST_INSERT_ID(), b.blood_id, ?, ?, ?, ?, ?, ?, ?, ?
FROM blood_type AS b
WHERE b.blood_group= ?") or die ("Can't prepare donor query: " . mysqli_error($conn));
mysqli_stmt_bind_param($stmt2, "sssssssss", $_POST['fname'], $_POST['lname'], $_POST['email'], $_POST['gender'], $_POST['Birthday'], $_POST['Telephone'], $_POST['city'], $_POST['lastdonation'], $_POST['bloodgroup']);
mysqli_execute($stmt2);
theres a few things wrong with that code snippet:
Line 15: You've got a rogue 'w' at the start of the line before your $sql variable
All of your $_POST'ed parameters need to be in the format $_POST['parameter'] (Missing quotes, remember to escape your already quoted ones in places)
The where clause sub-select query in line 14 is selecting from a table that does not exist (blood_type)
I guess what your trying to achieve is a mapping between 'user_account' and 'donor' of which you may be better either storing a foreign key in the user account table of the 'donor_id', or a matrix/mapping table that links the two together.
The matrix/mapping table would hold the primary key date from both user_account and donor to create your matrix.
You can then get to either table information from the other knowing just one side of the information.
I'd also make sure your escaping your inbound variables in your queries to prevent any SQL Injection attacks (see here)
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.
Is this possible if I want to insert some data into two tables simultaneously?
But at table2 I'm just insert selected item, not like table1 which insert all data.
This the separate query:
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
Can I insert COUNT(model) at table2?
I have found some script, could I use this?
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$result = mysql_query($sql,$conn);
if(isset($model))
{
$model = mysql_insert_id($conn);
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
$result = mysql_query($sql,$conn);
}
mysql_free_result($result);
The simple answer is no - there is no way to insert data into two tables in one command. Pretty sure your second chuck of script is not what you are looking for.
Generally problems like this are solved by ONE of these methods depending on your exact need:
Creating a view to represent the second table
Creating a trigger to do the insert into table2
Using transactions to ensure that either both inserts are successful or both are rolled back.
Create a stored procedure that does both inserts.
Hope this helps
//if you want to insert the same as first table
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";
$result = #mysql_query($qry2);
//or if you want to insert certain parts of table one
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (two) VALUES('$two')";
$result = #mysql_query($qry2);
//i know it looks too good to be right, but it works and you can keep adding query's just change the
"$qry"-number and number in #mysql_query($qry"")
its cant be done in one statment,
if the tables is create by innodb engine , you can use transaction to sure that the data insert to 2 tables
<?php
if(isset($_POST['register'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$website = $_POST['website'];
if($username == NULL OR $password == NULL OR $email == NULL OR $website == NULL) {
$final_report2.= "ALERT - Please complete all fields!";
} else {
$create_chat_user = mysql_query("INSERT INTO `chat_members` (`id` , `name` , `pass`) VALUES('' , '$username' , '$password')");
$create_member = mysql_query("INSERT INTO `members` (`id`,`username`, `password`, `email`, `website`) VALUES ('','$username','$password','$email','$website')");
$final_report2.="<meta http-equiv='Refresh' content='0; URL=login.php'>";
}
}
?>
you can use something like this. it works.
In general, here's how you post data from one form into two tables:
<?php
$dbhost="server_name";
$dbuser="database_user_name";
$dbpass="database_password";
$dbname="database_name";
$con=mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to the database:' . mysql_error());
$mysql_select_db($dbname, $con);
$sql="INSERT INTO table1 (table1id, columnA, columnB)
VALUES (' ', '$_POST[columnA value]','$_POST[columnB value]')";
mysql_query($sql);
$lastid=mysql_insert_id();
$sql2=INSERT INTO table2 (table1id, table2id, columnA, columnB)
VALUES ($lastid, ' ', '$_POST[columnA value]','$_POST[columnB value]')";
//tableid1 & tableid2 are auto-incrementing primary keys
mysql_query($sql2);
mysql_close($con);
?>
//this example shows how to insert data from a form into multiples tables, I have not shown any security measures