I want to be able for members to add more info (location, story) to their profile and also update their password if needed.
For that I use the following snippet:
$query = mysql_query("
INSERT INTO
members (location, story)
VALUES
('$location', '$story')
WHERE
username='$user'
ON DUPLICATE KEY UPDATE
hash = '$password',
location='$location',
story='$story'
");
This does not work with the "WHERE" part, but if I remove it then the data just gets filled into an empty record, not the user record. How do I properly use the WHERE part in this snippet, so the correct user profile is updated?
I have searched up and down the internet and this website, but not found a single solution, which surprises me as this seems to be a very common question?
Does anyone know how to solve this problem?
Thanks in advance!
First, mysql is deprecated, you should use mysqli.
Second, make sure you escape your values before entering them in queries. mysql_real_escape_string() is a bare minimum.
Third, INSERT / ON DUPLICATE KEY UPDATE does not accept WHERE clause.
It's use is for avoid duplicating keys.
For a simple user signup or whatever, you could avoid using IDs / auto increment and use username as primary key. But for this you'd need MyISAM or MySQL 5.6+ in order to have fulltext indexing, and in general, this is recommended.
But in this use case, your location and story would be always overwritten.
If this is what you want, you can try whatever I've written in the previous paragraph.
You can use a INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE construct like
INSERT INTO
members (location, story)
SELECT '$location', '$story'
FROM table_name
WHERE username='$user'
ON DUPLICATE KEY UPDATE
hash = '$password',
location='$location',
story='$story'
Ok, I was finally able to solve this problem on my own. For anyone who is interested, here is the code:
// if user entered location
if (!empty($_POST['location']))
{
// if database row empty
if ($row['location'] == " ")
{
mysql_query("INSERT INTO members (location) VALUES ('".$location."') WHERE username='".$user."'");
}
// if database row not empty
else
{
mysql_query("UPDATE members SET location='".$location."' WHERE username='".$user."'");
}
}
// if user entered story
if (!empty($_POST['story']))
{
// if database row empty
if ($row['story'] == " ")
{
mysql_query("INSERT INTO members (story) VALUES ('".$story."') WHERE username='".$user."'");
}
// if database row not empty
else
{
mysql_query("UPDATE members SET story='".$story."' WHERE username='".$user."'");
}
}
Related
I have a table where user can input dates. It correctly goes to database and Replace the previous input and display in the table.
Now I want to store all the user's inputs in database and display only the last input. I have a button called update.
I believe that it is something with this update button. Hope You can help me to solve this. Please help. Thanks
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE `fiber`.`fiberexcel` SET Quotation11='$_POST[A12]',
ApprovalJFSRequest13='$_POST[A14]',
ApprovalJFSReceived15='$_POST[A16]',
JFSDone17='$_POST[A18]',
OFNtoSAQ19='$_POST[A20]',
ApprovalDrawing21='$_POST[A22]',
TechEvaluation23='$_POST[A24]' ,
AllQuotationsRecieved25='$_POST[A26]' ,
MailConfirmationWorkStart27='$_POST[A28]',
POReceived28='$_POST[A29]',
WorkApprovalRequest30='$_POST[A31]',
WorkApprovalReceived32='$_POST[A33]',
IBWStarted34='$_POST[A35]',
IBWCompleted36='$_POST[A37]',
HandOverContractor38='$_POST[A39]',
RequestAuthority40='$_POST[A41]',
EstimateReceivedDialog42='$_POST[A43]',
SystemPRRequested44='$_POST[A45]',
SystemPODone46='$_POST[A47]',
DocumentToFIN48='$_POST[A49]',
PaymentFin50='$_POST[A51]',
PaymentContractor52='$_POST[A53]',
PaymentAuthority54='$_POST[A55]',
OSPWorkStart56='$_POST[A57]',
OSPWorkComplete58='$_POST[A59]',
TestingCompleted60='$_POST[A61]',
Remarks65='$_POST[Remarks]'
WHERE `fiberexcel`.`SiteID0`='$_POST[hidden]'";
//echo($UpdateQuery);
mysqli_query($conn, $UpdateQuery);
};
First at all you have to change UPDATE query to INSERT query, make that primary key to be autoincrement as well. After that you can simply do
ORDER BY DATE_TO_ORDER LIMIT 1,1;
this will give you only 1st record which is actually newest insert to database.
And please dont use $_POST directly in your query because your code is now SQL injectable. Make new variables for each post and then insert them in query.
I really recommend you to use PDO prepared statements.
By 'change UPDATE to INSERT':
UPDATE QUERY:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
INSERT QUERY:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
I a trying to add column id which will be a primary key with auto increment properties. So i execute this SQL query:
ALTER TABLE `user_info` ADD `id` INT NULL AUTO_INCREMENT PRIMARY KEY FIRST ;
The column is created successfully and even creates id for the already existing data.
But i am unable to insert anything inside the table anymore.
<?php
require "init.php";
$name=$_POST["user"];
$user_email=$_POST["user_email"];
$user_pass=$_POST["user_pass"];
$sql_query="SELECT * FROM user_info WHERE user_email='$user_email'";
$check=mysqli_fetch_array(mysqli_query($con,$sql_query));
if(isset($check)){
$response["success"]=false;
$response["message"]="Email already exists";
echo json_encode($response);
}else{
$sql_query="insert into user_info values('$name','$user_email','$user_pass');";
if(mysqli_query($con,$sql_query)){
//echo "<h3> Data Insert success</h3>";
$response["success"]=true;
$response["message"]="Registration successful";
echo json_encode($response);
}
else{
$response["success"]=false;
$response["message"]="Registration unsuccessful";
echo json_encode($response);
}
}
?>
I googled around and found out that i could insert 0 or null in place of my id.
I purposefully read that :
In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows. The database will supply a value for you.
The code works well when i drop column id but when i add it, i get response as Registration unsuccessful within my json.
The workarounds from here or here did not seem to solve my problem.
What am i missing?
You have four columns in your table now, however you only provide three values. Checking mysqli_error would give you an error message telling you this.
You can either change your SQL to send NULL for the id which will create an appropriate id:
insert into user_info values(null, 'Foo','Foo#example.com','password');
Or, even better is to tell MySQL which columns you are targeting. This means in the future that if you add columns your SQL wont break:
insert into user_info (name,email, password)
values('Foo','Foo#example.com','password');
Note: There is some issues with your code. You are vulnerable to SQL injection - if someone sends a malicious value it could run SQL commands you don't intend.
Additionally storing passwords in plain text is not a good idea. You should be hashing them with a secure algorithm. See: http://php.net/manual/en/faq.passwords.php
Your INSERT syntax was correct before you added an ID column on first place:
$sql_query="insert into user_info values('$name','$user_email','$user_pass');";
But now you should specify the columns prior to the VALUES :
$sql_query="insert into user_info (name,email, password) values('$name','$user_email','$user_pass');";
For my employee's table, an e-mail is a unique field. When I insert a new employee, I check on the existance of the email. If it already exists, you get an error message:
$selectquery ="SELECT * FROM employee WHERE empemail='$empemail'";
$selectresult=mysql_query($selectquery) or die("query fout " . mysql_error() );
if(mysql_num_rows($selectresult)==1)
{
$errormsgnewemployee = '<p id=notification>The email you entered already exists.</p>';
}
But how to do it when UPDATING a field? Because if I update an employees data (without changing his mail), it will not let me, because the email already exists. All I can think of it is to UPDATE first, check then if there are 2 records, if there are 2, update it back as it was before.
Is this a good approach or is there a better solution?
EDIT
My own solution is to UPDATE the table having a unique index on the table and using the query error:
if (mysql_error())
{
$errormsgnewemployee = '<p id=notification>Update failed. Please check if the email you entered already exists.</p>';
}
Because, why else would the user have error if it's not for the only unique field? In all other cases the update would succeed.
You can use the same solution, you just need to "fetch this email address, but not mine" to check if there are any other users using it.
Eg. Before the update, do something like this:
SELECT 1 FROM employee WHERE empemail = '$empemail' AND id != '$myid';
Should only return rows where the email belongs to someone else.
On a side note, there are potential security issues with interpolating variables into SQL queries like that - you shouldn't do it. And the mysql_* functions are being deprecated should be replaced with PDO or mysqli alternatives.
I would recommend you to use INSERT ... ON DUPLICATE UPDATE ... sql construction. Take a deeper look at manual.
So your query could be the following:
INSERT INTO employee (email, first_name, last_name, ...)
VALUES ('employee_email#example.com', 'nik', 'smtih', ...)
ON DUPLICATE UPDATE
first_name = 'nik',
last_name = 'smith',
...
Pay attention that INSERT part of this query will fail due to UNIQUE KEY constraint, that is why the second part of the query, ON DUPLICATE UPDATE, will be executed and the data will be updated instead of inserting.
been working all day on something and can't seem to get this right...
I have a key generation script in PHP that runs some if statements, selects a license, creates a key, inserts it into the database and then emails the user the output.
The key is inserting into the database fine, and the email even sends fine with the key in it. The variable for email is $email, and is declared at this point, because it gets used down below this query to send an email (which sends). However, I can't get this UDPATE query to work in between the two (yes, the key is already generated and inserted by now):
$username = $email;
mysql_query("UPDATE keys SET username='".$username."' WHERE key='".$userkey."'");
Username is varchar, 255.
HELP!
KEY is a reserved word in MySQL (e.g. PRIMARY KEY).
If you're going to use it as an identifier, you will have to surround the name with `backticks` in every query.
mysql_query("UPDATE `keys` SET username='".$username."' WHERE `key`='".$userkey."'");
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
Both key and keys are reserved words in MySQL. You need to escape both with backticks:
mysql_query("UPDATE `keys` SET username='".$username."' WHERE `key`='".$userkey."'");
I have values which use the GET method to send URL variables to a PHP page using Ajax.
On the page, I have:
$value=$_GET["q"];
$id=$_GET["id"];
$mod=$_GET["mod"];
I started out using the UPDATE SET method to modify values in a mySQL database.
I used: $num_rows= mysql_num_rows($result);
With an If Else statement to either Insert the values (if not there) or Update the column "Attribute"
But this was very inconsistant and often would not UPDATE, and there developed several duplicate values (even though if($num_rows > 0){ (WHERE Object_ID = '".$mod."' AND Type='".$id."') it SHOULD NOT have inserted, but it did.)
So I switched to this:
$sql="SELECT * FROM Attributes WHERE Object_ID = '".$mod."' AND Type='".$id."'";
$result = mysql_query($sql);
mysql_query("DELETE FROM Attributes WHERE Object_ID = '".$mod."' AND Type = '".$id."'");
mysql_query("INSERT INTO Attributes (Object_ID, Type, Attribute)
VALUES ('".$mod."', '".$id."', '".$value."')");
I know, really bad idea. But Even this method doesn't always insert the values correctly.
I know that the variables are getting to the page, because the response would be written in a div using innerHTML, and it always showed up correctly.
How can I ensure that the values are ALWAYS updated/inserted in the database?
Why not run a SELECT COUNT(*) for the condition and check what that returns and based on that run your UPDATE or INSERT?
i am really confused what is wrong with your database operation but the only way to ensure is to send back response from your php script to ajax.
It can be json or simple text informing you that which action was requested and what is performed. Depending on the response you can adjust what you want.
You have to query the table to find out if the id already exists there or not if it exits then write an Update Query i.e.
$update = "update tbl_name set column=value where id = $_GET['id']"
and if the id does not exist then use the insert
$insert = "Insert into ......"
hope this solves your issue. And Further more you have to echo out the response here in either a string format or a some other value which you will get in the success method of $.Ajax.
No need to query the database to see if the data exists already. As long as you have good data, you can delete the row every time. If the row doesn't exist, the DELETE does nothing.
Run these two queries every time, and you will be fine.
mysql_query("DELETE FROM Attributes WHERE Object_ID = '$mod' AND Type='$id'");
mysql_query("INSERT INTO Attributes (Object_ID, Type, Attribute) VALUES ('$mod', '$id', '$value'");
And please at a minimum, before you do anything with $_GET, run those through mysql_real_escape_string first. You should probably be doing more checking just to make sure that the values passed in are valid.
$value=mysql_real_escape_string($_GET["q"]);
$id=mysql_real_escape_string($_GET["id"]);
$mod=mysql_real_escape_string($_GET["mod"]);