I want to do an HTTP GET request from the Python script to my server. The data I want to send is stored in a variable data.
I am using requests package of python to send it to my PHP page and I am getting the following error
import requests
data=850
r=requests.get("http://xxxxx.org/retrieve.php", params= str(data))
my retrieve.php file is
<?php
if (isset($_GET['data'])){
$data = $_GET['data'];
echo $data;
}
else{
echo "Data not received";
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$f=0;
$data= intval(data);
$sql="select max(ID) from moisture";
$res1 = mysqli_query($conn,$sql);
$row = mysqli_fetch_row($res1);
$ref = $row[0] + 1;
$sql1 = "INSERT INTO moisture VALUES ('$ref' , '$data')";
if (mysqli_query($conn, $sql1))
{
$f=1;
}
else {
$f=0;
}
mysqli_close($conn);
?>
I converted the data to string and then send it. On php script, I am getting the intval of the string but it is storing value '0' instead of '850'
My code is working for any static value that I am assigning to it. But it is not sending the data if I am receiving it from the sensor.
import serial
import requests
ser=serial.Serial('COM12',9600)
while True:
data=ser.readline()
r=requests.get("http://xxxxx.org/retrieve.php", params= data)
Related
Sorry for the newbie question, but I have this task which kind of got me stuck.
So, I made a database in PhpMyAdmin, created a table with data : Products(id, name, city) and created a stored procedure that will actually do a query on the table to find out the product with a certain name (which will be input-ed by the user on the web page). My stored procedure is: proc_test and takes one VARCHAR paramter.
So, how can I do this in a php script? How can i ask the user for some data, (on the site he should have like a box to type it) then click a search button, and get redirected to the page with the query results. This is my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CALL proc_test('pencil');";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['numec'] . "<br/>";
}
}
$conn->close();
?>
Here, of course, I manually give the parameter in the script. But I don't know how to change this and ask for a user input instead. Any help is welcome!
You can use ajax to send the data from your website to the php file where you can search for it in the database and send that data back to the user. In my example, the data is being displayed on the same webpage. You could echo the link to the website and redirect the user on the webpage using JavaScript if you really wanted to but my example is just a proof of concept.
index.html
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input required type="text" id="user_input">
<button onclick="sendData()">Search</button>
<p id="result"></p>
<script>
function sendData() {
var var_params = $('#user_input').val();
$.post('test.php', {params: var_params}, function(data) {
document.getElementById('result').innerHTML = "Your search result: " + data;
});
}
</script>
</body>
</html>
test.php
<?php
if(isset($_POST['params'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$param = mysqli_real_escape_string($conn, $_POST['params']);
$sql = "CALL proc_test('$param');";
if($result = mysqli_query($conn, $sql)) {
while($row=mysqli_fetch_assoc($result)) {
echo $row['numec']. "<br/>";
}
}
$conn->close();
}
?>
I'm currently doing a project regarding an attendance system using arduino uno and Ethernet shield. For now I have successfully saved the id I get from arduino to the database. My problem is how to make an alert or popup message that says the data has been received and stored in the database every time I receive data from arduino.
Thank you.
Below is my arduino code:
if (client.connect(myServer, 80)) {
Serial.println("Connecting to Database server");
// send the HTTP PUT request:
client.print("GET /school/inc/jaripelajar.php?P_ID=");
client.print(P_ID);
client.println(" HTTP/1.1");
client.println("Host: 192.168.137.1");
client.println("User-Agent: arduino-ethernet");
client.println("Connection: close");
client.println();
}
php code
// GET request
if (isset($_GET['P_ID'])){
$data1 = $_GET['P_ID'];
}
else{
//echo "Data not received";
}
// Initialize connection to MySQL database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully <br>";
//Insert into database
$data1_sql = "INSERT INTO test (P_ID) VALUES ($data1);";
$data1_query = mysqli_query($conn, $data1_sql);
I use the hosting company aPlus.net, and I can't seem to get past a connection error I'm getting when trying to process some php to write database content to a webpage, and I am curious as to if this is because my database appears to not be on the same server as the entire rest of my hosting account, and if there is a way to resolve this in my code? This is my first attempt at writing PHP, and it would be good to know if my code is wrong, or if my hosting company is messing me up. (and either way, how to fix it)
Here's the code that's failing to pull from the database:
{
$con = mysql_connect("localhost","2p5dq9vxmy240651","MY_PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("felineasthma_2p5dq9vxmy240651", $con);
$users_name = $_POST['name'];
$users_comment = $_POST['requests'];
$users_name = mysql_real_escape_string($users_name);
$users_comment = mysql_real_escape_string($users_comment);
$inputid = $_GET['id'];
$query = "
INSERT INTO `felineasthma_2p5dq9vxmy240651`.`submissions` (`id`,
`name`, `requests`, `inputid`) VALUES (NULL,
'$users_name', '$users_comment', '$inputid');";
mysql_query($query);
echo "<h2>Your request has been processed, reload page.</h2>";
mysql_close($con);
}
and here's some screen captures from inside my hosting account (links because I don't have enough posts here yet to upload images, sorry):
felineasthma_2p5dq9vxmy240651 doesn't appear in my hosting account
yet it clearly exists in MySQL Manager, but on a different server
I was even more confused while making the user for this database, as the control panel didn't allow me to make a username, it just randomly assigned one. Help? Advice?
I found a more modern tutorial to learn PHP with, and now everything works, I just need to add security measures now. Here's the working code snippets, if anyone ever comes here asking the same questions.
here's the form action that places the entries into the database:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = $_POST['name'];
$users_request = $_POST['requests'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO submissions (name, requests)
VALUES ('$users_name', '$users_request')";
if (mysqli_query($conn, $sql)) {
header("Location: clv.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
here's the include that puts the database entries onto the page:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, requests, name FROM submissions";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "" . $row["requests"]. " - by " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
I have been developing a CRUD application using PHP & MySQL database.
I was succeeded by creating, displaying, updation parts. But I stuck at the deletion part of a row from a database table.
I tried my best solving all the PHP shown errors but now in final it is now showing a message which I wrote to echo in case of failure.
I request someone to please help me with this problem.
Thankyou in advance.
Code I wrote for deletion:
//include database connection
include 'db_connect.php';
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "DELETE
FROM `grocery`
WHERE `GrocerID` ='".$mysqli->real_escape_string($_GET['id'])."'
limit 0,1";
//execute query
if( $mysqli->query($query) ){
//if successful deletion
echo "User was deleted.";
}else{
//if there's a database problem
echo "Database Error: Unable to delete record.";
}
$mysqli->close();
?>
Code I wrote for delete link in display table:
//just preparing the delete link to delete the record
echo "<a href='delete.php?id={$GrocerID}'>Delete</a>";
Code I wrote for db config:
<?php
//set connection variables
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
?>
I tried this and got working, can you update the code and see if this works?
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
// Delete row
if ($mysqli->query (sprintf( "DELETE FROM grocery WHERE email = '".$mysqli->real_escape_string($_GET['id'])."' LIMIT 1") )) {
printf ( "Affected Rows %d rows.\n", $mysqli->affected_rows );
}
I hope this helps.
Provide a connection :
if( $mysqli->query($con, $query) ){
I've been trying to get my python code to transfer SQL query data from client running python to web server running PHP, then input that data into a MySQL database.
The below is the python test code simulating a single row:
#!/usr/bin/python
import requests
import json
url = 'http://192.168.240.182/insert_from_json.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":5,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=dict(payload=json.dumps(payload)), headers=headers)
print response
The below is the PHP script on the server side:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload']
//$payload = '{"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}';
$payload_array = json_decode($payload_dump,true);
//get the data_payload details
$device = $payload_array['device'];
$type = $payload_array['data_type'];
$zone = $payload_array['zone'];
$sample = $payload_array['sample'];
$count = $payload_array['count'];
$time = $payload_array['time_stamp'];
$sql = "INSERT INTO data(device, data_type, zone, sample, count, time_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
If I comment out $payload_dump and instead use $payload and run the script the row is added correctly. But when I call the python script on the client I get a "response 200" but the record was not added. Something either my JSON string in python isn't formatted correctly or I am not passing the value correctly.
1) What is the syntax/procedure on the python code that would allow me to see what has actually been received by the PHP code. (i.e. convert the "$payload_dump" variable contents to a string and send back to the python script?
2) How do I resolve the above code?
Your first problem is using json headers which you shouldn't use since you aren't sending a raw json:
your data look like
{payload = {'key1': 'value1',
'key2': 'value2' }
}
and a raw json data should be in the form:
{'key1': 'value1',
'key2': 'value2'}
So you need to remove the headers from the request
response = requests.post(url, data=dict(payload=json.dumps(payload)))
Second you need to fix that missing semicolon
$payload_dump = $_POST['payload']
to
$payload_dump = $_POST['payload'];
Better solution
You can send the json data directly using requests
response = requests.post(url, json=payload)
then grab it in php with
$payload_array = json_decode(file_get_contents('php://input'), true);