此PHP5源在PHP7中不好

此PHP5源在PHP7中不好,php,mysql,Php,Mysql,我想在Amazon服务器上读取MySQL并将结果发送到我的Unity程序。 PHP5中的PHP源代码在另一台服务器上工作,我将该源代码复制到PHP7中的Amazon服务器上 然而,每次我运行这个程序时,我都会遇到这样的错误 'PHP分析错误:语法错误,文件意外结束。。。第51行'。 第51行是源代码的末尾 我是PHP新手。我在谷歌上搜索了几天,试图找出问题所在。但是我找不到 有人能帮我吗?如有任何建议,将不胜感激。 我的消息来源在这里 <?php $servername = 'localh

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

然而,每次我运行这个程序时,我都会遇到这样的错误 'PHP分析错误:语法错误,文件意外结束。。。第51行'。 第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);
?>

您的代码使用PHP7.0.22在我的服务器上运行良好,因此我认为这一定是AWS服务器上的PHP配置错误,您是否尝试运行phpinfo()之类的简单脚本

此外,出于安全原因,最好不要在此处添加php结尾标记“更多信息”:

似乎您的ajax(我认为有一个是因为
$\u POST
变量)对错误非常挑剔:-)

请注意,我不知道您是否以及如何发出ajax请求。因此,我将在html页面的脚本标记中引用ajax请求

第一个问题:

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

第二个问题:

您的代码仍然抛出一个通知,因为
if($connect==0)
语句:

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

有关正确的错误处理(包括数据库连接故障),请参阅和。下面我也举一个例子

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

通知发出后立即发出警告

警告:无法修改标题信息-标题已由发送 (输出开始于 /php:9)中 /getUsers.php在线 三十二

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

如果您在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 {}

另外,我认为在您的情况下,
头(…)
是不必要的。我不确定,因为我不知道团结


建议和代码: 请注意,在我的示例中,所有系统导致的错误/异常(如数据库连接失败、准备/执行sql语句失败等)将仅在日志文件中可见。只有开发者才能看到,而不是网站的用户。应该如此。用户永远不会看到诸如“对不起,连接失败”之类的错误。应该向用户显示的错误(如“请提供用户id”、“未找到提供用户id的用户”等)应该直接
echo
-ed,或者在“特定”try catch块中抛出和处理(就像我在
getUsers.php
中所做的那样)

现在,由于我抛出并捕获异常(就像我在
getUsers.php
中两次那样,例如,使用两个try-catch块),回显消息将自动发送到jquery.ajax()的“error”函数,而不是“success”函数。如果使用标题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块:

同样:消息将被发送到jquery.ajax()的“error”函数。要点是:任何从服务器发送到客户端(例如浏览器)的状态代码不是2xx的响应头(请参阅和)都会发出ajax请求,以调用“错误”回调,而不是“成功”回调。在上面的代码中,报头发送401或404代码,例如不同于2xx(200等)

因此,您可以选择使用try-catch块(就像我在下面的
getUsers.php
中所做的那样),也可以选择使用头回送对(也可以在
getUsers.php
中,但需要注释)

我在ApacheWeb服务器+PHP7+MySQL5.7+jQuery3.2.1+HTML5上进行了测试

祝你好运

代码示例:

index.php

演示
$(文档).ready(函数(){
$(“#提交”)。单击(函数(事件){
$(“#消息”).empty();
$(“#结果”).empty();
$.ajax({
方法:“post”,
数据类型:“json”,
url:'getUsers.php',
数据:{
“userId”:$(“#userId”).val()
},
成功:函数(响应、文本状态、jqXHR){
$。每个(响应、功能(键、用户){
变量结果='User_Id:'+User.User_Id+',';
结果+='直径数量:'+用户直径数量+',';
结果+='战斗机信息:'+user.Fighter\u信息+',';
结果+='InvBonus:'+user.InvBonus;
if (!isset($_POST['userId']) || empty($_POST['userId'])) {
    header('HTTP/1.1 401 Unauthorized');
    echo 'Please provide the user ID.';
    exit();
}
if (!$users) {
    header('HTTP/1.1 404 No Content');
    echo 'No users found for the provided user id.';
    exit();
}
<!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>
<?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();
<?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);
<?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');