PHP to MySQL, POST problem

Links for php scripts

Moderators: egami, macek, gesf

Post Reply
gaspar
New php-forum User
New php-forum User
Posts: 3
Joined: Thu Mar 02, 2017 4:51 am

Thu Mar 02, 2017 5:09 am

Hello guys, Im new in PHP and Mysql so sorry if its an stupid question but I could not find any information about.

Im trying to send some data from Arduino to PHP script and then insert it to a database, this is code is supposed to do so:

Code: Select all

<?php
   	include("connect.php");
   	
   	$link=Connection();

	$temp1=$_POST["temp1"];
	$hum1=$_POST["hum1"];

	$query = "INSERT INTO tempLog (temperature, humidity) 
		VALUES ('".$temp1."','".$hum1."')"; 
   	
   	mysql_query($query,$link);
	mysql_close($link);
	
	

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

	
	
	

   	header("Location: index.php");
?>
I just want to insert temperature and humidity, and display it in a web wich is http://gas.rf.gd/ there you can see 4 values that I inserted from Mysql
But for some reason its not working you can test with this page: http://requestmaker.com/ and this data;
Request URL :http://gas.rf.gd/add.php
Request header: Content-Type ; application/x-www-form-urlencoded
Request data: temp1=33&hum1=30;

Thans in advance for your help!

Best Regards.
Gaspar.

User avatar
Strider64
php-forum Active User
php-forum Active User
Posts: 314
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Thu Mar 02, 2017 10:35 am

The main reason it's probably not working is that it's using mysql, you should be using mysqli or PDO (my recommendation).

Here's an example on how to insert something using PDO

Code: Select all

/*
 * Registration function of user:
 */

function registration(array $data, $pdo = NULL) {

    $password = password_hash($data['password'], PASSWORD_DEFAULT);
    $confirmation = password_hash($data['confirmation'], PASSWORD_DEFAULT);

    $query = 'INSERT INTO login(name, email, password, confirmation, dateCreated) VALUES ( :name, :email, :password, :confirmation, NOW())';
    $stmt = $pdo->prepare($query);
    $result = $stmt->execute([':name' => $data['name'], ':email' => $data['email'], ':password' => $password, ':confirmation' => $confirmation]);
    if ($result) {
        return TRUE;
    } else {
        return FALSE;
    }
}
If you insist on still trying use mysql then I'm sure someone here will gladly lead you down the wrong path, but I hope you don't.

User avatar
Strider64
php-forum Active User
php-forum Active User
Posts: 314
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Thu Mar 02, 2017 10:45 am

Not tested but here's how I would do it (Hint it uses constants for the db connection):

Code: Select all

<?php

include("connect.php");

$temp1 = htmlspecialchars($_POST["temp1"]);
$hum1 = htmlspecialchars($_POST["hum1"]);

$db_options = [
    /* important! use actual prepared statements (default: emulate prepared statements) */
    PDO::ATTR_EMULATE_PREPARES => false
    /* throw exceptions on errors (default: stay silent) */
    , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    /* fetch associative arrays (default: mixed arrays)    */
    , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);

$query = 'INSERT INTO tempLog(temperature, humidity) VALUES ( :temperature, :humidty)';


$stmt = $pdo->prepare($query);
$result = $stmt->execute([':temperature' => $temp1, ':humidty' => $hum1]);

if ($result) {
    echo "Yeppie, the data has been inserted correctly into the database table!<br>\n";
} else {
    echo "I'm sorry something went wrong, try again with the script!<br>\n";
}

User avatar
Strider64
php-forum Active User
php-forum Active User
Posts: 314
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Thu Mar 02, 2017 10:49 am

Here's part of the connect.php script I would use:

Code: Select all

<?php
$server_name = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_URL);
define('BASE_PATH', realpath(dirname(__FILE__)));
/* Setup constants for local server and remote server */
define('EMAIL_HOST', 'your_email_host');
define('EMAIL_USERNAME', 'your_email_username');
define('EMAIL_PASSWORD', 'your_email_password');
define('EMAIL_ADDRESS', 'your_email_address');
define('EMAIL_PORT', 587);
define('PRIVATE_KEY', 'your_private_key');
if (filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_URL) == "localhost") {
  define('DATABASE_HOST', 'local_host');
  define('DATABASE_NAME', 'your_db_name');
  define('DATABASE_USERNAME', 'root');
  define('DATABASE_PASSWORD', 'your_db_password');
  define('DATABASE_TABLE', 'users');
} else {
  define('DATABASE_HOST', 'your_remote_host');
  define('DATABASE_NAME', 'your_remote_database');
  define('DATABASE_USERNAME', 'your_remote_username');
  define('DATABASE_PASSWORD', 'your_remote_password');
  define('DATABASE_TABLE', 'users');
}
I would also probably stick the $pdo connection in that too.

gaspar
New php-forum User
New php-forum User
Posts: 3
Joined: Thu Mar 02, 2017 4:51 am

Thu Mar 02, 2017 4:40 pm

Thanks Strider64,I did not even know of the existence of PDO, today I was studying it so probably tomorrow will see if I can put in practice your recommendation.

gaspar
New php-forum User
New php-forum User
Posts: 3
Joined: Thu Mar 02, 2017 4:51 am

Fri Mar 03, 2017 10:44 am

I have managed to learn and understand most of your code, now I can connect to mysql with PDO, there are only two things that I dont fully understand:

the first thing is your connect script im not sure how to execute it

Code: Select all

$server_name = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_URL);
define('BASE_PATH', realpath(dirname(__FILE__)));
and the second thing is that I still get this error in response body when sending POST:

Code: Select all

<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("0f787997018fe8303bf96648f52b8226");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://www.gas.rf.gd/add.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
The weird thing is that if I join to this URL: http://www.gas.rf.gd/add.php I get this response "Yeppie, the data has been inserted correctly into the database table!" and on Mysql database a new row is inserted with temperature 0 and humidity 0!!

Post Reply