Home » Php » How can I bring data from MariaDB hosted in a server using a php file?

How can I bring data from MariaDB hosted in a server using a php file?

Posted by: admin February 25, 2020 Leave a comment


We have a remote server containing a SQL MariaDB. I have to write a piece of code to be placed in that same server whose mission is to execute querys asking for data, modify that data and send it to an external api hosted in another server. When I was shown the DB, it was through ssh commands and entering sql mode inside the server rather than trough code like PHP as I have always done it before.
So, my code is to placed in the same server as the DB, brings the data, modifys some info and calls the api to upload it.

As I said, I am completely lost so my question is simple: can this be achieved? if so, how?
I’ve read about ssh_connect and exec, but since the code will be placed in the same server I don’t think this is necessary, correct me if I am wrong. I can’t place any code since I don’t know how to start.

How to&Answers:

Thank you guys for all the help, I am closing the question now:
All I had to do was to use PDO as a secure way to establish a connection and to prepare and execute the querys. Remember I placed my php file in the same server that hosts the DB and note that I had to create a user and grant permissions to the DB you can find how in one of the comments above or here. Here is the code:

try {
    $conn = new PDO('mysql:host=yourhostserver;dbname=dbname','user','password');
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
    echo "ERROR: " . $e->getMessage();

//Example of query
$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids FROM cdr');
foreach ($stmt as $row) {
    $string = $row['ids'];