创建新对象php并插入mysql

时间:2018-05-03 20:35:35

标签: php mysql pdo

目标是:

    A POST request to this script should create a new company object and thus 
    a new row in the company table and associated company address table.

目前,我已正确使用以下内容:

$randomname="1";
$randomdescription="Bill is going to work at this company";
$randomad="123 Main Street";
$randomad2="N/A";
$randomcity="Cincinnati";
$randomstate="Ohio";
$randomzip="45205";
$completedesc=$randomname." ". $randomdescription." ".$randomad." ". $randomad2." ".$randomcity." ".$randomstate." ".$randomzip;
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO company (name, description)
    VALUES ('$randomname', '$completedesc')";
    // use exec() because no results are returned
    $conn->exec($sql);
   $data= "New record created successfully";
   $data = json_encode($data, JSON_PRETTY_PRINT);
   echo $data;
    }
catch(PDOException $e)
    {
     $data= "company error". $sql . "<br>" . $e->getMessage();
   $data = json_encode($data, JSON_PRETTY_PRINT);
   echo $data;
    }
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO company_address (company_id, address,address_2,city,state,zip)
    VALUES ('$randomname','$randomad','$randomad2','$randomcity','$randomstate','$randomzip')";
    // use exec() because no results are returned
    $conn->exec($sql);
   $data= "New record created successfully into company address";
   $data = json_encode($data, JSON_PRETTY_PRINT);
   echo $data;
    }
catch(PDOException $e)
    {
   $data= "company address error". $sql . "<br>" . $e->getMessage();;
   $data = json_encode($data, JSON_PRETTY_PRINT);
   echo $data;
    }    

我最挣扎的问题是“创建一个新的公司对象”。现在我不相信我的代码使用的是对象。是否有一种简单的方法来制作一个对象,以便我可以执行插入。

0 个答案:

没有答案