如何在PHP命令行中运行cURL命令



我不知道以前是否有人问过这个问题,但我正试图在我的PHP CLI中运行php index.php命令,因为cURL代码是index.php页面,我一直得到这个错误。

Connection failed: SQLSTATE[HY000] [2002] Connection refusedPHP Warning:  Undefined variable $conn in /Users/test/.bitnami/stackman/machines/xampp/volumes/root/htdocs/api-call/index.php on line 26
Warning: Undefined variable $conn in /Users/test/.bitnami/stackman/machines/xampp/volumes/root/htdocs/api-call/index.php on line 26
PHP Fatal error:  Uncaught Error: Call to a member function prepare() on null in /Users/test/.bitnami/stackman/machines/xampp/volumes/root/htdocs/api-call/index.php:26
Stack trace:
#0 {main}
thrown in /Users/test/.bitnami/stackman/machines/xampp/volumes/root/htdocs/api-call/index.php on line 26
Fatal error: Uncaught Error: Call to a member function prepare() on null in /Users/test/.bitnami/stackman/machines/xampp/volumes/root/htdocs/api-call/index.php:26
Stack trace:
#0 {main}
thrown in /Users/test/.bitnami/stackman/machines/xampp/volumes/root/htdocs/api-call/index.php on line 26

在下面的代码中,我试图从API插入记录到数据库中使用MySQL准备好的语句。

<?php
include_once './config/Database.php';
$url = "http://exampledomain.com/api/properties";
$ch = curl_init($url);
$headers = array(
'Content-type: application/json',
'API_KEY: 2S7rhsaq9X1cnfkMCPHX64YsWYyfe1he',
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$resp = curl_exec($ch);
if($e = curl_error($ch)){
echo $e;
}
else {
$decoded = json_decode($resp,true);
// print_r($decoded);
$stmt = $conn->prepare
("INSERT 

INTO 
details 
(
county,
country,
town,
description,
type
) 
VALUES 
(
:county,
:country,
:town,
:description,
:type
)
");
$stmt = $conn->prepare($query);
//Clean Data
$county = htmlspecialchars(strip_tags($county));
//Bind data
$stmt->bindParam(':county', $county);
$stmt->bindParam(':country', $country);
$stmt->bindParam(':town', $town);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':type', $type);
foreach($decoded["data"] as $decode){
$county = $decode['county'];
$country = $decode['country'];
$town = $decode['town'];
$description = $decode['description'];
$type = $decode['type'];


$stmt->execute();
}
// $stmt->close();
// $conn->close();
}
curl_close($ch);

我在我的Database。php中有这段代码它连接了数据库

<?php
$servername = "127.0.0.1";
$username = "test";
$password = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=api-call", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully"; 
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}

这不是关于cURL,而是关于到数据库的连接。您自己的错误消息告诉您:

Connection failed: SQLSTATE[HY000] [2002] Connection refused

你的代码忽略了这个错误,并继续执行,这直接导致了其他错误。

确保MySQL在您的机器上运行,并尝试将您连接的地址从127.0.0.1更改为localhost

最新更新