好的,让我首先说我是一个刚刚学习使用Swift进行编码的IOS开发人员。我对PHP一无所知,但我正在为我的Web服务编写基本脚本。如果我的问题听起来很愚蠢,请耐心等待。
这是我正在尝试做的事情:我正在从我的MySQL数据库中检索数据,并且我将检索到的数据(从我的MySQL表中某一行的某个列的值)分配给变量{{ 1}}。之后,我开始一个$retrievedStatus
循环,只要从MySQL表中检索到的值等于我正在监听的某个值,我就希望该循环继续运行。在代码中,它看起来像这样:
do while
问题在于:我测试了代码,一旦客户端触发上述代码开始通过数据任务运行,它就会从Web服务({{1}内部)接收数据。每隔5秒(注意网络服务在每个循环中休眠5秒),这样循环就能完美运行。问题是,只要我的MYSQL表中的列// CREATE DATABASE CONNECTION
$db = new DbConnect('localhost', 'myusername', 'mypassword', 'mydatabase');
$db->show_errors();
// DECODE PHP INPUT (WILL RECEIVE INPUT FROM CLIENT SIDE WHICH WILL BE USED TO CHECK STATUS)
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$id = $data['idToCheck'];
$username = $data['usernameToCheck'];
$retrievedStatus = ""; // <-- CREATING A STRING OBJECT OUTSIDE THE DO BLOCK EVEN THOUGH I ASSIGN A VALUE TO IT INSIDE THE DO BLOCK. I DO THIS SO I CAN CHECK UPON THE VALUE AFTER THE DO BLOCK HAS FINISHED AND IT CHECKS FOR THE WHILE CONDITION TO SEE IF IT SHOULD REPEAT
do {
// Sleep for 5 seconds
sleep(5);
// SQL query to retrieve status
$sql = "SELECT * FROM mytable WHERE id = '" . $id . "' AND username = '" . $username . "'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Assign each row into an array
$dataArray[] = $row;
}
// Get status from returned row: ONLY 1 ROW WAS RETURNED
$jsonArray = json_encode($dataArray);
$decodedArray = json_decode($jsonArray, true);
$userDictionary = $decodedArray[0];
$retrievedStatus = $userDictionary['status']; // <-- THIS IS WHERE THE VALUE GETS ASSIGNED TO THE STRING OBJECT I CREATED EARLIER
// DOWN HERE SOME CODE IS EXECUTED TO RETURN DATA BOTH BACK TO THE CLIENT AND THE SERVER
} while ($retrievedStatus != "connected") // AS LONG AS THE COLUMN status IN MY SQL TABLE IS NOT EQUAL TO "connected" THIS LOOP WILL CONTINUE RUNNING AND IT WILL REPEAT THE PROCESS OF UPDATING THE STATUS AND DOING THE DATA TASK AFTERWARDS
更改为“已连接”,循环就应该停止重复,因为while条件将为false。但它并没有这样做,相反,它只是永远运行(无限循环),这意味着当SQL查询的返回值被分配给do
时,显然会出现问题。我在Swift中学到了你无法从最初创建它的代码块之外访问变量,这就是我在status
块之前创建空字符串变量的原因。这是必要的和/或这是正确的方法吗?我希望我对我正在努力实现的目标的解释是清楚的,我希望有人可以帮助我解决这个问题。谢谢!