Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a web form that should store data into two different tables in the database. In my includes, I have a php file that performs the necessary queries. The web form should store two pieces of information: The xp value being submitted from the form into the users table, and the article id into the completed_quests table. Individually, the queries work exactly as they should. However, if I try to perform both queries together, only the first query is performed and the second one is ignored. How do I make it so that both queries run once the user hits the submit button?
(edit) I have updated the code. To clarify, there is other code in my php file that defines the variables used in these queries. These are simply the two queries I was trying to run and I needed to know how to run both queries as it seemed to be ignoring the second one (the update). It is now working, however I am running into an issue of the INSERT query creating duplicate entries.
(edit) I have updated the code again. I used an ON DUPLICATE KEY UPDATE to avoid duplicate entries in the table. I made sure that the user id was the primary key in the table and it is now functioning perfectly.
mysql_select_db("questroot_joomla", $con);
mysql_query("INSERT INTO arp2i_completed_quests (user_id, content_id) Values ($userId, $currentArticle)
ON DUPLICATE KEY UPDATE content_id=$currentArticle");
mysql_query( "UPDATE arp2i_users"
. " SET userxp= $userXp"
. " WHERE id = $userId");
mysql_close($con);
$sql = "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values ('$_POST[current_user]', '$_POST[current_article]')";
/* it's not in $sql ->> */ "UPDATE `arp2i_users`
SET `userxp`= '$_POST[xpValue]'
WHERE `id` = '$_POST[current_user]'";
Try this:
$sql = "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values
('$_POST[current_user]', '$_POST[current_article]');
UPDATE `arp2i_users`
SET `userxp`= '$_POST[xpValue]'
WHERE `id` = '$_POST[current_user]'";
A lot of people here are just answering as though you are using PHP and not a framework that already is designed to handle all this stuff for you and do it safely, including checking for injection etc. You use a framework to make it simpler and avoid doing unsafe things. The combination of JForm, JDatabaseQuery and other parts of the API will handle updating multiple tables just fine, you can see that all over the core. How you would do it depends on what you are doing, such as is it more like updating the profile table when you are saving user data or is it more like updating the assets table or creating a new tag when saving content. What you should do though is stop fighting the API and start using it to your advantage.
You can simply add many mysqli_* queries as you want :
mysqli_query($link, "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values ('".$_POST['current_user']."', '".$_POST['current_article']."')";
mysqli_query($link, "UPDATE `arp2i_users` SET `userxp`= '".$_POST['xpValue']."' WHERE `id` = '".$_POST['current_user']."'");
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
hi all i want to insert data into four tables how can i do.so far i write code to insert data into two tables .now am unable to insert data into four tables.please help me to do .below is my code
this code is am inserting data through post .i am inserting data into two tables perfectley but am unable to insert data into four tables .all the four tables have common id usr_id
$_POST = json_decode(file_get_contents('php://input'), true);
if (isset($_POST['nric'],$_POST['id'],$_POST['fullname'],$_POST['gender'],$_POST['password'],$_POST['address'],$_POST['postcode'],$_POST['state'],$_POST['contact1'],$_POST['email'])) {
global $db;
$db = mysqli_connect("localhost", "root", "", "asklms");
if($db === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$nric=mysqli_real_escape_string($db,$_POST["nric"]);
$id =(int)$_POST["id"]; $fullname=mysqli_real_escape_string($db,$_POST["fullname"]);
$gender=mysqli_real_escape_string($db,$_POST["gender"]);
$address=mysqli_real_escape_string($db,$_POST["address"]); $postcode=mysqli_real_escape_string($db,$_POST["postcode"]);
$state=mysqli_real_escape_string($db,$_POST["state"]); $expirydate=mysqli_real_escape_string($db,$_POST["expirydate"]); $contact1=mysqli_real_escape_string($db,$_POST["contact1"]); $email=mysqli_real_escape_string($db,$_POST["email"]);
query 1 to insert data into usr_data ::
$sql1 ="INSERT INTO usr_data (login,usr_id, firstname, gender, street, zipcode, country, phone_mobile, email) VALUES ('$_POST[nric]','$_POST[id]','$_POST[fullname]','$_POST[gender]','$_POST[address]','$_POST[postcode]','$_POST[state]','$_POST[contact1]','$_POST[email]')
ON DUPLICATE KEY UPDATE login='$_POST[nric]',usr_id='$_POST[id]',firstname='$_POST[fullname]',gender='$_POST[gender]',street='$_POST[address]',zipcode='$_POST[postcode]',country='$_POST[state]',phone_mobile='$_POST[contact1]',email='$_POST[email]'";
$sql ="INSERT INTO `object_data` ( `obj_id`, `type`, `owner`) VALUES ('$_POST[id]','usr','-1')
ON DUPLICATE KEY UPDATE obj_id='$_POST[id]',type='usr'
";
$sql2 ="INSERT INTO `udf_text` ( `obj_id`) VALUES ('$_POST[id]')
";
$sql3 ="INSERT INTO `role_data` ( `role_id`, `allow_register`, `assign_users`,`auth_mode`,`disk_quote`,`wsp_disk_quota`) VALUES ('$_POST[id]','0','0','default','0','0')
";
$update1 = mysqli_query($db,$sql1);
// dd($update1);
$update2 = mysqli_query($db,$sql);
$update3 =mysqli_query($db,$sql2);
$update4 =mysqli_query($db,$sql3);
i wrote like this but data inserting to only two tables
i want to insert data into four tables how can i do.so far i write code to insert data into two tables .now am unable to insert data into four tables.please help me to do i want to insert data into four tables how can i do.
If you are able to insert data into two columns, then you should also able to do that for other two as well.
But you said it's not happening.
In this scenario, there is a high chance that you may have some error in your statements like there is some mistake typing of column names of table names etc.
So go through your statements again.
One more remedy is there, you make echo your query statements which are not working, and do paste them on the server in mysql directly.There you will be able to clearly see the errors.
Do let me know if you are able to see any error or do some inspection and be specify the problem.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm writting a HTML form for newsletter subscribers. So far the form ignores duplicates entries by making the subscriber_email field unique in the mysql table and using:
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')";
I'm trying to improve the form so it updates the other fields when the email already exists in the table, and if the email does not exists then it inserts a new record. For that I'm doing this (so far it works but I feel it's not the proper way to do it):
//HTML form variables----------------------------------------------------//
$subscriber_name = mysql_real_escape_string($_POST['subscriber_name']);
$subscriber_email = mysql_real_escape_string($_POST['subscriber_email']);
//Try update into DB---------------------------------------------------------//
$sqlUpdate =
"UPDATE newsletter_subscriber_popup
SET subscriber_name = '$subscriber_name'
WHERE subscriber_email = '$subscriber_email'";
if(!mysql_query($sqlUpdate)){
//Insert into DB--------------------------------------------------------//
$sqlInsert =
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')";
if(!mysql_query($sqlInsert)){
die('Error: ' .mysql_error());
}
}
The scripts works when the subscriber_email exists and it updates the other fields but it fails when it should insert a new record.
EDIT----------------------------
ON DUPLICATED KEY UPDATE is what I was looking for. The script now updates the other fields when the subscriber_email already exists, and insert a new record when the the subscriber_email does not exists.
//HTML form variables----------------------------------------------------//
$subscriber_name = mysql_real_escape_string($_POST['subscriber_name']);
$subscriber_email = mysql_real_escape_string($_POST['subscriber_email']);
//Insert into DB--------------------------------------------------------//
$sqlName =
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')
ON DUPLICATE KEY UPDATE subscriber_name = '$subscriber_name'";
if(!mysql_query($sqlName)){
die('Error: ' .mysql_error());
}
Note: Thanks for all the advices about sql injection but the question wasn't about security.
INSERT .. ON DUPLICATE KEY UPDATE may be just what you are looking for. see https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
You need to have an unique constraint on subscriber_email though.
NO. It is not SQL-injection-proof. If somwone enters 'a or 1 = 1 ' as subscriber_email, he will update all of your entries. have a look on Wikipedia: SQL-Injection and PHP-Doc to prepared statements
First off, at least use sqli instead of sql. here is a good documentation on sql injection in PHP http://php.net/manual/en/security.database.sql-injection.php
Also, if you're not sure about the inputs that are coming from the user (e.g. email address), then you can use an email parser http://php.net/manual/en/ref.mailparse.php (server side). It's a good practice to validate the value on both client and server side.
Remember, more rules for the form entries means more security and thereby less sql injection vulnerability.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am creating a form that collects data and sends to a database using php, with a code snippet i got online.
$con=mysqli_connect("localhost","root","famakin","k");
if(mysqli_connect_errno())
{
echo"FailedtoconnecttoMySQL:".mysqli_connect_error();
}
$sql="INSERT INTO transactions(Username,Insured_Name,combined,Residential_Address,Telephone,Email,Make_Of_Car,Model,Engine_Number,Year_Of_Manufacture,Chassis_Number,Vehicle_Class,Colour,Registeration_Number,Product_Type,Premium,Policy_Number,Start_Date,Expiry_Date,Date_Begin,Type_Of_Insurance,Status, Transaction_id)VALUES('$_POST[Username]','$_POST[Insured_Name]','$_POST[combined]','$_POST[Residential_Address]','$_POST[Telephone]','$_POST[Email]','$_POST[Make_Of_Car]','$_POST[Model]','$_POST[Engine_Number]','$_POST[Year_Of_Manufacture]','$_POST[Chassis_Number]','$_POST[Vehicle_Class]','$_POST[Colour]','$_POST[Registeration_Number]','$_POST[Product_Type]','$_POST[Premium]','$_POST[Policy_Number]','$_POST[Date]','$_POST[Date_Expiry]','$_POST[Date_Begin]','$_POST[Type_Of_Insurance]','$_POST[Status]','$_POST[Transaction_id]')";
if(!mysqli_query($con,$sql))
{
die('Error:'.mysqli_error($con));
}
mysqli_close($con);
This works for inserting details into the database,but i want to check if for example the username in which i am inserting into the database exists,please how do i go about this with what i have already?
regards
There are two main approaches, essentially...
SELECT from the database before trying to INSERT. If the record is found by the SELECT, don't perform the INSERT and instead respond to the user accordingly.
Place a UNIQUE constraint on the column (or set of columns) which needs to be unique in the table. This would cause the INSERT to fail, and the code would have to catch and handle that failure and respond to the user accordingly.
The second option puts the responsibility squarely on the database itself, which is important if anything else if ever going to use that database and needs to maintain that same responsibility.
Also, and this is important, please note that your code is open to SQL injection attacks, which allows users to execute their own code on your server. You'll want to read up on that so you can protect your application.
Here, you can do it via mysqli_num_rows():
$username = mysqli_real_escape_string($con, $_POST['Username']);
$check_select = mysqli_query("SELECT * FROM `transactions` WHERE Username = '$username'");
$numrows=mysqli_num_rows($check_select);
if($numrows > 0){
// do something
}
else{
// do something else
}
Although there are other ways to do this, it is but one example.
You can avoid this by also setting your column(s) as UNIQUE.
By the way, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they much safer.
Just do a SELECT query before the INSERT. If a record with that username exists then don't insert the record.
Well before you insert one you want to query for it's existence (please refer to Google on how to "Select data from Database PHP").
If that select count(*) from Transactions.... where Username =.. returns something other than 0 the username is already taken.
Note: I have bigger concerns about the fact you include POST-Parameters directly into your SQL-Query string and recommend you read something about "SQL Injection PHP".
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've inserted into databases before but never used the 'where' feature. For some reason, it is not inserting, but dieing instead.
<?php
$member=$_SESSION['member'];
$SQL = "INSERT into members where name='$member'(money) VALUES ('100')";
mysql_query($SQL) or die("Could not insert money");
print "Money successfully inserted";
?>
This is not valid SQL:
INSERT into members where name='$member'(money) VALUES ('100')
I would assume something like this:
update `members` set `money`=100 where `name`='$member';
Rationale: (money) is a field and 100 is the value for money (since those 2 make the most sense from a INSERT INTO members (field) VALUES (value) syntax point of view).
Never die() with a fixed error message, especially when you can output the actual reason: ... or die(mysql_error()).
But yes, your problem is a syntax error. INSERT queries do NOT have a WHERE clause - where is used to filter records already in the database table. This makes no sense for a new record, because it's not IN the table to filtered in the first place.
You query should basically be just
INSERT into members (name, money) VALUES ('$member', '100')
And note that you are vulnerable to SQL injection attacks, and are using a deprecated/obsolete database interface.
If you want to change existing data, use the update command instead of insert.
You can't use WHERE clause with INSERT command
http://dev.mysql.com/doc/refman/5.0/en/insert.html
You have to do an update
<?php
$member=$_SESSION['member'];
$SQL = "UPDATE `members` SET `money`='100' WHERE `name`='$member'; ";
mysql_query($SQL) or die("Could not insert money");
print "Money successfully inserted";
?>
For inserting :
$SQL = "INSERT INTO members(money) VALUES ('100')";
MySQL INSERT Syntax does not support the WHERE clause. MySQL.com Insert Info
Are you actually trying to insert a new row, or update an existing 'member'? If update, then try:
UPDATE members SET money = 100, WHERE name='$member';
I got two tables. One is account, another is Interest.
One account can have multi Interests and It can be edited.
Now, the process is deleting all Interest of this account then insert these insterests.
The QUERY IS:
"DELETE FROM Interests WHERE account_id='$id'"
"INSERT INTO Interests (account_id, interest_name) VALUES('$id', '$name')"
I use the both query when user update their account, but the insert is fail, there is nothing insert into the table (ps. the interests_id is auto_increment and this was be counted) but there is nothing new in the table. When I comment out the delete query. The insert will be successful.
Does any one know what can i do?
If you want to update your table records, you will do update operation.
like this:
UPDATE TABLE_NAME SET FIELD_NAME = 'VARIABLE_NAME'
WHERE PRIMERY_FIELD_NAME = 'VARIABLE_NAME' ;
you did not have to use these two queries, if you want to update data simply use the updat query of mysql.use this:
<?php
$query = "UPDATE Interests SET interest_name = '".$name."' WHERE account_id = '".$id."'" ;
mysql_query($query);
?>
If you want to update your table records then you may execute update operation. It like following
UPDATE Interests
SET
interest_name = '$name'
WHERE
accountno = '$id' ;
Try it. You may solve your problem by this way.
If you have queries failing, you should capture the error and see what went wrong. In all MySQL APIs for PHP, a query that fails returns a status code to indicate this. Examples of checking this status code are easy to find in the docs. But most developers fail to check the status.
Use transactions to ensure that both changes succeed together or neither are applied.
How to Decide to use Database Transactions
Definition of a transaction in MySQL: http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_transaction
Syntax for starting and committing transactions in MySQL: http://dev.mysql.com/doc/refman/5.5/en/commit.html
You need to use InnoDB. MyISAM does not support transactions. http://dev.mysql.com/doc/refman/5.5/en/innodb-storage-engine.html
In PHP, you need to stop using the old ext/mysql API and start using MySQLi or PDO.
http://php.net/manual/en/mysqli.quickstart.transactions.php
http://php.net/manual/en/pdo.begintransaction.php
This happens because the query are treated as two single transaction, so the order of execution is not guaranteed.
The effect you are describing is because the insert is processed before delete, so the interests_id is auto-incremented properly, then the row is deleted by delete statement.
You should change the query logic or perform both queries in one single transaction.