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');";
Related
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."'");
}
}
The logical error here is that the mysql_insert_id() always starts at 0 and I want it to increment from 1 and so on. I wonder why it gives me an error: Duplicate entry '0' for key 'PRIMARY'. I don't want to duplicate the key I just want to add it.
eg. 1 2 3 4.
Here's my code:
$insertID=mysql_insert_id(); //I want this to start at 1
if (isset($_POST['lastname']) && isset($_POST['firstname']) && isset($_POST['address']))
{
$sql="INSERT INTO contact(idnum, lastname, firstname, address) values ('$insertID','$_POST[lastname]','$_POST[firstname]','$_POST[address]')";
if(!mysql_query($sql, $con))
{
die("Error: " .mysql_error());
}
echo "Saved...";
}
You seem to be misunderstanding what mysql_insert_id() actually does.
It doesn't generate an ID for you to use in your next query. It tells you the ID that MySQL generated in the last query. So...
If your table isn't using an auto-generated ID, there's no generated ID for the database to return.
You're asking for the generated ID before you insert anything.
If you're using a manual ID, then it's the responsibility of your application to generate a unique one. If you're using a database-generated ID, then remove the ID from your INSERT statement and get the ID from the database after it's been generated.
Also, side note, your code is wide open to SQL injection vulnerabilities.
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"]);