我如何获得正确的工作pdo服务器副本的代码

问题描述 投票:0回答:1

我是pdo做的新手,并且正在尝试将我的mysqli代码转换为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;
    }
    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服务器,这是我的代码看起来像代码:

    <?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方法我的代码不会输出结果,当一个查询被发送到($ _SESSION [“user_name”])要更新到我的数据库,我不知道为什么它不输出结果因为我一个新的pdo语句初学者我相信我在此之后会好起来的。

任何人都可以弄清楚为什么我的代码会将记录插入数据库?

php pdo prepared-statement statements
1个回答
2
投票

我坚信使用正确的代码缩进可以更容易地找到错误 - 发布的代码很难“按原样”阅读,并且发现了许多小错误并在下面突出显示。

如果您在代码周围使用try/catch块,您应该会发现更容易找到代码失败的特定点 - prepared statements常见的失败因此使用prepare方法的返回值作为抛出新异常的逻辑测试下面。

希望能帮助到你

<?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() );
    }

?>

再看看你原来的以及我在阅读你的评论之后提出的建议并迅速将以下内容放在一起〜或许略有不同的逻辑,但我认为仍然遵循原文。

我试图将prepare方法调用移动到任何循环之外(因为它们应该是)以及bindParam调用,重新使用$stmt对象名称,但确保$stmt对象在使用后关闭。

问题仍然存在 - sql中的loading是什么 - 如果它是一个占位符它需要什么值以及该值来自何处?

<?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() );
    }

?>
© www.soinside.com 2019 - 2024. All rights reserved.