PHP Mysqli查询不返回任何值或错误

时间:2018-08-04 06:52:29

标签: php mysqli

我正在尝试创建一个订单跟踪系统,并具有以下查询

    //create the order variable and assign it the value that the user has entered
            $order = $_POST["order"];
$query = mysqli_query($link,"SELECT shipping_status FROM orders WHERE code_ticket = $order");
  if($result = mysqli_fetch_assoc($query)){
//the status value
     $status = $result['shipping_status'];
  }
  else{
    $status = "Order Not yet placed";
  }

我的问题是查询是即使我提供db中的值,我也要执行else部分而不是if部分。 我可能做错了什么?

2 个答案:

答案 0 :(得分:1)

检查$query是否等于false。如果是这样,则使用mysqli_error()来检查错误:

$query = mysqli_query($link, "YOUR SQL QUERY");
if(!$query) {
    echo "There is an error with db:" . mysqli_error($link);
    exit;
}

//continue your code

答案 1 :(得分:1)

在开发此系统时,明智的做法是尽早采用最佳实践,而不是以后采用-在这种情况下,我指的是sql injection,可惜上面的代码容易受到攻击。我对上述内容的猜测是嵌入变量-code_ticket = $order周围缺少引号-如果$order是字符串,则需要引号。话虽这么简单,但要注入prepared statement是前进的方向。我迅速改写了您的代码,以说明如何使用try/catch块和prepared statement来有望解决此问题并使代码更安全。

<?php

    if( $link && $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST["order"] ) ){
        try{

            $order = $_POST['order'];

            /* basic query with placeholder for variable */
            $sql = 'select `shipping_status` from `orders` where `code_ticket` = ?';

            /* create the prepared statement object */
            $stmt = $link->prepare( $sql );

            /* if the query failed raise an exception to indicate failure */
            if( !$stmt ) throw new Exception( 'Failed to prepare sql' );

            /* so far so good. Bind placeholder to a variable */
            $stmt->bind_param( 's', $order );

            /* execute the query */
            $result = $stmt->execute();

            /* deal with recordset */
            if( !$result ) throw new Exception( 'No results: Order not placed' );
            else {

                /* bind column data to an output variable */
                $stmt->bind_result( $status );

                /* fetch the records */
                $stmt->fetch();

                /* do something with output variable */
                printf( 'Shipping Status: %s', $status );


                $stmt->free_result();
                $stmt->close();

            }
        }catch( Exception $e ){
            exit( $e->getMessage() );
        }
    }

?>