0

I have constructed a function where two queries are performed. Both of these queries insert data into two separate tables, data that is related to the registration of a user. In one table things like username,password are held and in the other table stuff like address, phone etc... Here is the function:

function register_biz_user($post,$connection)

    {
    $name=$connection-> real_escape_string($_POST['name']);
    $lastname= $connection->real_escape_string($_POST['lastname']);
    $pass_hashed = password::hash($_POST['password']); 

    $passwd= $connection->real_escape_string($pass_hashed);
    $buztype= $connection->real_escape_string($_POST['buztype']); 
    $usertype= $connection->real_escape_string($_POST['usertype']);
    $address= $connection->real_escape_string($_POST['address']);
    $city= $connection->real_escape_string($_POST['city']);
    $municipality= $connection->real_escape_string($_POST['municipality']);
    $url= $connection->real_escape_string($_POST['wwwaddress']);
    $email= $connection->real_escape_string($_POST['e-mail']);
    $phone= $connection->real_escape_string($_POST['phone']);
    $hash =$connection->real_escape_string(md5( rand(0,1000) ))  ;


      $connection->set_charset("utf8");

      $result1 = $connection->query("insert into users values
      (NULL,'" .$name. "','" .$lastname . "','".$email."','". $passwd."','".                   
      $hash."','". $usertype."')");

      if (!$result1) {
          throw new Exception('error');
         return false;                                         
         }



       else{$result2=$connection->query("insert into business_users values
           ('".$connection->insert_id."','" .$address."','".$url ."','".$phone. 
             "','".$city. "','".$municipality. "','".$buztype. "')");
           }
      if(!$result2)
      {  throw new Exception('error');
          return false;}

return true; }

And here is my problem: If you look at the code you might notice that there is the problem that the 1st query runs without problem and the second throws an exception or vice verca.

My point is that there is the danger that the db WILL have ONLY partial data of the registered user. The goal is that either both queries run successfully or none runs.

How I must write the above code such that I can achieve the above statement?

I hope I was clear enough.

4

1 回答 1

1

使用事务:http ://dev.mysql.com/doc/refman/5.0/en/commit.html

BEGIN
... queries ...
COMMIT or ROLLBACK

注意:“或反之亦然” - 这是不可能的。在这种情况下,第二个查询永远不会被执行。

笔记2:

  • 什么$post?好像没用过。
  • 你为什么不使用准备好的语句?逃避一切很容易出错。
  • 为什么你有一个程序界面,通过$connection?您应该拥有了解数据库连接的对象...您至少有 3 个不同层的混合代码...如果您打算创建 write-once-get-rid-of-code 但可能不是很好您必须维护数月/数年的项目的想法。
于 2013-09-03T20:44:02.527 回答