Android Question Connecting to MySQL

erasmusackon

Member
Licensed User
Longtime User
Am getting this error when connecting to mysql using PHP script. Need help.

[15-Jun-2017 04:58:55 CST6CDT] PHP Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /xxx/xxx/public_html/app/sikacon.php:8
Stack trace:
#0 {main}
thrown in /xxx/xxx/public_html/app/sikacon.php on line 8

This is the scripts.

<?php

$host = "xxxxx";
$user = "xxxxx";
$pw = "xxxx";
$db = "xxxxx";

$con = mysql_connect($host,$user,$pw) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES 'utf8'");

$action = $_GET["action"];

switch ($action)

{
case "CountPersons":
$q = mysql_query("SELECT * FROM DepositTransactions");
$count = mysql_num_rows($q);
print json_encode($count);
break;

Case "GetPersons":
$q = mysql_query("SELECT AccountNumber, MemberID FROM DepositTransactions");
$rows = array();
while($r = mysql_fetch_assoc($q))
{
$rows[] = $r;
}
print json_encode($rows);
break;

case "InsertNewPerson":
$name = $_GET["name"];
$age = $_GET["age"];
$q = mysql_query("INSERT INTO UserRegister (CustomerName, CustomerNo) VALUES ('$name', $age)");
print json_encode("Inserted");
break;

}

?>
 

ronell

Well-Known Member
Licensed User
Longtime User
mysql_connect is already deprecated , try to use pdo or mysqli

or

if your using php 7 , see if you can downgrade it to 5.5
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
1. Use code tags when posting code!
2. Your server is running a higher version of php than expected. The mcysql_* methods are deprecated in PHP 5.something....
Solution is to switch to a MySQLi-Class which does not use this old (deprecated) methods. (find one attached)

Find the use of this class in this copy of a project of mine

PHP:
<?php
include_once("./MysqliDb.php");
$db = new MysqliDb (Array ('host' => 'database-host','username' => 'myusername', 'password' => 'mypassword', 'db'=> 'databasename', 'port' => 3306, 'prefix' => '', 'charset' => 'utf8'));

if (isset($_REQUEST['action'])){$action=strtolower($_REQUEST['action']);} else {$action="init";}

$db->setTrace (true);

$file_handle = fopen('./logs/brrrz_'.date("Y-W", time()).'.log', 'a+');
if(sizeof($_REQUEST) > 0){
  fwrite($file_handle, "======================================"."\r\n");
  foreach($_REQUEST as $name => $value){
    fwrite($file_handle, date("d.m.Y H:i:s", time()).": ".$name."=".$value." ".$add."\r\n");
  }
}

if($action == "register"){ 
  if (isset($_REQUEST['name'])){$name=$_REQUEST['name'];} else {$name="";}
  if (isset($_REQUEST['topic'])){$topic=$_REQUEST['topic'];} else {$topic="";}
  if (isset($_REQUEST['deviceID'])){$deviceID=intval($_REQUEST['deviceID']);} else {$deviceID=0;}
  if ($deviceID == 0){
    # Error #-2 
    echo -2;
    exit;
  }
  if ($deviceID != $topic){
    # Error #-3
    echo -3;
    exit;
  }
  $users = $db->rawQuery("SELECT bd_id FROM brrrz_devices WHERE bd_deviceID = '".$deviceID."' AND bd_topic='".$topic."';", null);
  #echo "SizeOf(users) -> ".sizeof($users);
  if(sizeof($users) == 1){
    #echo "device found";
    # Vorhanden....
    $usr = $users[0];
    $db->rawQuery("UPDATE brrrz_devices SET bd_topic='".$topic."', bd_name='".$name."' WHERE bd_id=".$usr["bd_id"].";", null);
    echo "Benutzer ".$usr["bd_id"]." aktualisiert (".$name.")";
  } else {
    echo "SizeOf(users) != 1 -> ".sizeof($users);
    # Noch nicht vorhanden...
    $data = Array ("bd_deviceID" => $deviceID,
       "bd_topic" => $topic,
             "bd_name" => $name
    );
    $id = $db->insert ('brrrz_devices', $data);
    if($id){
      echo $id;
    } else {
      echo $db->getLastError();
    }
  }
  #print_r($db->trace);
}

if($action == "init"){ 
  if (isset($_REQUEST['token'])){$token=$_REQUEST['token'];} else {$token="";}
  if ($token != "brrrz!"){
    # Error #-2 
    echo -5;
    exit;
  }
  $Devices = $db->rawQuery("SELECT bd_name, bd_id, bd_deviceID FROM brrrz_devices WHERE bd_deviceID<>'' AND bd_name<>''", null);
  echo json_encode($Devices);
}
if($action == "getversion"){
  $appresult = array();
  $appresult["Version"] = 0.10;
  echo json_encode($appresult);
}
if($action == "createtoken"){
  if (isset($_REQUEST['count'])){$count=intval($_REQUEST['count']);} else {$count=-1;}
  if (isset($_REQUEST['len'])){$len=intval($_REQUEST['len']);} else {$len=10;}
 
  $token = array();
  for ($i = 0; $i < $count; $i++) {
    $token[] = randomCode($len);
  }

  $appresult = array();
  $appresult["token"] = $token;
  echo json_encode($appresult);
}
function randomCode($length = 10) {
    $characters = '0123456789abcdefghjkmnrsuvwxyz';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
if($action == "updatetoken"){ 
  if (isset($_REQUEST['token'])){$token=$_REQUEST['token'];} else {$token="";}
  if (isset($_REQUEST['topic'])){$topic=$_REQUEST['topic'];} else {$topic="";}
  if (isset($_REQUEST['deviceID'])){$deviceID=intval($_REQUEST['deviceID']);} else {$deviceID=0;}
  if ($deviceID == 0){
    # Error #-2 
    echo -2;
    exit;
  }
  # Vorhanden....
  $id = $db->rawQuery("UPDATE brrrz_devices SET bd_token='".$token."' WHERE bd_topic='".$topic."' AND bd_deviceID='".$deviceID."';", null);
  if($id){
    echo $id;
  } else {
    echo $db->getLastError();
  }
  #print_r($db->trace);
}


#
# Scriptende...
#
fwrite($file_handle, $db->trace."\r\n");
fclose($file_handle);
?>
 

Attachments

  • MySQLi-Class.zip
    18.7 KB · Views: 319
Upvote 0

ronell

Well-Known Member
Licensed User
Longtime User
Please am using a hosting service and the database is mysqli. Any idea on how to correct the error?
see if you can downgrade the php in your hosting configuration,

if not possible then see 4th post because i also do not recommend to use deprecated methods
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
see if you can downgrade the php in your hosting configuration
This i would not suggest. The old php-version may be removed from the server in the future. No provider will hold old, deprecated, versions on his servers for ever.
The right solution is to update the php-code to be php 7 compatible! And with this; compatible with online hosting providers too as they mostly uses up-to-date installations.
 
Upvote 0

erasmusackon

Member
Licensed User
Longtime User
1. Use code tags when posting code!
2. Your server is running a higher version of php than expected. The mcysql_* methods are deprecated in PHP 5.something....
Solution is to switch to a MySQLi-Class which does not use this old (deprecated) methods. (find one attached)

Find the use of this class in this copy of a project of mine

PHP:
<?php
include_once("./MysqliDb.php");
$db = new MysqliDb (Array ('host' => 'database-host','username' => 'myusername', 'password' => 'mypassword', 'db'=> 'databasename', 'port' => 3306, 'prefix' => '', 'charset' => 'utf8'));

if (isset($_REQUEST['action'])){$action=strtolower($_REQUEST['action']);} else {$action="init";}

$db->setTrace (true);

$file_handle = fopen('./logs/brrrz_'.date("Y-W", time()).'.log', 'a+');
if(sizeof($_REQUEST) > 0){
  fwrite($file_handle, "======================================"."\r\n");
  foreach($_REQUEST as $name => $value){
    fwrite($file_handle, date("d.m.Y H:i:s", time()).": ".$name."=".$value." ".$add."\r\n");
  }
}

if($action == "register"){
  if (isset($_REQUEST['name'])){$name=$_REQUEST['name'];} else {$name="";}
  if (isset($_REQUEST['topic'])){$topic=$_REQUEST['topic'];} else {$topic="";}
  if (isset($_REQUEST['deviceID'])){$deviceID=intval($_REQUEST['deviceID']);} else {$deviceID=0;}
  if ($deviceID == 0){
    # Error #-2
    echo -2;
    exit;
  }
  if ($deviceID != $topic){
    # Error #-3
    echo -3;
    exit;
  }
  $users = $db->rawQuery("SELECT bd_id FROM brrrz_devices WHERE bd_deviceID = '".$deviceID."' AND bd_topic='".$topic."';", null);
  #echo "SizeOf(users) -> ".sizeof($users);
  if(sizeof($users) == 1){
    #echo "device found";
    # Vorhanden....
    $usr = $users[0];
    $db->rawQuery("UPDATE brrrz_devices SET bd_topic='".$topic."', bd_name='".$name."' WHERE bd_id=".$usr["bd_id"].";", null);
    echo "Benutzer ".$usr["bd_id"]." aktualisiert (".$name.")";
  } else {
    echo "SizeOf(users) != 1 -> ".sizeof($users);
    # Noch nicht vorhanden...
    $data = Array ("bd_deviceID" => $deviceID,
       "bd_topic" => $topic,
             "bd_name" => $name
    );
    $id = $db->insert ('brrrz_devices', $data);
    if($id){
      echo $id;
    } else {
      echo $db->getLastError();
    }
  }
  #print_r($db->trace);
}

if($action == "init"){
  if (isset($_REQUEST['token'])){$token=$_REQUEST['token'];} else {$token="";}
  if ($token != "brrrz!"){
    # Error #-2
    echo -5;
    exit;
  }
  $Devices = $db->rawQuery("SELECT bd_name, bd_id, bd_deviceID FROM brrrz_devices WHERE bd_deviceID<>'' AND bd_name<>''", null);
  echo json_encode($Devices);
}
if($action == "getversion"){
  $appresult = array();
  $appresult["Version"] = 0.10;
  echo json_encode($appresult);
}
if($action == "createtoken"){
  if (isset($_REQUEST['count'])){$count=intval($_REQUEST['count']);} else {$count=-1;}
  if (isset($_REQUEST['len'])){$len=intval($_REQUEST['len']);} else {$len=10;}

  $token = array();
  for ($i = 0; $i < $count; $i++) {
    $token[] = randomCode($len);
  }

  $appresult = array();
  $appresult["token"] = $token;
  echo json_encode($appresult);
}
function randomCode($length = 10) {
    $characters = '0123456789abcdefghjkmnrsuvwxyz';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
if($action == "updatetoken"){
  if (isset($_REQUEST['token'])){$token=$_REQUEST['token'];} else {$token="";}
  if (isset($_REQUEST['topic'])){$topic=$_REQUEST['topic'];} else {$topic="";}
  if (isset($_REQUEST['deviceID'])){$deviceID=intval($_REQUEST['deviceID']);} else {$deviceID=0;}
  if ($deviceID == 0){
    # Error #-2
    echo -2;
    exit;
  }
  # Vorhanden....
  $id = $db->rawQuery("UPDATE brrrz_devices SET bd_token='".$token."' WHERE bd_topic='".$topic."' AND bd_deviceID='".$deviceID."';", null);
  if($id){
    echo $id;
  } else {
    echo $db->getLastError();
  }
  #print_r($db->trace);
}


#
# Scriptende...
#
fwrite($file_handle, $db->trace."\r\n");
fclose($file_handle);
?>

Thank you. am trying it and will give you feedback. Most grateful for your urgent responds
 
Upvote 0

ronell

Well-Known Member
Licensed User
Longtime User
This i would not suggest. The old php-version may be removed from the server in the future. No provider will hold old, deprecated, versions on his servers for ever.
The right solution is to update the php-code to be php 7 compatible! And with this; compatible with online hosting providers too as they mostly uses up-to-date installations.
noted :)
 
Upvote 0

erasmusackon

Member
Licensed User
Longtime User
Thank you. am trying it and will give you feedback. Most grateful for your urgent responds

@DonManfred I Edited your code to look like this for my purpose. please can you confirm if am on the right track. am getting error meesage recvfrom failed.

B4X:
<?php
include_once("./MysqliDb.php");
$db = new MysqliDb (Array ('host' => 'xxxxx','username' => 'xxx', 'password' => 'eViV{5Z_fUxX', 'db'=> 'xxx', 'port' => 3306, 'prefix' => '', 'charset' => 'utf8'));

if (isset($_REQUEST['action'])){$action=strtolower($_REQUEST['action']);} else {$action="init";}

$db->setTrace (true);


if($action == "GetP"){
  $Devices = $db->rawQuery("SELECT * FROM DepositTransactions WHERE MemberID='".$memberid."';", null);
  echo json_encode($Devices);
}


#
# Scriptende...
#
fwrite($file_handle, $db->trace."\r\n");
fclose($file_handle);
?>
 
Upvote 0

erasmusackon

Member
Licensed User
Longtime User
is that the whole php code? can you show us your b4a code ?

I am trying my hands on different options and finally did additional search online and concluded on the script below but am getting this error: Java.net.SocketException:recvfrom failed: ECONNRESET (Connection reset by peer). same error as I applied @DonManfred option.

B4X:
<?
$databasehost = "www.xxxx.com";
$databasename = "xxxDB";
$databaseusername = "xxx2";
$databasepassword = "xxx";

$con = mysqli_connect($databasehost,$databaseusername,$databasepassword) or die(mysqli_error());
mysqli_set_charset ($con , "utf8");

if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$action = $_GET["action"];

switch ($action)

{
    case "CountPersons":
        $q = mysqli_query($con,"SELECT * FROM DepositTransactions WHERE MemberID=40001762");
        $count = mysqli_num_rows($q);
        print json_encode($count);
        mysqli_close($con);
    break;
  
    Case "GetPersons":
        $q = mysqli_query($con,"SELECT * FROM DepositTransactions WHERE MemberID=40001762");
        $rows = array();
        while($r = mysqli_fetch_assoc($q))
        {
            $rows[] = $r;
        }
        print json_encode($rows);
        mysqli_close($con);
    break;
  
    case "InsertNewPerson":
        $name = $_GET["name"];
        $age = $_GET["age"];
        $q = mysqli_query($con,"INSERT INTO UserRegister (CustomerName, CustomerNo) VALUES ('$name', $age)");
        print json_encode("Inserted");
        mysqli_close($con);
    break;
  
}

?>


B4X:
Sub GetPersonsButton_Click
    Dim GetPersons As HttpJob
    GetPersons.Initialize("GetP", Me)
    GetPersons.download2("http://" & ServerIP & "/app/sikacon.php", Array As String ("action", "GetPersons"))
End Sub

Sub JobDone(Job As HttpJob)
    ProgressDialogHide
    If Job.Success Then
       Dim res As String
        res = Job.GetString
        Log("Back from Job:" & Job.JobName )
        Log("Response from server: " & res)
              
        Dim parser As JSONParser
        parser.Initialize(res)
      
        Select Job.JobName
                      
            Case "GetP"
               Dim ListOfPersons As List
                Dim PersonName As String
                Dim PersonAge As Int
              
                ListOfPersons = parser.NextArray 'returns a list with maps
              
                PersonsListview.Clear
              
                If ListOfPersons.Size=0 Then
                   PersonsListview.AddSingleLine ("No persons found...")
                Else
                    For i = 0 To ListOfPersons.Size - 1
                        Dim Person As Map
                        Person = ListOfPersons.Get(i)
                                          
                        PersonName = Person.Get("AccountNumber")
                        PersonAge = Person.Get("MemberID")
                      
                        PersonsListview.AddSingleLine (PersonName & ", " & PersonAge)
                      
                    Next
                End If
      
            Case "CountP"
                PersonsListview.AddSingleLine ("Persons in table: " & parser.NextValue)
              
            Case "InsertNewP"
                'Do nothing
              
        End Select
      
      
      
    Else
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
    Job.Release
End Sub
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
On one hand I want to keep quiet, especially since this "rant" is not answering the original posters question. On the other hand, code like this

B4X:
$users = $db->rawQuery("SELECT bd_id FROM brrrz_devices WHERE bd_deviceID = '".$deviceID."' AND bd_topic='".$topic."';", null);

makes my skin crawl. Here we are building a dynamic SQL string. This should be a red flag for possible SQL INJECTION vectors. Now, we are using single quotes to escape the variables, but (big BUT for me), these variables are directly taking from the POST/GET variables, as seen by this code

B4X:
if (isset($_REQUEST['token'])){$token=$_REQUEST['token'];} else {$token="";}
if (isset($_REQUEST['topic'])){$topic=$_REQUEST['topic'];} else {$topic="";}
if (isset($_REQUEST['deviceID'])){$deviceID=intval($_REQUEST['deviceID']);} else {$deviceID=0;}

At minimum (not that I'm calling this correct), the following should have been done before building the string

B4X:
$topic = $db->escape($topic);
$deviceID = $db=>escape($deviceID);

Even then, you are not really save, see this post: https://stackoverflow.com/a/12118602
That post is a very long read, but should be read to see how clever attackers can be.

The proper way should have been:

B4X:
$users = $db->rawQuery('SELECT bd_id FROM brrrz_devices WHERE bd_deviceID = ? AND bd_topic=?', Array($deviceID, $topic));
(please note I'm not proficient in PHP, so some coding error may be in that statement).

Does this guarantee 100% SQL INJECTION protection? No, but now you are relying on the underlying DB's prepared statement mechanism to handle the variable escaping. If something is buggy with it, an updated library will take care of it. With the code as is, any issues need to be dealt with in the code and depending on how pervasive this is, it would mean a lot of changes in the code base.

An finally, another really good write up on why not to use dynamic SQL, with counters for pretty much every reason why one thinks dynamic SQL is necessary: The Curse and Blessings of Dynamic SQL.
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
meaning the hosting company has to check the server for me. Right?
I've noticed that you original post mentioned PHP errors. Did you receive them by going directly to the URL via a web browser or your Android App? Have you tried accessing your (new) PHP script via a web browser just to see if it produces the JSON that you are expecting?
 
Upvote 0

ronell

Well-Known Member
Licensed User
Longtime User
I've noticed that you original post mentioned PHP errors. Did you receive them by going directly to the URL via a web browser or your Android App? Have you tried accessing your (new) PHP script via a web browser just to see if it produces the JSON that you are expecting?
problem is in the hosting provider.. it will be the same error
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
problem is in the hosting provider.. it will be the same error
But why did he get a PHP error in the first post and now he's getting something different? What has changed? Or is he not getting a PHP error (via a browser) and just the App is having issues. The reason I'm asking is that a lot on the WWW seems to point to some keep-alive issues, but how can it be narrowed down to that if we don't even know if the script runs (for some reason it did in post#1, it just erred out because of deprecated function use).
 
Upvote 0

erasmusackon

Member
Licensed User
Longtime User
One more try! First: I'm not a PHP programmer, nor B4A, but I can read code. Here are my issues with this case.

1)
First post: PHP throws up an error message.
Solution: The site does not support old PHP functions.
Solutions proposed by w/some code by @DonManfred

2)
@erasmusackon comes back with some code in post#9. The problem is, this code should have not worked. Why? Because of:
B4X:
#
# Scriptende...
#
fwrite($file_handle, $db->trace."\r\n");
fclose($file_handle);
Nowhere in his code did he ever use fopen to assign a file handle to $file_handle. When accessing his script via a web browser, some sort of error message should have been shown/created/logged, no?

3)
@erasmusackon comes back with more code in post#11, reverting back to the old mysql functions. This makes no sense to me. I thought the server did not support the old functions? If so, the website will not produce a correct result.

What I'm getting at is that @erasmusackon should first have a proper PHP script that will produce an expected output when accessed via a web browser. Until that happens, we can say squat about why the Android app is not working or if the hosting provider is at fault with anything. Let's get one thing up and running first, before worrying about the other.

My 2 cents.

@OliverA Thanks. Am was trying to get the bottom of the error and currently the hosting service provider is checking why am getting Error:javax,net.ssl.SSLHandshakeExecption:SSL handshake aborted, I/O during system call, connection reset by peer.
 
Upvote 0
Top