I need to write a custom module/server extension in PHP to export a portion of my MySQL database.
I’m struggling to find the portion of code to invoke the current connection from wappler
(what otherwise would be something along the lines of $DBH = new PDO("mysql:host=".$DBHOST.";dbname=".$DBNAME."; charset=utf8", $DBUSER, $DBPASS);), so I can then run construct my queries and write a SQL file with their output.
I’m very new to Wappler so I could be wrong, but I don’t think it stores the connection info in variables. I found it as a string in dmxConnect/Modules/Connections/db.php when I was manually uploading files to another test server and the connection failed cause I needed to change the password.
That is correct. But there could be a built-in method or object in Wappler so that the data in file can be readily available as a connection string.
I haven’t looked into Wappler’s own files yet for the implementation, maybe that will give a clue. Best bet is to get this information from @patrick directly.
Here an example on how to use the db connection and the sql builder from server connect.
<?php
namespace modules;
use \lib\core\Module;
use \lib\db\Connection;
use \lib\db\SqlBuilder;
// create a module called dbuser
class dbuser extends Module
{
// get user from database
public function getuser($options) {
// connection option is required
option_require($options, 'connection');
// userid option is required
option_require($options, 'userid');
// parse expressions in the options
$options = $this->parseOptions($options);
// get the database connection
$connection = Connection.get($this->app, $options->connection);
// query
$query = 'SELECT * FROM Users WHERE UserId = ?';
// params
$params = array($options->userid);
// execute query
$results = $connection->execute($query, $params);
// return only first result or NULL when no results
return count($results) ? $results[0] : NULL;
}
// get user from database (using SqlBuilder)
public function getuser2($options) {
// connection option is required
option_require($options, 'connection');
// userid option is required
option_require($options, 'userid');
// parse expressions in the options
$options = $this->parseOptions($options);
// get the database connection
$connection = Connection.get($this->app, $options->connection);
// build the sql query and params
$sql = new SqlBuilder($this->app, $connection);
$sql->from('Users');
$sql->where('userid', '=', $options->userid);
// compile it
$sql->compile();
// execute query
$results = $connection->execute($sql->query, $sql->params);
// return only first result or NULL when no results
return count($results) ? $results[0] : NULL;
}
}