2017-12-30 30 views
0

の正しい作業PDOサーバーのコピーを入手できますどのように私は多くのlessionと読書に行うPDOに新しいですが、PDOサーバーコードに以下の私のmysqliのコードを変換しようとしています:私は私のコード

すべての変更しようとし
<?php 
    include "init.php"; 
    session_start(); 
    if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { 
    echo "<h2 align='center'>Your shopping cart is empty</h2>"; 
    exit(); 
    } 
    elseif (!isset($_SESSION["user_name"]) || count($_SESSION["user_name"]) < 1) { 
    $book=RAND(1000000, 2000000); 
    foreach ($_SESSION["cart_array"] as $each_item) { 
    $item_id = $each_item["item_id"]; 
    $qty = $each_item["quantity"]; 
    if($item_id =='sms') 
    { 
    $msg = $each_item["msg"]; 
    $qty = 1; 
    } 
    mysqli_query($conn, "insert into books (book, item_name, quantity, msg) values ('$book', '$item_id', '$qty', '$msg')") or die(mysqli_error()); 
    } 
    echo "<div class='info_post'>YOUR SHOPPING BOOKED CODE IS ' . $book . ' KINDLY COPY TO ANY DEALER NEAR YOU TO COMFIRM<br/ ></div><form action='mail.php' method='POST'><b> Mail me:</b><br/ > 
    <input type='text' name='book' size='23'> <input type='submit' name='submit' value='SEND EMAIL'></form>"; 
    unset($_SESSION["cart_array"]); 
    } 
    elseif (isset($_SESSION["user_name"]) || count($_SESSION["user_name"]) > 1) { 
    $username=$_SESSION["user_name"]; 
    $query=mysqli_query($conn, "select * from users where username='$username'"); 
    if($row = mysqli_fetch_array($query)) 
    { 
    $id=$row["id"]; 
    $username=$row["username"]; 
    $ip=$row["ip"]; 
    $ban=$row["validated"]; 
    $balance=$row["balance"]; 
    $buy="$cartTotal"; 
    { 
    if($ban != "0") 
    { 
    echo "<div class='info_post'><b>$buy $balance $ban</div>"; 
    } 
    } 
    if($buy<$balance) 
    { 
    $redut = $balance-$buy; 
    $go = mysqli_query($conn,"update users set balance='$redut' where id='$id'"); 
    if($go) 
    { 
    $book=RAND(1000000, 2000000); 
    foreach ($_SESSION["cart_array"] as $tem) { 
    $m = $tem["item_id"]; 
    $p = $tem["quantity"]; 
    $gob = mysqli_query($conn, "insert into books (book, item_name, quantity) values ('$book', '$m', '$p')") or die(mysqli_error()); 
    $msg = "Transation of $totalquantity products cost of $cartTotal occur on your account with ticket id $book"; 
    $time = date('Y-m-d H:i:s'); 
    mysqli_query($conn, "insert into details (poster, message, date) values ('$username', '$msg', '$time')") or die(mysqli_error()); 
    if($gob) 
    { 
    echo "jamjamja $book"; 
    unset($_SESSION["cart_array"]); 
    } 
    else 
    { 
    echo "nootjo"; 
    } 
    } 
    } 
    } 
    } 
    } 
    ?> 

ここではPDOサーバにするコードは、コードのようにどのように私のコードを見ている:これまでにクエリが($ _SESSION [ "USER_NAMEに送信されたときに、PDO方法私のコードを使用すると、出力結果がないことを言って申し訳ありません

<?php 
    include "init.php"; 
    session_start(); 
    if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { 
    echo "<h2 align='center'>Your shopping cart is empty</h2>"; 
    exit(); 
    } 
    elseif (!isset($_SESSION["user_name"]) || count($_SESSION["user_name"]) < 1) { 
    $book=RAND(1000000, 2000000); 
    foreach ($_SESSION["cart_array"] as $each_item) { 
    $item_id = $each_item["item_id"]; 
    $qty = $each_item["quantity"]; 
    if($item_id =='sms') 
    { 
    $msg = $each_item["msg"]; 
    $qty = 1; 
    } 
    $me = $conn->prepare("insert into books (book,item_name,quantity,msg) values (:book, :m, :p, :d)"); 
    $me->bindParam(':book', $book); 
     $me->bindParam(':m', $item_id); 
     $me->bindParam(':p', $quantity); 
     $me->binParam(':d', $msg); 
    $me->execute(); 
    } 
    echo "<div class='info_post'>YOUR SHOPPING BOOKED CODE IS ' . $book . ' KINDLY COPY TO ANY DEALER NEAR YOU TO COMFIRM<br/ ></div><form action='mail.php' method='POST'><b> Mail me:</b><br/ > 
    <input type='text' name='book' size='23'> <input type='submit' name='submit' value='SEND EMAIL'></form>"; 
    unset($_SESSION["cart_array"]); 
    } 
    elseif (isset($_SESSION["user_name"]) || count($_SESSION["user_name"]) > 1) { 
    $username=$_SESSION["user_name"]; 
    $records = $conn->prepare("select * from users where username= :book AND used = loading"); 
    $records->bindParam(':book', $username); 
     $records->execute(); 

    if($row = $records->fetch(PDO::FETCH_BOTH)){ 
    $id=$row["id"]; 
    $username=$row["username"]; 
    $ip=$row["ip"]; 
    $ban=$row["validated"]; 
    $balance=$row["balance"]; 
    if($ban != "0") 
    { 
    echo "<div class='info_post'><b>$buy $balance $ban</div>"; 
    } 
    if($buy<=$balance) 
    { 
    $redut = $balance-$buy; 
    $go = $conn->prepare("update users set balance= :redut' where id= :id"); 
    $go->bindParam(':redut', $redut); 
     $go->bindParam(':id', $id); 
     $go = $go->execute(); 
    } 
    if($go) 
    { 
    $book=RAND(1000000, 2000000); 
    foreach ($_SESSION["cart_array"] as $tem) { 
    $m = $tem["item_id"]; 
    $p = $tem["quantity"]; 
    $gob = $conn->prepare("insert into books (book, item_name, quantity) values (:book, :m, :p)"); $gob->bindParam(':book', $book); 
     $gob->bindParam(':m', $m); 
     $gob->bindParam(':p', $p); 
     $gob = $gob->execute(); 
    $msg = "Transation of $totalquantity products cost of $cartTotal occur on your account with ticket id $book"; 
    $time = date('Y-m-d H:i:s'); 
    $ty = $conn->prepare("insert into details (poster, message, date) values (:username, :msg, :time)"); 
    $ty = bindParam(':username', $username); 
    $ty = bindParam(':msg', $msg); 
    $ty = bindParam(':time', $time); 
    if($gob) 
    { 
    echo "jamjamja $book"; 
    unset($_SESSION["cart_array"]); 
    } 
    else 
    { 
    echo "nootjo"; 
    } 
    } 
    } 
    } 
    } 
    ?> 

午前"])私のデータベースに更新されると私はなぜそれが結果を出力しない理由を把握できない新しいpdoステートメントが頼むインナー私は私たちがこの後に大丈夫だと信じています。

私のコードがレコードをデータベースに挿入するのはなぜですか?

+1

エラー報告をオンにすると、 '$ conn = new PDO(...); 'が開始されていないことがわかります。 – ino

+1

あなたの質問の1つに問題があります: 'used = loading'。 – Progrock

+0

ループして複数の挿入を行っている場合は、準備済みのステートメントを再利用します。 – Progrock

答えて

2

適切なコードインデントを使用すると、エラーを見つけるのが簡単になると確信しています。投稿されたコードは「そのまま」と読みにくく、以下にいくつかの小さな間違いが見つかって強調されています。

あなたはそれが簡単にコードが失敗した時に、特定のポイントを見つけるために見つける必要があり、コードの周りtry/catchブロックを使用した場合 - 一般的な失敗をするための論理テストとしてprepareメソッドの戻り値を使用して、したがってprepared statementsであります以下のような新しい例外をスローします。

はそれが

<?php 
    include "init.php"; 

    session_start(); 

    try{ 

     if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { 

      throw new Exception("<h2 align='center'>Your shopping cart is empty</h2>"); 

     } elseif(!isset($_SESSION["user_name"]) || count($_SESSION["user_name"]) < 1) { 

      $book = RAND(1000000, 2000000); 

      foreach($_SESSION["cart_array"] as $each_item) { 

       $item_id = $each_item["item_id"]; 
       $qty = $each_item["quantity"]; 
       $msg=''; #<--------- value?? 

       if($item_id == 'sms') { 
        $msg = $each_item["msg"]; 
        $qty = 1; 
       } 

       $me = $conn->prepare("insert into books (book,item_name,quantity,msg) values (:book, :m, :p, :d)"); 
       if(!$me)throw new Exception('Failed to prepare sql statement',1); 

       $me->bindParam(':book', $book); 
       $me->bindParam(':m', $item_id); 
       $me->bindParam(':p', $qty); #<-------- not quantity 
       $me->bindParam(':d', $msg); #<-------- bindParam not binParam 
       $me->execute(); 
      } 

      echo " 
      <div class='info_post'>YOUR SHOPPING BOOKED CODE IS ' . $book . ' KINDLY COPY TO ANY DEALER NEAR YOU TO COMFIRM<br/ ></div> 
      <form action='mail.php' method='POST'><b> Mail me:</b><br/ > 
       <input type='text' name='book' size='23'> 
       <input type='submit' name='submit' value='SEND EMAIL'> 
      </form>"; 

      unset($_SESSION["cart_array"]); 

     } elseif(isset($_SESSION["user_name"]) || count($_SESSION["user_name"]) > 1) { 

      $username = $_SESSION["user_name"]; 
      $records = $conn->prepare("select * from users where username= :book AND used = loading");  #<--------- loading?? an unbound parameter perhaps? 
      if(!$records)throw new Exception('Failed to prepare sql statement',2); 

      $records->bindParam(':book', $username); 

      #$records->bindParam(':loading', $loading);  #<---------- is there supposed to be a second bound parameter? 
      $records->execute(); 



      if ($row = $records->fetch(PDO::FETCH_BOTH)) { 

       $id = $row["id"]; 
       $username = $row["username"]; 
       $ip = $row["ip"]; 
       $ban = $row["validated"]; 
       $balance = $row["balance"]; 

       if ($ban != "0") { 
        echo "<div class='info_post'><b>$buy $balance $ban</div>"; 
       } 

       if ($buy <= $balance) { 
        $redut = $balance - $buy; 

        $go = $conn->prepare("update users set balance= :redut' where id=:id"); 
        if(!$go) throw new Exception('Failed to prepare sql statement',4); 

        $go->bindParam(':redut', $redut); 
        $go->bindParam(':id', $id); 
        $go = $go->execute(); 
       } 

       if ($go) { 

        $book = RAND(1000000, 2000000); 
        foreach($_SESSION["cart_array"] as $tem) { 

         $m = $tem["item_id"]; 
         $p = $tem["quantity"]; 

         $gob = $conn->prepare("insert into books (book, item_name, quantity) values (:book, :m, :p)"); 
         if(!$gob)throw new Exception('Failed to prepare sql statement',5); 

         $gob->bindParam(':book', $book); 
         $gob->bindParam(':m', $m); 
         $gob->bindParam(':p', $p); 
         $gob = $gob->execute(); 

         $msg = "Transation of $totalquantity products cost of $cartTotal occur on your account with ticket id $book"; 
         $time = date('Y-m-d H:i:s'); 

         $ty = $conn->prepare("insert into details (poster, message, date) values (:username, :msg, :time)"); 
         if(!$ty) throw new Exception('Failed to prepare sql statement',6); 

         $ty = bindParam(':username', $username); 
         $ty = bindParam(':msg', $msg); 
         $ty = bindParam(':time', $time); 

         if ($gob) { 
          echo "jamjamja $book"; 
          unset($_SESSION["cart_array"]); 
         } 
         else { 
          echo "nootjo"; 
         } 
        } 
       } 
      } else { 
       throw new Exception('No records found',3); 
      } 
     } 

    } catch(Exception $e){ 
     printf('Error: Code %d Message %s', $e->getCode(), $e->getMessage()); 
    } 

?> 

があなたの元で別の見ていたとの提案が、私はあなたのコメントを読んだ後、以前に作られたとすぐに、おそらく一緒に次〜わずかに異なるロジックを置くが、私はまだ次のだと思うホープ

元の。

Iはprepare方法は、再使用$stmtオブジェクト名、bindParamコールと共に(それらがあるべきであるように)任意のループの外に呼び出しが、$stmtオブジェクトが使用後に閉鎖された確保移動しようとしました。

質問がまだ残っています - loadingはsqlにあります - それはどのような値を取るか、その値はどこから派生したのですか?

<?php 

    include 'init.php'; 

    session_start(); 

    try{ 
     if(empty($_SESSION['cart_array'])){ 
      throw new Exception('<h2 align="center">Your shopping cart is empty</h2>'); 
     } else { 
      if(empty($_SESSION['user_name'])){ 
       $book = rand(1000000, 2000000); 

       /* Prepare SQL once outside the loop */ 
       $sql = 'insert into `books` (`book`,`item_name`, `quantity`, `msg`) values (:book, :item, :qty, :msg)'; 
       $stmt=$conn->prepare($sql); 
       if($stmt){ 

        /* bind placholders to variables */ 
        $stmt->bindParam(':book', $book); 
        $stmt->bindParam(':item', $id); 
        $stmt->bindParam(':qty', $qty); 
        $stmt->bindParam(':msg', $msg); 

        /* assign variables and execute inside loop */ 
        foreach($_SESSION['cart_array'] as $item) { 

         $id = $item['item_id']; 
         $qty = $item['quantity']; 
         $msg = ''; 

         if($id == 'sms') { 
          $msg = $item['msg']; 
          $qty = 1; 
         } 

         $stmt->execute(); 
        } 
        $stmt->closeCursor(); 



        echo " 
        <div class='info_post'> 
         YOUR SHOPPING BOOKED CODE IS ' . $book . ' KINDLY COPY TO ANY DEALER NEAR YOU TO COMFIRM 
         <br/ > 
        </div> 
        <form action='mail.php' method='POST'><b> Mail me:</b><br/ > 
         <input type='text' name='book' size='23'> 
         <input type='submit' name='submit' value='SEND EMAIL' /> 
        </form>"; 

        unset($_SESSION['cart_array']); 

       } else { 
        throw new Exception('Failed to prepare sql statement',1); 
       } 
      } else { 

       /* create and prepare sql */ 
       $sql='select * from `users` where `username`=:book'; 
       $stmt=$conn->prepare($sql); 

       /* bind parameters */ 
       if($stmt){ 

        $stmt->bindParam(':book', $username); 

        $username = $_SESSION['user_name']; 

        $result = $stmt->execute(); 

        if($result){ 

         $row = $stmt->fetch(PDO::FETCH_BOTH); 
         $stmt->closeCursor(); 

         if(!$row) throw new Exception('bad foo',3); 

         /* assign vars */ 
         $id   = $row['id']; 
         $username = $row['username']; 
         $ip   = $row['ip']; 
         $ban  = $row['validated']; 
         $balance = $row['balance']; 


         if($ban != "0") { 
          echo "<div class='info_post'><b>$buy $balance $ban</div>"; 
         } 

         if($buy <= $balance) { 
          $redut = $balance - $buy; 

          $sql='update `users` set `balance`=:redut where `id`=:id;'; 
          $stmt=$conn->prepare($sql); 

          if($stmt){ 
           $stmt->bindParam(':redut', $redut); 
           $stmt->bindParam(':id', $id); 

           $result = $stmt->execute(); 
           $stmt->closeCursor(); 

           if($result){ 

            $book = rand(1000000, 2000000); 

            $sql_insert_1='insert into `books` (`book`, `item_name`, `quantity`) values (:book, :name, :qty)'; 
            $stmt_insert_1=$conn->prepare($sql); 

            $sql_insert_2='insert into `details` (`poster`, `message`, `date`) values (:username, :msg, :time)'; 
            $stmt_insert_2=$conn->prepare($sql); 


            if($stmt_insert_1){ 
             $stmt_insert_1->bindParam(':book', $book); 
             $stmt_insert_1->bindParam(':name', $name); 
             $stmt_insert_1->bindParam(':qty', $qty); 
            } else { 
             throw new Exception('Failed to prepare sql statement',5); 
            } 


            if($stmt_insert_2){ 
             $stmt_insert_2->bindParam(':username', $username); 
             $stmt_insert_2->bindParam(':msg', $msg); 
             $stmt_insert_2->bindParam(':time', $time); 
            } else { 
             throw new Exception('Failed to prepare sql statement',6); 
            } 


            foreach($_SESSION['cart_array'] as $item) { 

             /* $book defined above - rand() */ 
             $name = $item['item_id']; 
             $qty = $item['quantity']; 

             /* $username defined earlier */ 
             $msg = "Transation of $totalquantity products cost of $cartTotal occur on your account with ticket id $book"; 
             $time = date('Y-m-d H:i:s'); 


             $result = $stmt_insert_1->execute(); 
             if(!$result)throw new Exception('insert failed',7); 

             $result = $stmt_insert_2->execute(); 
             if(!$result)throw new Exception('insert failed',8); 

            } 

            $stmt_insert_1->closeCursor(); 
            $stmt_insert_2->closeCursor(); 

            unset($_SESSION['cart_array']); 
           } 
          } else { 
           throw new Exception('Failed to prepare sql statement',4); 
          } 
         } 
        } 
       } else { 
        throw new Exception('Failed to prepare sql statement',2); 
       } 
      } 
     } 
    } catch(Exception $e){ 
     printf('Error: Code %d Message %s', $e->getCode(), $e->getMessage()); 
    } 

?> 
+0

最初の処理は期待通りにうまく動作しますが、$ _SESSION ["user_name"]にrecoreが存在する場合はページが処理されません – obinnak

+0

どこを意味していますか? – RamRaider

+0

私のコードラインにロードすることについては本当にありません。私はライトを見逃していると思いますが、私のコードではそれを取り除きます。私はそれを置く場所がなく、すべてのことは非常にうまく動作します。最初のステートメントは期待通りに動作しますが、レコードが存在する場合、$ _SESSION ['user_name']ページプロセスは訪問中ではなく、$ _SESSION ['cart_array']はこのプロセスの後に解除されません。 これは私のコードを配置する方法です それを参照してください:https://ideone.com/tQSQVX – obinnak