Send data to MySQL database (SOLVED)

I got the data from the database into defold with

function http_result(self, id, response)
    data = json.decode(response.response)
    pprint(data)
end

function init(self)
    http.request("http://localhost/php/storeupdate.php", "GET", http_result)
end

the php code looked like this

<?php 
$host="localhost";                 //replace with your hostname 
$username="root";       //replace with your username 
$password="";               //replace with your password 
$db_name="shop";                //replace with your database 
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name") or die ("cannot select DB"); 
$sql = "select * from stock";  //replace with your table name 
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){while($row=mysql_fetch_row($result)){ 
$json[]=$row; 
}
}
mysql_close();
echo json_encode($json);
?>

So now my question is how can I send data to the php to be put into the database, or is that even possible?

1 Like

It is very possible. Reference these docs and then see if you need more help. You will need to edit your PHP script more to accept data.

https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

http://shodor.org/~kevink/phpTutorial/nileshc_getreqpost.php#3

1 Like

It depends on how much data you want to send, but a simple way to send a couple of kilobytes would be to use GET parameters in your HTTP request… Please see the below example as psuedo code since it was a couple of years since I last wrote a line of PHP…

myscript.php

$hostname = "localhost";
$username = "root"; // Never ever use an administrative user
$password = "secret";
$database = "defolddb";
if(isset($_GET['username'])) {
    $usr = $_GET['username'];
    $conn = mysql_connect($hostname, $username, $password);
    mysql_select_db($conn, $database);

    # Never ever do this, susceptible to SQL Injection
    # Read more at https://www.owasp.org/index.php/SQL_Injection
    $query = "INSERT INTO table_name VALUES ($usr)";
    mysql_query($conn, $query);
    mysql_close($conn);
}

myscript.lua

function http_result(self, id, response)
    data = json.decode(response.response)
    pprint(data)
end

function init(self)
    http.request("http://defold.com/php/myscript.php?username=jakob", "GET", http_result);
end
3 Likes

This fills my needs, thank you a lot.