Jump to content

Update and Insert at the same time


cdoggg94

Recommended Posts

This was kind of thrown together, but is this on the right track ?

 

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO table_1 (FirstName, LastName, Age)
VALUES
('".$_POST[firstname]."','".$_POST[lastname]."','".$_POST[age]."')");

mysql_query("UPDATE Table_2 SET Age=".$_POST[age]."
WHERE  ID='".$_POST['id']."'");

mysql_close($con);
?>

This was kind of thrown together, but is this on the right track ?

 

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO table_1 (FirstName, LastName, Age)
VALUES
('".$_POST[firstname]."','".$_POST[lastname]."','".$_POST[age]."')");

mysql_query("UPDATE Table_2 SET Age=".$_POST[age]."
WHERE  ID='".$_POST['id']."'");

mysql_close($con);
?>

Yes. You don't really need to close mysql, and you should not use POST data straight into a database query.

By not using POST data straight into the query, do you mean to make variables out of the POST data then use those ?

 

Maybe that's a stupid question... :(

Not a stupid question, because I didn't explain why you shouldn't do it. :)

It's because you should sanitize the input so people can't do stupid things to your database by giving it data you don't expect. It opens up for hackers to easily take control over your database.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.