-1

I am fetching data from python script using post method in php and storing that data in database.

PHP Script:

<?php
if (isset($_POST['sign'])) {
    
    $sign = $_POST['sign'];
    $msg = $_POST['msg'];
    echo $sign . " " . $msg ;
    $sql1 = "INSERT INTO data1 (message, sign)
    VALUES ('$msg','$sign')";
    if ($conn->query($sql1) === TRUE) {
        echo "New record created successfully";
    }   
    else {
        echo "Error: " . $sql1 . "<br>" . $conn->error;
    }
}
else {
    echo "";
}
$sql2 = "SELECT message FROM data1 WHERE id= (SELECT max(id) FROM data1) AND sign= '".$sign."'";
$result = $conn->query($sql2);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        
            echo "message: " . $row["message"];
            $c= escapeshellcmd('python new.py'   .$row["message"] );
            echo "<br>";
       
        
            
    
        
    }
}
else {
  echo "0 results";
}

?>

data is storing in database perfectly but after execution of read query it gives error that "Undefined variable : sign" if anyone have any idea about it kindly share Thank you.

sam
  • 309
  • 2
  • 9

1 Answers1

1

Your code defines variable $sign only when if (isset($_POST['sign'])) is true (when there is a POST data with key sign), but you're using the $sign variable inside the second SQL query, which is outside of the if statement.

$sql2 = "SELECT message FROM data1 WHERE id= (SELECT max(id) FROM data1) AND sign= '".$sign."'";`

In order to fix the undefined variable error, you should move the piece of code to inside the if body.

<?php
if (isset($_POST['sign'])) {
    
    $sign = $_POST['sign'];
    $msg = $_POST['msg'];
    echo $sign . " " . $msg ;
    $sql1 = "INSERT INTO data1 (message, sign)
    VALUES ('$msg','$sign')";
    if ($conn->query($sql1) === TRUE) {
        echo "New record created successfully";
    }   
    else {
        echo "Error: " . $sql1 . "<br>" . $conn->error;
    }

    $sql2 = "SELECT message FROM data1 WHERE id= (SELECT max(id) FROM data1) AND sign= '".$sign."'";
    $result = $conn->query($sql2);
    
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            
                echo "message: " . $row["message"];
                $c= escapeshellcmd('python new.py'   .$row["message"] );
                echo "<br>";
           
            
                
        
            
        }
    }
    else {
      echo "0 results";
    }

}
else {
    echo "";
}
Rafael
  • 18,349
  • 5
  • 58
  • 67