Article

Dr Design - Javascript to PHP

Page: 1 2 3 Next

Variable Assignment Blues

Hello Doctor,
I have a quick question for you. I am new to PHP programming and have quickly found myself stuck. After connecting to a MySQL database through PHP, I am using the following PHP code to insert rows into an existing table...

   // If an artist has been submitted,  
   // add them to the database.  
   if ($addArtist == "Add") {  
     $sql = "INSERT INTO Artists SET  
     Name='$AddName',  
     bio='$AddBio';";  
     if (@mysql_query($sql)) {  
       echo("Artist Added");  
     } else {  
       echo("<p>Error adding submitted order: " .  
            mysql_error() . "</p>");  
 
     }  
   }

However, I need to also add rows into a different table under the same database at the same time. I have had no success with adding it this way (only one sql statement is recognized, not both)...

   // If an artist has been submitted,  
   // add it them the database.  
   if ($addArtist == "Add") {  
     $sql = "INSERT INTO Artists SET  
     Name='$AddName',  
     bio='$AddBio'";  
     $sql = "INSERT INTO Pictures SET  
     fileSRC='$AddPicture'";  
     if (@mysql_query($sql)) {  
       echo("Artist Added");  
     } else {  
       echo("<p>Error adding submitted order: " .  
            mysql_error() . "</p>");  
     }  
   }

I've looked everywhere and have not found a solution. Please let me know if you can help.
Thank you,
David

David, it always makes my heart rejoice to hear of someone finding the path to open source enlightenment and wisdom. You will be a master of PHP in no time!

Here is the problem with your second code example. When you assign your second query string to the variable $sql, this will "overwrite" the previous value of the variable, which is the first query string you assigned. Here's an example:

$myString = "foo";  
$myString = "bar";  
echo $myString;

This will output:
bar

However, if I write:
$myString = "foo";  
echo $myString;  
echo '<br>';  
$myString = "bar";  
echo $myString;

This will output:
foo  
bar

Back in your code, you might want to try something like this:

if ($addArtist == "Add") {  
 
  // first insert the record into Artists  
  $sql = "INSERT INTO Artists SET  
       Name='$AddName',  
       bio='$AddBio'";  
 
  if (@mysql_query($sql)) {  
     echo("Artist Added");  
  } else {  
     echo("<p>Error adding submitted order: " .  
           mysql_error() . "</p>");  
  }  
       
  // next insert the record to Pictures  
  $sql = "INSERT INTO Pictures SET  
      fileSRC='$AddPicture'";  
 
  if (@mysql_query($sql)) {  
     echo("Picture Added");  
  } else {  
     echo("<p>Error adding submitted order: " .  
            mysql_error() . "</p>");  
  }        
}

That should do it!

If you liked this article, share the love:
Print-Friendly Version Suggest an Article