Skip to content

subscribe query and publish - how? #126

@pw44

Description

@pw44

I'm trying the following:

subscribe to a topic
by paylod make a query to a database
publish to another topic.

`
mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id);
if(!$mqtt->connect(true, NULL, $username, $password)) {
echo "Failed to connect to Mqtt: ";
exit(1);
}

$con = new mysqli($mysql_host, $mysql_user, $mysql_pass, $mysql_mydb );
if ($con -> connect_errno) {
echo "Failed to connect to MySQL: " . $con -> connect_error;
exit(2);
}
$con->set_charset('utf8mb4'); // always set the charset

$mqtt->debug = true;

$topics['rfid/card/ping'] = array('qos' => 0, 'function' => 'procMsg');
$mqtt->subscribe($topics, 0);
while($mqtt->proc()) {
// echo "proc.....";
}
$mqtt->close();

function procMsg($topic, $msg){
echo 'Msg Recieved: ' . date('r') . "\n";
echo "Topic: {$topic}\n";
echo "Payload: {$msg}\n";
echo $msg;
echo "\n";
// query con
//$tagid = "39EAB06D";
$query = "SELECT name, id FROM rfidtags WHERE id = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('s', $msg);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($name, $id);
if ($stmt->fetch()) {
echo "$name $id\n";
echo "1";
} else {
echo "failed to fetch data\n";
echo "2";
}
$con->close();
}
`

but the error:

paulo@hp15pw:~/TOOLS/MQTT-PHP$ php subscribe-query-publish.php
Mon, 19 Jul 2021 12:22:32 -0300: Received CMD: 3 (PUBLISH)
Mon, 19 Jul 2021 12:22:32 -0300: Fetching: 24 bytes
Msg Recieved: Mon, 19 Jul 2021 12:22:32 -0300
Topic: rfid/card/ping
Payload: 39EAB06D
39EAB06D
PHP Notice: Undefined variable: con in /home/paulo/TOOLS/MQTT-
PHP/subscribe-query-publish.php on line 51
PHP Fatal error: Uncaught Error: Call to a member function prepare() on
null in /home/paulo/TOOLS/MQTT-PHP/subscribe-query-publish.php:51
Stack trace:
#0 [internal function]: procMsg()
#1 /home/paulo/TOOLS/MQTT-PHP/phpMQTT.php(482): call_user_func()
#2 /home/paulo/TOOLS/MQTT-PHP/phpMQTT.php(547): Bluerhinos\phpMQTT-

message()
#3 /home/paulo/TOOLS/MQTT-PHP/subscribe-query-publish.php(36):
Bluerhinos\phpMQTT->proc()
#4 {main}
thrown in /home/paulo/TOOLS/MQTT-PHP/subscribe-query-publish.php on line 51

any clue?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions