Question:
php problem - insert into database, update if exists?
Craig Lee
2011-05-04 13:56:02 UTC
hello, amateur php craftsman here with an annoying problem :(

basically i'm making a site and i've created a user profile, so once the fields have been filled in they insert into the sql database, which is fine. my problem is, when the same fields are filled in again by the same user, instead of updating the database a new row is created

here is my code:

if ($submit=='Update'){
if ($name&&$age&&$location){
require_once("db_connect.php");
if($db_server){
mysql_select_db("a200492680.profiles");
$query = "INSERT INTO a200492680.profiles (name, age, location, facebook, experience, bands, movies, books, other) VALUES ('$name', '$age', '$location', '$facebook', '$experience', '$bands', '$movies', '$books', '$other')";
mysql_query($query) or die("User insert failed. " . mysql_error() . "
" . $query);
$message = "Profile has been updated!

View your profile";
}else{
}else{
$message = "Error: could not connect to the database.";
}
require_once("db_close.php");
}else{
$message = "Please fill your name, age and location!";
}
}

i believe i need to make use of "INSERT INTO", but i'm not really sure how to do this or where it should go... all help would be greatly appreciated!
Four answers:
Crefelean Nicolae
2011-05-04 14:52:32 UTC
INSERT is used to add new rows in your tables

UPDATE is used to update one or more rows inside your tables



But the biggest of your problems is the lack of security, which will allow bad guys to create you so many issues you will be discouraged in programming for the web. The security basics you need to understand is:



1. Never assume the data sent by users is SAFE.

2. Always filter the data sent by users so you can make sure (at a certain level) they are sending valid data.

3. Only store filtered data inside your database.



What you need at this point is to learn basic security skills with PHP and basic MySQL usage.



There are many ways to do secure code and you will use different methods as you learn. Here's a great course on PHP & MySQL that is still freely available on YouTube, thanks to SitePoint:



http://www.youtube.com/watch?v=SKdof1MECqQ&playnext=1&list=PL37726087193091B2



Now regarding your problem, you need to understand how MySQL works. There are basically three things you can do with data:



1. You can INSERT data inside a table

2. You can UPDATE existing data inside a table

3. You can DELETE data from tables



What you did was only INSERT, which is why you ended up with several rows with the same data. You will have to make use of UPDATE. The syntax is actually simple:



UPDATE table_name SET field_name1='new_value', field_name2='another_value' WHERE this_field='certain_value'



What's important here is to notice there are two things to pay attention to:



1. field names and values

2. WHAT condition to use to update



Reading your code I noticed you didn't use uniquely identifiable data in that table of yours, which will make it hard to update your table contents. This is easily fixed by using an ID per row. Here's a good structure for your table.



CREATE TABLE profiles (

user_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,

user_name VARCHAR(50) NOT NULL,

user_age VARCHAR(3),

user_location VARCHAR(100),

user_facebook VARCHAR(50),

user_experience VARCHAR(50),

user_bands VARCHAR(250),

user_movies VARCHAR(250),

user_books VARCHAR(250),

user_other VARCHAR(250),

PRIMARY KEY (user_id)

) ENGINE = MyISAM;



Now you will have a unique ID for every user inside your profiles table. Updating a user will require an UPDATE query as I mentioned above. There's a trick with using unique IDs in MySQL tables. Adding new rows inside your table doesn't require you to specify the field name at all. So this will work and the user_id value will be automatically generated by the server:



INSERT INTO profiles (user_name, user_age, user_location) VALUES('Cody', '20', 'New York');



The query will work. The thing is when you define a column as AUTO_INCREMENT, MySQL will start with numer 1 as the first row's value then that value will automatically be incremented as you add more rows.



Just to make it clear: as an example, after you executed the INSERT query above you will have this data inside the new table:



1, 'Cody', '20', 'New York'



When you will have to update.. let's say the location... you will have to execute a script like this:



UPDATE profiles SET user_location='Manhattan' WHERE user_id=1



Don't forget to look at that course. They will remove it probably at the end of this month because they moved their courses to a new (private) site. There's a lot of good information on the web but videos are more friendly and it might help you better. Good luck!
Nik
2011-05-05 11:01:19 UTC
Instead of writing an essay liek soem appear to have done below is a script I use for browser detection it checks DB if a match exists it updates it if it doesn't it creates it glean from it what you will.



$browser_name= "MSIE";

$version = "7";

$sql = ("SELECT * FROM $TB WHERE browser = '$browser_name' AND version = '$version'");

$result = mysql_query($sql);

$count = mysql_num_rows($result);

if($count == 1)

{

$mysql = "UPDATE $TB SET amount = amount+1

WHERE browser='$browser_name' AND version='$version'";

mysql_query($mysql);

exit();

}

else

{

$mysql = "INSERT INTO $TB (browser, version, amount)

VALUES ('$browser_name', '$version', '1')";

mysql_query($mysql);

exit();

}







Like I mentioned your going to need to clean the code out as there is probably going to be a lot you don't need.
Tasm
2011-05-04 14:11:37 UTC
UPDATE a200492680.profiles

SET name=$name, age=$age....

WHERE username=$username and password=$password



You can look up a record by a primary key, in this case I used a double key username and password. If the username passwords match then you can update the record, otherwise insert a new one.
Chandresh Upadhyay
2014-05-28 22:37:56 UTC



include "myconnection/myconnection.php";

?>






$rollno="";

$name="";

$maths="";

$science="";

$english="";



if(isset($_REQUEST["umid"])==true)

{

$umid=$_GET["umid"];



$ucmd=Select("select * from marksheet where mid='$umid'");



$urow=mysql_fetch_array($ucmd);



$rollno=$urow["rollno"];

$name=$urow["name"];

$maths=$urow["maths"];

$science=$urow["science"];

$english=$urow["english"];



}



?>










if(isset($_REQUEST["mid"])==true)

{

$mid=$_GET["mid"];



Delete("delete from marksheet where mid='$mid'");

header("location:all_in_one.php");

}



?>

















Untitled Document















































































Roll No::-

readonly="readonly"value="" />

Name::-
Maths::-
Science::-
English::-



if(isset($_REQUEST["umid"])==true)

{

?>








}

else

{

?>






}



?>


if(isset($_REQUEST["cancel"])==true)

{

header("location:all_in_one.php");



}



?>


if(isset($_REQUEST["update"])==true)

{

$r=$_POST["rollno"];

$n=$_POST["name"];

$m=$_POST["maths"];

$s=$_POST["science"];

$e=$_POST["english"];



Update("update marksheet set name='$n',maths='$m',science='$s',english='$e' where rollno='$r' ");

header("location:all_in_one.php");

}



?>







































$cmd=Select("select * from marksheet order by rollno");



while($row=mysql_fetch_array($cmd))

{

?>
























}



?>

Roll NoNameMathsScienceEnglishDeleteEdit
">Delete ">Edit



if(isset($_REQUEST["insert"])==true)

{

$r=$_POST["rollno"];

$n=$_POST["name"];

$m=$_POST["maths"];

$s=$_POST["science"];

$e=$_POST["english"];



Insert("insert into marksheet(rollno,name,maths,science,english) values('$r','$n','$m,','$s','$e')");





header("location:all_in_one.php");

}



?>









This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...