gpt4 book ai didi

php Curl 无法在 if 语句中正确读取响应,回显正常

转载 作者:行者123 更新时间:2023-11-29 06:53:33 24 4
gpt4 key购买 nike

你好,我正在做我的大学工作,我们正在使用curl和php,我已经制作了一个脚本。该脚本从html表单中检索一个id,然后使用curl将其传递给php脚本来更新数据库,这一切都工作正常,但是在我的curl脚本中,我从php页面读取了回显的响应

OK

更新数据库后,我的 if 语句无法读取 OK,我做错了什么?正如我所说,代码工作正常,只是在读取响应后没有在 if 语句中显示正确的消息,这是如果我尝试的话,curl 脚本会显示的内容,数据库再次更新良好等,只是没有正确读取响应正如您在代码中看到的,我回显响应来测试它,它显示“确定”,“确定”之前有一个空格,所以我尝试了“确定”和“确定”,然后再次尝试了一个空格,但都无法将其与响应匹配。

error

test responce = OK

代码。

curl 代码

<?php
$id = $_POST["id"];

$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, "http://southamptonstudentrooms.com/Wad/downloadwebservice3.php");
$dataToPost = array ("id" => $id);
curl_setopt($connection,CURLOPT_RETURNTRANSFER,1);
curl_setopt($connection,CURLOPT_POSTFIELDS,$dataToPost);
$response = curl_exec($connection);
// display any errors
if(curl_errno($connection)){
echo 'Curl error: ' . curl_error($ch);
}
curl_close($connection);
if ($response == " OK") {
echo "updated";
}
else if ($response == " ERROR") {
echo "updated failed";
}
else {
echo "error";
}
echo "<br><br>test response =" . $response; // displays " OK"
var_dump($response); // displays: string(4) " OK"
?>

为了安全起见,它访问的 PhP 脚本 - 要连接的用户信息已更改

<?php
$servername = "localhost";
$username = "south609_edwin";
$password = "Zx10r2006";
$dbname = "south609_test_database";
$ID = $_POST["id"];
$status;

// 11: Chris Palmer, username ChrisPalmer, Password tree987, Balance 2.00
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM ht_users WHERE username='ChrisPalmer'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if($row["balance"] >= 0.79)
{
mysqli_close($conn);
try {
//WAI
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "UPDATE wadsongs SET downloads=downloads + 1 WHERE songid='$ID'";

// Prepare statement
$stmt = $conn->prepare($sql);

// execute the query
$stmt->execute();

$status = "OK";
// echo a message to say the UPDATE succeeded
// echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
else{
$status = "ERROR";
}
}
}
else {
echo "0 results";
mysqli_close($conn);
}
echo $status;
?>

最佳答案

您遇到的问题是您得到的响应有一个与“OK”不匹配的空格,因此您可以借助 PHP 中的 trim() 函数修剪空格

所以现在你的代码将变成

if(trim($response) == "OK"){
//Your success code
}

关于php Curl 无法在 if 语句中正确读取响应,回显正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46570910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com