我有一个 PHP 查询,它根据 MySQL 数据库中的时间向人们发送消息:如果是晚上 8:00,它将在晚上 8:00 将消息发送给数据库中有该时间的人我遇到的问题是我的 php 查询仅将消息发送给数据库中的第一个人,只是它没有查看数据库中的其他用户。我现在正在使用短信网关发送消息。 这是我的 php:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hospital";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM uap";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " - Drug time: " . $row["drug1morning"]. "<br>";
$hour = date('G');
$min =date('i');
$sec =date('sa');
if ($hour == $row["drug1morning"] && $min == 00 && $sec == 03 ) {
function SendSMS ($host, $port, $username, $password, $phoneNoRecip, $msgText) {
$fp = fsockopen($host, $port, $errno, $errstr);
if (!$fp) {
echo "errno: $errno \n";
echo "errstr: $errstr\n";
return $result;
}
fwrite($fp, "GET /?Phone=" . rawurlencode($phoneNoRecip) . "&Text=" . rawurlencode($msgText) . " HTTP/1.0\n");
if ($username != "") {
$auth = $username . ":" . $password;
$auth = base64_encode($auth);
fwrite($fp, "Authorization: Basic " . $auth . "\n");
}
fwrite($fp, "\n");
$res = "";
while(!feof($fp)) {
$res .= fread($fp,1);
}
fclose($fp);
return $res;
}
$x = SendSMS("127.0.0.1", 8800, "admin", "admin", $row["phonenumber"], "Hey there !!!!");
echo $x;
}
}
}
最佳答案
在您的 while($row = $result->fetch_assoc())
中,该函数被多次定义。只需将其移出即可。
正确的方法:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//old code
}
}
function SendSMS (...) {
}
如果确实需要放入其中,请避免多重声明:
if (!function_exists('SendSMS')) {
function SendSMS (...) {
}
}
关于PHP查询只执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43944160/