从一个数据库中选择并使用匹配的行更新到另一个

时间:2017-03-28 14:19:45

标签: php mysqli

选择数据库值并更新到具有相同ID的另一个数据库:  我得到的错误是哪里 试图获得非对象的属性 我怎么能实现它有没有解决方案??

   $servername = "localhost";
   $username = "root";
   $password = "pass";
   $dbname = "db1";
   $dbname2="db2";


   $conn = new mysqli($servername, $username, $password, $dbname);

   if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
   } 


   $conn2 = new mysqli($servername, $username, $password, $dbname2);

   if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
   } 

   $sql = "SELECT * FROM affiliates";
   $result = $conn->query($sql);

   if ($result->num_rows > 0) {
   //output data of each row

      while($row = $result->fetch_assoc()) {
            echo "from db1 id: " . $row["id"]. "publish " .$row["publishinsuppliercontants"]. "<br>";

      $sql2 = "UPDATE a1_affilates_cstm SET publish_in_supplier_contacts_c=".$row["publishinsuppliercontants"]." WHERE id_c=".$row["id"]."";
     $result2 = $conn2->query($sql2);

    $sql2 = "SELECT * FROM a1_affilates_cstm WHERE id_c = ". $row["id"]."";

    $result2=mysqli_query($conn2,$sql2) or die mysqli_error($conn2);
    $row1 = mysqli_fetch_array($result2);
   ///check whether inserted ...
           echo "from db2 id: " . $row1["id_c"]. " - publish: ".row1["publish_in_supplier_contacts_c"]. " <br>";

       }
   } else {
       echo "0 results";
   }

1 个答案:

答案 0 :(得分:0)

看起来你没有得到结果对象。 SELECT查询是否成功?

在使用结果对象进行make操作之前,需要检查select查询状态/结果。

例如在您的情况下:

$sql = "SELECT * FROM affiliates";
if ( $result = $conn->query($sql) ) {
  if ($result->num_rows > 0) {
     ... some logic ...

来自PHP mysqli manual

“失败时返回FALSE。对于成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询,mysqli_query()将返回一个mysqli_result对象。对于其他成功的查询,mysqli_query()将返回TRUE。”