2017-02-25 1 views
-2

안녕하세요, 하나의 함수에서 마지막 삽입 된 ID를 가져올 수 있지만 어떻게 그 함수의 외부에있을 때 정의되지 않은 변수로 표시되는 것처럼 다른 함수에서 사용할 수 있습니다.하나의 함수에서 lastInsertID를 가져와 다른 함수에서 사용하는 방법은 무엇입니까? PDO

감사

편집

: class.user.php

public function one($first) 
    { 
     try 
     { 
      $stmt = $this->db->prepare("INSERT INTO table1(first) VALUES(:first)"); 
      $stmt->bindParam(':first', $first); 
      $stmt->execute(); 

      $newId = $this->db->lastInsertId(); 

      return $stmt; 
      return $newId; 

     } 
     catch(PDOException $e) 
     { 
      echo $e->getMessage(); 
     } 
    } 

    public function two($array, $newID) 
    { 
     try 
     { 
      foreach($array as $arrayText){ 
       $this->db->beginTransaction(); 
       $stmt = $this->db->prepare("INSERT INTO table2(arrayText, table1_id) VALUES(:array, :newId)"); 
       $stmt->bindParam(':array', $arrayText); 
       $stmt->bindParam(':newId', $newId); 
       $stmt->execute(); 



       $this->db->commit(); 

      } 

      return $stmt; 
     } 
     catch(PDOException $e) 
     { 
      echo $e->getMessage(); 
     } 
    } 

php code 

if(isset($_POST['btn'])) 
{ 
    $first = trim($_POST['first']); 
    $array = $_POST['array']; 


    if($user->one($first) && $user->two($array, $newId)) 
    { 
     Print '<script>alert("Added to database");</script>'; //Prompts the user 
    } 

} 

답변

0

반환 첫 번째 함수에 return 문을 사용하여이 값에서 코드, 다음, 다른에서이 함수를 호출합니다.

<?php 
function returnValue() { 
    $someVar = 'hello'; 
    return $someVar; //or just 'hello' instead 
} 

function sayHello() { 
    echo returnValue(); //or 
    $helloText = returnValue(); // $helloText stores 'hello' string now 
} 

는 두 return 문장 하나 하나를 사용할 수 없습니다. 귀하의 코드 값이 $stmt이지만, $newId은 반환되지 않습니다. 2 개의 값을 반환하려면 배열을 만들어야합니다.

예 :

기능이()에서
<?php 
return array($stmt, $newId); 

지금 바로 one($first)

+0

Wolen처럼 수익을 사용할 수 있습니다 전화 - 내 lastInsertID은 내가 돌아올 수 있어요 $ NEWID로 저장됩니다 첫 번째 기능. 두 번째 함수에서해야합니까 $ newID2 = functionOne ($ newID); ? 감사합니다 – liquidtabs

+0

첫 번째 게시물을 편집하여 코드를 표시 할 수 있습니까? 나는 그것에 대해 살펴보고 내 대답을 편집 할 것이다. – Wolen

+0

지금 코드를 편집했습니다. – liquidtabs

0

는이

<?php 
function myfunction() 
{ 
    $var='My variable'; 
    return $var; 
} 

echo myfunction(); 
관련 문제