简体   繁体   中英

Executing Python script from PHP and insert in mysql

I have a php script that executes a python script and returns the data back and it is stored in mysql. It's working fine but when the data is stored in the database it inserts an additional blank row. My question would be, how could I make so that it stores only the actual data I recieve.

This is part of the python script


##ser.write(sync)
    ser.write(counters)
    a = ser.read(30)
    state = binascii.hexlify(a)
    asd = re.sub(rb'([0-9, a-z, A-Z])(?!$)', rb'\1,', state)
    url = 'http://127.0.0.1/sastest/meters.php'
    x = requests.post(url, data = asd)
    print(asd)

And this is from the PHP


    passthru("meters.py");

    $incomingData = file_get_contents("php://input");


    $qry1 = "INSERT INTO machtest(data)
                values('".$incomingData."')";

    mysqli_query($conn,$qry1);

From comments we discover the overall process:

When I call meters.php it activates meters.py . meters.py interrogates a devices and sends the data back to meters.php

Because PHP's passthru does not support output return but a similar function exec does as array object with each line as elements, use that instead and do not have Python post back a response. Of course, always run parameterization when interacting with databases and passing input values.

Python (meters.py)

ser.write(counters)
a = ser.read(30)
state = binascii.hexlify(a)
asd = re.sub(rb'([0-9, a-z, A-Z])(?!$)', rb'\1,', state)

print(asd)

PHP (meters.php)

// USE output ARG
exec(command = "meters.py", output = $incomingData);

// USE PARAMETERIZATION
$qry = "INSERT INTO machtest (data) VALUES (%s)";
$stmt = mysqli_prepare($qry);
mysqli_stmt_bind_param($stmt, "s", $incomingData[0]);
mysqli_stmt_execute($stmt);

See mysqli prepared statement docs


Alternatively, have Python run all processing including device and database interaction. Then, have PHP call the .py script:

Python (meters.py)

import mysql.connector        # USE ANY MySQL DB-API. THIS IS AN EXAMPLE
...

### INTERROGATE DEVICE
ser.write(counters)
a = ser.read(30)
state = binascii.hexlify(a)
asd = re.sub(rb'([0-9, a-z, A-Z])(?!$)', rb'\1,', state)

### APPEND TO DATABASE
# OPEN CONNECTION AND CURSOR
conn = mysql.connector.connect(host='localhost', database='mydatabase',
                               user='root', password='pwd')
cur = conn.cursor()

# USE PARAMETERIZATION   
qry = "INSERT INTO machtest (data) VALUES (%s)"
cur.execute(qry, (asd,))
conn.commit()

cur.close()
conn.close()

See MySQL cursor execute docs

PHP (meters.php)

// NO NEED FOR output
passthru(command = "meters.py");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM