这个PHP5源码在PHP7中不太好用

时间:2018-02-08 04:22:13

标签: php mysql

我想在亚马逊服务器上阅读MySQL并将结果发送到我的Unity程序。 PHP5中的PHP源代码在另一台服务器上工作,我将源代码复制到PHP7中的Amazon服务器上。

但是,每次运行此程序时,都会收到此错误消息 ' PHP Parse错误:语法错误,文件意外结束...行号。 51&#39 ;. 第51行是源头。

我是PHP的新手。我已经谷歌搜索了几天,并试图找出问题所在。但我找不到任何东西。

任何人都可以帮助我吗?任何建议将被认真考虑。 我的来源是......

<?php
$servername = 'localhost';
$username = 'root';
$password = '********';
$dbname = 'mysqldb';

$connect = mysqli_connect($servername, $username, $password, $dbname);
if ($connect == 0) {
    echo "SORRY SCORE SERVER CONNECTION ERROR";
} else {}

mysqli_select_db($connect, $dbname);

$User_Id2 = $_POST["User_Id"];
$User_Id = $User_Id2 + 0;

$sql = "select * from Users where User_Id = '".$User_Id."'";
$result = mysqli_query($connect, $sql);

$rows = array();
$return = array();
while($row = mysqli_fetch_array($result)) {
    $rows['User_Id'] = $row['User_Id'];
    $rows['Dia_Qty'] = $row['Dia_Qty'];
    $rows['Fighter_Info'] = $row['Fighter_Info'];
    $rows['InvBonus'] = $row['InvBonus'];

    array_push($return, $rows);
}

header("Content-type:application/json");
echo json_encode($return);

mysqli_close($connect);
?>

2 个答案:

答案 0 :(得分:0)

您的代码在我的服务器上使用PHP 7.0.22运行正常,所以我认为它必须是您的AWS服务器上的PHP配置错误,您是否尝试过运行像phpinfo()这样的简单脚本?

另外出于安全原因,最好不要在这里添加php结尾标记更多信息:

Why would one omit the close tag?

答案 1 :(得分:0)

似乎你的ajax(我想因为$_POST变量而存在一个)对于错误非常挑剔: - )

请注意,我不知道您是否以及如何制作ajax请求。所以我将自己引用到html页面中 script 标记内的ajax请求。

第一个问题:

如果您使用json_encode输出,例如据说将数据发送到ajax请求回调(“succes”,“error”等),然后你必须在exit();之后提供json_encode语句,以便停止执行更多的语句。这可能是您最初错误的原因:mysqli_close($connect);之前缺少退出语句。实际上,您不需要它,因为php在完成脚本处理后关闭每个连接(如getUsers.php)。此外,您不需要?>标记,正如@ Chico3001正确说的那样。

第二个问题:

由于if ($connect == 0)声明:

,您的代码仍然会发出通知
  

注意:类mysqli的对象无法转换为int in   第9行的/getUsers.php

要正确处理错误(包括数据库连接失败),请参阅thisthis。下面我也举一个例子。

第三个问题(取决于第二个问题:):

在通知发出后立即发出警告。

  

警告:无法修改标头信息 - 已发送的标头   (输出始于   /getUsers.php:9)in   /getUsers.php在线   32

这是因为之前的通知被打印在屏幕上 - 至少在我的测试中。

如果你在ajax请求代码中做了类似的事情,你可能已经看到了这些错误:

$.ajax({
    //...
    error: function (jqXHR, textStatus, errorThrown) {
        $('#messages').html(jqXHR.responseText);
    }
});

所以:

解决方案1(推荐):删除if ($connect == 0)语句并继续我提供的链接(关于PHP中的正确错误/异常处理)。见下面的例子。

解决方案2:替换

if ($connect == 0) {
    echo "SORRY SCORE SERVER CONNECTION ERROR";
} else {}

if (!$connect) {
    echo json_encode("SORRY SCORE SERVER CONNECTION ERROR");
    exit();
}

此外,我认为header(...)在你的情况下是不必要的。我不确定因为我不知道 Unity

建议和代码:

请注意,在我的示例中,所有系统导致的错误/异常(如数据库连接失败,准备/执行sql语句失败等)将仅在日志文件中可见。只有开发人员才能看到,而不是网站的用户。应该如此。用户永远不应该看到“抱歉,连接失败”之类的错误。应该向用户显示的错误(例如“请提供用户ID ”,“找不到用户ID的用户”等)应该是直接echo - ed,或thrown&amp;在“特定” try-catch 块中处理(就像我在getUsers.php中所做的那样)。

现在,因为我抛出并捕获异常(正如我在getUsers.php中所做的两次,例如使用两个 try-catch 块),回显的消息将自动发送到“ 错误 jquery.ajax()的功能,不是“成功”< / strong>功能。如果您使用标题401和echo - 而不是第一个 try-catch 块,您可以实现完全相同的功能 - 例如: - 像这样:

if (!isset($_POST['userId']) || empty($_POST['userId'])) {
    header('HTTP/1.1 401 Unauthorized');
    echo 'Please provide the user ID.';
    exit();
}

或者,而不是第二个 try-catch块

if (!$users) {
    header('HTTP/1.1 404 No Content');
    echo 'No users found for the provided user id.';
    exit();
}

同样的事情:消息将被发送到 jquery.ajax()的“错误”功能。重点是:任何响应头(请参阅thisthis)从服务器发送到客户端(例如浏览器),状态代码不是2xx,这使得ajax请求调用“错误” “回调 - 而非”成功“之一。在上面的代码中,标题发送401或404代码,例如不同于2xx(200等)。

因此,您可以选择使用 try-catch 块(就像我在下面的getUsers.php中所做的那样),或者选择如上所述的header-echo对(也在getUsers.php中) ,但评论说。)

我在Apache Web服务器+ PHP 7 + MySQL 5.7 + jQuery 3.2.1 + HTML 5上进行了测试。

祝你好运。

代码示例:

的index.php

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#submit').click(function (event) {
                    $('#messages').empty();
                    $('#results').empty();

                    $.ajax({
                        method: 'post',
                        dataType: 'json',
                        url: 'getUsers.php',
                        data: {
                            'userId': $('#userId').val()
                        },
                        success: function (response, textStatus, jqXHR) {
                            $.each(response, function (key, user) {
                                var result = 'User_Id: ' + user.User_Id + ', ';
                                result += 'Dia_Qty: ' + user.Dia_Qty + ', ';
                                result += 'Fighter_Info: ' + user.Fighter_Info + ', ';
                                result += 'InvBonus: ' + user.InvBonus;

                                $('#results').append(result);
                            });
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            $('#messages').html(jqXHR.responseText);
                        },
                        complete: function (jqXHR, textStatus) {
                            //...
                        }
                    });
                });
            });
        </script>

        <style type="text/css">
            body {
                padding: 30px;
            }

            button {
                padding: 5px 10px;
                background-color: #8daf15;
                color: #fff;
                border: none;
            }

            #messages {
                color: #c00;
                margin-bottom: 15px;
            }

            #results {
                margin-top: 20px;
            }
        </style>
    </head>
    <body>

        <div id="messages">
            Here come the success, or error messages...
        </div>

        <div class="form-container">
            <label for="userId">User ID</label>
            <input type="text" id="userId" name="userId" value="2">

            <button type="button" id="submit" name="submit" value="submit">
                Submit
            </button>
        </div>

        <div id="results">
            Here comes the fetched data...
        </div>

    </body>
</html>

getUsers.php:

<?php

include 'handlers.php';
include 'db.php';

// Validate the posted values.

// Like this:
try { // If an exception is thrown, then it will be handled by the "error" callback of jquery.ajax().
    if (!isset($_POST['userId']) || empty($_POST['userId'])) {
        throw new InvalidArgumentException('Please provide the user ID.');
    }

    // Here other validations...
} catch (InvalidArgumentException $exc) {
    /*
     * If you want you can use a header to specify a certain status code (here 401), which can be 
     * read in the ajax call for further customizations. I think the second parameter ("textStatus") 
     * of the "error" callback of jquery.ajax() is the one displaying it.
     * 
     * Notice that no json_encode() is needed. The same applies to the error/exception handlers in 
     * "handlers.php". So, no json_encode() in their echo's, as well. Why? Because in the "error"
     * callback the "responseText" property is used to display the error, not the "responseJSON".
     */
    // header('HTTP/1.1 401 Unauthorized');
    echo $exc->getMessage();
    exit();
}

//**********************************************************
// ... or like this instead:
//if (!isset($_POST['userId']) || empty($_POST['userId'])) {
//    header('HTTP/1.1 401 Unauthorized');
//    echo 'Please provide the user ID.';
//    exit();
//}
//**********************************************************

$userId = $_POST['userId'];

/*
 * The SQL statement to be prepared. Notice the so-called markers, 
 * e.g. the "?" signs. They will be replaced later with the 
 * corresponding values when using mysqli_stmt::bind_param.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'SELECT * 
        FROM Users 
        WHERE User_Id = ?';

/*
 * Prepare the SQL statement for execution - ONLY ONCE.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$statement = $connection->prepare($sql);

/*
 * Bind variables for the parameter markers (?) in the 
 * SQL statement that was passed to prepare(). The first 
 * argument of bind_param() is a string that contains one 
 * or more characters which specify the types for the 
 * corresponding bind variables.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
$statement->bind_param('i', $userId);

/*
 * Execute the prepared SQL statement.
 * When executed any parameter markers which exist will 
 * automatically be replaced with the appropriate data.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.execute.php
 */
$statement->execute();

/*
 * Get the result set from the prepared statement.
 * 
 * NOTA BENE:
 * Available only with mysqlnd ("MySQL Native Driver")! If this 
 * is not installed, then uncomment "extension=php_mysqli_mysqlnd.dll" in 
 * PHP config file (php.ini) and restart web server (I assume Apache) and 
 * mysql service. Or use the following functions instead:
 * mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.get-result.php
 * @link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
 */
$result = $statement->get_result();

/*
 * Fetch data and save it into $fetchedData array.
 * 
 * @link http://php.net/manual/en/mysqli-result.fetch-all.php
 */
// Fetch all rows at once...
$users = $result->fetch_all(MYSQLI_ASSOC);

// ... OR fetch one row at a time.
// $users = [];
// while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
//     $users[] = $row;
// }

/*
 * Free the memory associated with the result. You should 
 * always free your result when it is not needed anymore.
 * 
 * @link http://php.net/manual/en/mysqli-result.free.php
 */
$result->close();

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them 
 * so that the next query can be executed.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.close.php
 */
$statement->close();

/*
 * Close the previously opened database connection.
 * 
 * @link http://php.net/manual/en/mysqli.close.php
 */
$connection->close();

// If no users found (e.g. $users is empty) display a message.

// Like this:
try {
    if (!$users) {
        throw new UnexpectedValueException('No users found for the provided user id.');
    }
} catch (UnexpectedValueException $exc) {
    echo $exc->getMessage();
    exit();
}

//****************************************************
// ... or like this instead:
//if (!$users) {
//    header('HTTP/1.1 404 No Content');
//    echo 'No users found for the provided user id.';
//    exit();
//}
//****************************************************

echo json_encode($users);
exit();

db.php中:

<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');

/*
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions 
 * (mysqli_sql_exception).
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/*
 * Create a new db connection.
 * 
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

handlers.php:

<?php

/**
 * Error handler.
 * 
 * @link http://php.net/manual/en/function.set-error-handler.php set_error_handler.
 * @param int $errno
 * @param string $errstr
 * @param string $errfile
 * @param int $errline
 */
function errorHandler($errno, $errstr, $errfile, $errline) {
    // Print a user-friendly message or show a custom error page.
    echo 'An error occurred during your request. Please try again or contact us.';

    // Log the error.
    error_log('Error ' . $errno . ' - ' . $errstr . ' in file ' . $errfile . ' on line ' . $errline);

    exit();
}

/**
 * Exception handler.
 * 
 * @link http://php.net/manual/en/function.set-exception-handler.php set_exception_handler.
 * @param Exception $exception
 */
function exceptionHandler($exception) {
    // Print a user-friendly message or show a custom error page.
    echo 'An error occurred during your request. Please try again or contact us.';

    // Log the exception.
    error_log('Exception ' . $exception->getCode() . ' - ' . $exception->getMessage() . ' in file ' . $exception->getFile() . ' on line ' . $exception->getLine());

    exit();
}

// Set the handlers.
set_error_handler('errorHandler');
set_exception_handler('exceptionHandler');