-3

I'm trying to learn php. I decided to do a simple system as practice. I am able to add data to my database. Now, I wanted to prevent the user from adding data if the id of the project already exists in the database. I am also able to do that. My problem is the text always shows that the transaction is'Successful' though it's not. Any response will be appreciated. Any response will be appreciated. Here is my code:

$query = "select * from setup_project where spin='$sspin' order by title"; 

 $numresults=mysql_query($query);
 $numrows=mysql_num_rows($numresults);



if ($numrows == 0)
 $query = mysql_query("insert into setup_project value ('$sspin','$stitle','$sfirm_id','$sequip','$sdateapp','$samnt','$srem');");



else{
 echo "SPIN already Exists!";
}

$message = "Successfully Added Project  to Database!";  



?>
<br><br><br><br><br><br>
<center><font size="6"><? echo "$message" ?></font></center>
DEADPOOL
  • 83
  • 2
  • 15
  • 3
    Your `$message` variable is set to 'Successful...' outside the `if...else` block, so it will be set regardless of the `if` condition –  Jan 20 '15 at 02:11
  • Oh and be careful about SQL injections as well, your current code is vulnerable. Take a look here : http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php for secure examples for both mysqli and PDO. –  Jan 20 '15 at 06:51

1 Answers1

0

This is easier:

  $query = mysql_query("insert into setup_project value ('$sspin','$stitle','$sfirm_id','$sequip','$sdateapp','$samnt','$srem');");


 if (mysql_errno==0){
    $message = "Successfully Added Project  to Database!";
  }
  elseif (mysql_errno==1062){
    echo "SPIN already Exists!";
  }

many times I want to INSERT and if the INSERT fails I follow the insert with an UPDATE.

Then check the UPDATE with $affected = mysql_affected_rows();

 if (mysql_errno==0){
   $message = "Successfully Added Project  to Database!";
 }
 elseif (mysql_errno==1062){
   UPDATE setup_project SET (...) VALUES(...) WHERE ????
   $affected = mysql_affected_rows();
   if ($affected == 0){
     echo "Record was updated";
   }
   else{
     echo 'Record Exists, No Updates';
   }
 }
 else{
   echo mysql_error();
 }
Misunderstood
  • 5,534
  • 1
  • 18
  • 25