Reputation: 599
Scenario:
I have got a client, php script and a MySQL database. I am sending information from the client to the database which the values include the name and favorite color. I have got 2 rows in MySQL database.
Name | Favorite Color
Johnny | Green
Where Name is a primary key.
Every time, the client would be sending both his name and favorite color. So if name (primary key) exist, it shows error. How should I set my php script to react if the client wants to update his favorite color? In other words, keep primary key but update favorite color.
script.php
<?php
mysql_connect("localhost","root","")
mysql_select_db("Information");
$name = mysql_real_escape_string($_POST["name"]);
$color = mysql_real_escape_string($_POST["color"]);
$sql=mysql_query("insert into Male (name, color) VALUES ('$name','$color')");
mysql_close();
Upvotes: 2
Views: 1971
Reputation: 188114
You are looking for the UPDATE
SQL statement. This will update an existing row:
$sql = mysql_query("UPDATE Male SET color = '$color' WHERE name = '$name'");
Alternatively you can use INSERT ... ON DUPLICATE KEY UPDATE.
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.
$sql = mysql_query("INSERT INTO Male (name, color) VALUES ('$name','$color')
ON DUPLICATE KEY UPDATE color = '$color'");
MySQL offers an SQL extension, namely REPLACE, which will insert a new row, if none exists.
$sql = mysql_query("REPLACE INTO Male (name, color) VALUES ('$name','$color')");
Upvotes: 1
Reputation: 13431
<?php
mysql_connect("localhost","root","")
mysql_select_db("Information");
$name = mysql_real_escape_string($_POST["name"]);
$color = mysql_real_escape_string($_POST["color"]);
$query = mysql_query("select name from Male where name = '$name'");
if(mysql_num_rows($query) > 0) {
mysql_query("update Male set color='$color' where name='$name'");
} else {
mysql_query("insert into Male (name, color) VALUES ('$name','$color')");
}
mysql.close();
?>
Upvotes: -1
Reputation: 3074
You'll want to modify your mysql_query with an update statement instead of insert. Something like this.
$name = mysql_real_escape_string($_POST["name"]);
$color = mysql_real_escape_string($_POST["color"]);
$sql=mysql_query("UPDATE Male SET color = '".$color."' WHERE name = '".$name."'");
mysql.close();
Upvotes: 0
Reputation: 2947
$sql=mysql_query("INSERT INTO Male (name, color) VALUES ('".$name."', '".$color."')
ON DUPLICATE KEY UPDATE color='".$color."'");
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
Upvotes: 8