I would like to make a general function to select last inserted id's of different tables.
I already tried multiple things, this might be the best effort (in db.inc.php);
<?php
define( 'DB_HOST', 'localhost' );
define( 'DB_NAME', 'modlar' );
define( 'DB_USER', 'root' );
define( 'DB_PASS', 'password' );
function verbinden(){
$verbinding = 'mysql:host=' . DB_HOST . ';DB_NAME=' . DB_NAME;
$db = null;
try{
return new PDO( $verbinding, DB_USER, DB_PASS );
}catch( PDOException $e ){
return NULL;
}
}
function loopdoor( $naam, $ding){
$regels = '';
if( is_array($ding) || is_object($ding)):
$wat = (is_array($ding)? 'array' : 'object');
$regels .= '<strong>'.$naam.'['.$wat.']</strong><ul>';
foreach( $ding as $k => $v):
$regels .= loopdoor( $k, $v);
endforeach;
$regels .= '</ul>';
else:
$regels .= '<li><strong>'.$naam.'</strong> => '.$ding.'</li>';
endif;
return $regels;
}
function last_id( &$db , $table, $column){
if( is_null( $db ) ) return array();
$sql = "
SELECT
max(modlar.table.column)
FROM
modlar.table";
$vraag = $db->prepare( $sql );
$vraag->bindValue( ':table', $table, PDO::PARAM_STR );
$vraag->bindValue( ':column', $column, PDO::PARAM_STR );
$vraag->execute();
return $vraag->fetchAll( PDO::FETCH_OBJ );
}
Where modlar is my database. And my variables (in db.php);
<?php
require_once 'db.inc.php';
// Verbinden met database
$db = verbinden();
if( is_null($db))
die('<h1>Error</h1>');
echo 'done';
$table = 'time';
$column = 'time_id';
$last = last_id($db, $table, $column);
echo '<ul>'.loopdoor('all data', $last).'</ul>';
?>
But I dont get any data on my screen (and no error). However, when I add the variables directly to the code, I'll get the last id of that table. So like;
$sql = "
SELECT
max(modlar.time.time_id)
FROM
modlar.time";
What is going wrong?
Related
Im stuck here: Fatal error: Call to a member function prepare() on null in C:\wamp64\www\covid19-rdc\wp-content\plugins\cov19-drc-form\inclus\cdf-functions.php on line 431.
Im building a wordpress plugin that contains a registration form. But trying to insert data through my plugin, Im getting this message. I've read similar issues online but none of them is close to my case. Im to nez to php, so please help.
Here is my connexion:
require_once plugin_dir_path(__FILE__) . 'cnx_bdd.php';
And the rest of the code is here below:
//Connexion to the db in the connexion file
$host = "localhost";
$db = "covid19rdc_db";
$user = "root";
$pass = "";
$charset = "utf8mb4";
try
{
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
//This is the function that saves the data
function save_data()
{
if ( isset($_POST['btnEnregistrer'] ) )
{
// sanitize entries
global $nomPat, $postnomPat, $prenomPat, $datenaisPat, $sexePat, $etatcivil, $nationalite_ID, $telPat, $emailPat, $domicilePat, $commune_ID, $ville, $paysvisites, $date_entree, $point_entree, $contactUrgence, $emailUrgence, $telUrgence, $catdeclarant, $fonction_agent, $commentaires;
$nomPat = sanitize_text_field( $_POST['nomPat'] );
$postnomPat = sanitize_text_field( $_POST['postnomPat'] );
$prenomPat = sanitize_text_field( $_POST['prenomPat'] );
$datenaisPat = $_POST['datenaisPat'];
$sexePat = $_POST['sexePat'];
$etatcivil = $_POST['etatcivil'];
$nationalite_ID = $_POST['nationalite_ID'];
$telPat = sanitize_text_field( $_POST['telPat'] );
$emailPat = sanitize_email( $_POST['emailPat'] );
$domicilePat = sanitize_text_field( $_POST['domicilePat'] );
$commune_ID = $_POST['commune_ID'];
$ville = sanitize_text_field( $_POST['ville'] );
$paysvisites = sanitize_text_field( $_POST['paysvisites'] );
$date_entree = $_POST['date_entree'];
$point_entree = sanitize_text_field( $_POST['point_entree'] );
$contactUrgence = sanitize_text_field( $_POST['contactUrgence'] );
$emailUrgence = sanitize_email( $_POST['emailUrgence'] );
$telUrgence = sanitize_text_field( $_POST['telUrgence'] );
$catdeclarant = $_POST['catdeclarant'];
$fonction_agent = sanitize_text_field( $_POST['fonction_agent'] );
$commentaires = sanitize_text_field( $_POST['commentaires'] );
$nomPat = $_POST['nomPat'] ;
$postnomPat = $_POST['postnomPat'] ;
$prenomPat = $_POST['prenomPat'] ;
$datenaisPat = $_POST['datenaisPat'];
$sexePat = $_POST['sexePat'];
$etatcivil = $_POST['etatcivil'];
$nationalite_ID = $_POST['nationalite_ID'];
$telPat = $_POST['telPat'] ;
$emailPat = $_POST['emailPat'] ;
$domicilePat = $_POST['domicilePat'] ;
$commune_ID = $_POST['commune_ID'];
$ville = $_POST['ville'] ;
$paysvisites = $_POST['paysvisites'] ;
$date_entree = $_POST['date_entree'];
$point_entree = $_POST['point_entree'] ;
$contactUrgence = $_POST['contactUrgence'] ;
$emailUrgence = $_POST['emailUrgence'] ;
$telUrgence = $_POST['telUrgence'] ;
$catdeclarant = $_POST['catdeclarant'];
$fonction_agent = $_POST['fonction_agent'] ;
$commentaires = $_POST['commentaires'] ;
// insert data
$sql = "INSERT INTO cov_patient(NomPatient, PostnomPatient, PrenomPatient, DateNaisPatient, SexePatient, EtatCivil, Nationalite_ID, TelPatient, EmailPatient, DomicilePatient, Commune_ID, Ville, PaysVisites, DateEntree, PointEntree, ContactUrgence, EmailUrgence, TelUrgence, CatDeclarant, FonctionAgent) VALUES (:nomPat, :postnomPat, :prenomPat, :datenaisPat, :sexePat, :etatcivil, :nationalite_ID, :telPat, :emailPat, :domicilePat, :commune_ID, :ville, :paysvisites, :date_entree, :point_entree, :contactUrgence, :emailUrgence, :telUrgence, :catdeclarant, :fonction_agent, :commentaires)";
$req = $pdo->prepare($sql);
$req-> execute(array(
":nomPat" => $nomPat,
":postnomPat" => $postnomPat,
":prenomPat" => $prenomPat,
":datenaisPat" => $datenaisPat,
":sexePat" => $sexePat ,
":etatcivil" => $etatcivil ,
":nationalite_ID" => $nationalite_ID ,
":telPat" => $telPat ,
":emailPat" => $emailPat ,
":domicilePat" => $domicilePat ,
":commune_ID" => $commune_ID ,
":ville" => $ville ,
":paysvisites" => $paysvisites ,
":date_entree" => $date_entree ,
":point_entree" => $point_entree ,
":contactUrgence" => $contactUrgence ,
":emailUrgence" => $emailUrgence ,
":telUrgence" => $telUrgence ,
":catdeclarant" => $catdeclarant ,
":fonction_agent" => $fonction_agent ,
":commentaires" => $commentaires
)
);
echo 'Success.';
}
else
{
//call the form creation function
mon_formulaire_covid19(
$nomPat,
$postnomPat,
$prenomPat,
$datenaisPat,
$sexePat,
$etatcivil,
$nationalite_ID,
$telPat,
$emailPat,
$domicilePat,
$commune_ID,
$ville,
$paysvisites,
$date_entree,
$point_entree,
$contactUrgence,
$emailUrgence,
$telUrgence,
$catdeclarant,
$fonction_agent,
$commentaires
);
}
}
You have a problem with the $pdo variable scope.
What you need to do is pass the $pdo to the function.
Assuming that all your code is located in cnx_bdd.php your save_data() function will need a parameter, like this save_data($pdo) {...}.
Now when calling the save_data function you can pass it the connection handle ($pdo) and everything will work.
Hope this helps.
when you are declaring $pdo it's in global scope...
try
{
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
but here inside this function you don't have reference to $pdo object...
function save_data()
{
...........
$req = $pdo->prepare($sql);
either you can declare your $pdo connection inside save_data() function or use global $pdo inside your save_data() function
Solution 1 :
function save_data()
{
...........
//Connexion to the db in the connexion file
$host = "localhost";
$db = "covid19rdc_db";
$user = "root";
$pass = "";
$charset = "utf8mb4";
try
{
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$req = $pdo->prepare($sql);
Solution 2 :
function save_data()
{
...........
global $pdo; //access $pdo db connection object
$req = $pdo->prepare($sql);
I already have read all about Sessions in PHP on stackoverflow but it haven't help. I have session class that was working on PHP 5.X, and I haven't been programing since.
I have been started about month ago again with PHP, but my session handler is invalid.
Please, can you help me?
<?php
<?php
/*
CREATE TABLE IF NOT EXISTS `sessions` (
`se_id` varchar(50) NOT NULL DEFAULT '',
`se_value` mediumblob,
`se_expires` int(11) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `sessions`
ADD PRIMARY KEY (`se_id`), ADD KEY `se_id` (`se_id`,`se_expires`);
*/
define( "MAXLIFETIME", 86400 );
define( "DSN", "mysql:host=localhost;dbname=demo" );
define( "DB_USER", "root" );
define( "DB_PASS", "whatever..." );
final class MYSession{
protected $_table_name = 'sessions';
protected $_primary_key = 'se_id';
protected $_where = array();
protected $_order_by = 'se_id';
protected $data = array( "se_id" => "",
"se_value" => "",
"se_expires" => ""
);
public $se_id;
public $se_id_old;
public $db;
private $sessionName;
//public $maxlifetime = get_cfg_var("session.gc_maxlifetime");
public $maxlifetime;
private $path;
private $domain;
private $secure;
private $httponly;
public function setParams(){
ini_set( 'session.gc_probability', 1 ) ;
ini_set( 'session.gc_divisor', 100 );
ini_set( "session.use_only_cookies", TRUE );
ini_set( "session.use_trans_sid", FALSE );
ini_set( "session.use_only_cookies", "1" );
ini_set( "session.entropy_file", "1" );
}
public function startSession( $sessionName, $maxlifetime = FALSE, $path = FALSE, $domain = FALSE, $secure = FALSE, $httponly = FALSE ){
$this->setParams();
if( $maxlifetime ){ $this->maxlifetime = $maxlifetime; }
else{ $this->maxlifetime = 0; }
if( $path ){ $this->path = $path; }
else{ $this->path = "/"; }
if( $domain ){ $this->domain = $domain; }
else{ $this->domain = NULL; }
if( $secure ){ $this->secure = $secure; }
else{ $this->secure = isset( $_SERVER[ 'HTTPS' ] ); }
if( $httponly ){ $this->httponly = $httponly; }
else{ $this->httponly = TRUE; }
$this->setSessionCookieData();
$this->sessionName = $sessionName;
session_name( $this->sessionName );
session_set_save_handler(
array( $this, "open" ),
array( $this, "close" ),
array( $this, "read" ),
array( $this, "write" ),
array( $this, "destroy" ),
array( $this, "gc" )
);
session_start();
session_regenerate_id( TRUE );
$this->se_id = session_id();
$this->gc( $this->maxlifetime );
return $this->se_id;
}
public function setSessionCookieData(){
return session_set_cookie_params( $this->maxlifetime, $this->path, $this->domain, $this->secure, $this->httponly );
}
public function getSessionCookieData(){
$sessionCookieDataArray = array();
$sessionCookieDataArray = session_get_cookie_params( );
return $sessionCookieDataArray;
}
//---------------------------------------------------------------------------------------------------
public function __destruct(){ session_write_close(); }
public function newSessid(){ return $this->se_id; }
public function oldSessid(){ return $this->se_id_old; }
public function open( $path, $se_id ){
try{
$this->db = new PDO( DSN, DB_USER, DB_PASS );
$this->db->setAttribute( PDO::ATTR_PERSISTENT, TRUE );
$this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $error ){ echo 'Error: '.$error->getMessage(); }
return TRUE;
}
public function close(){
$this->db = "";
return TRUE;
}
public function read( $se_id ){
$sql = "SELECT se_value FROM ". $this->_table_name. " WHERE se_id = :se_id";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->execute();
$result = $statement->fetch( PDO::FETCH_ASSOC );
}
catch( PDOException $error ){ die( "Unable to access to database read1" ); }
if( !empty( $result[ "se_value" ] ) ){
$sql = "UPDATE ". $this->_table_name. " SET se_expires = UNIX_TIMESTAMP( UTC_TIMESTAMP() ) WHERE se_id = :se_id";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->execute();
}
catch( PDOException $error ){ die( "Unable to access to database read2" ); }
}
return $result[ "se_value" ];
}
public function write( $se_id, $se_val ){
$sql = "SELECT * FROM " . $this->_table_name . " WHERE se_id = :se_id AND se_value = :se_val";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->bindValue( ":se_val", $se_val, PDO::PARAM_STR );
$statement->execute();
if( $statement->fetch() ){
$sql= "UPDATE ". $this->_table_name. " SET se_value = :se_val, se_expires = UNIX_TIMESTAMP( UTC_TIMESTAMP()) WHERE se_id = :se_id";
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->bindValue( ":se_val", $se_val, PDO::PARAM_STR );
$statement->execute();
}
else{
$sql = "INSERT INTO ". $this->_table_name. " ( se_id, se_value, se_expires ) VALUES( :se_id, :se_val, UNIX_TIMESTAMP( UTC_TIMESTAMP()) )";
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$statement->bindValue( ":se_val", $se_val, PDO::PARAM_STR );
$statement->execute();
}
}
catch( PDOException $error ){ die( "Unable to insert or update database" ); }
}
public function destroy( $se_id ){
$sql = "DELETE FROM ". $this->_table_name. " WHERE se_id = :se_id";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":se_id", $se_id, PDO::PARAM_STR );
$control_var= $statement->execute();
}
catch( PDOException $error ){ die( "Unable to destroy data in database" ); }
$this->gc( $this->maxlifetime );
return ( $control_var );
}
public function gc( $maxlifetime ){
$sql = "DELETE FROM ". $this->_table_name. " WHERE UNIX_TIMESTAMP( UTC_TIMESTAMP() ) - se_expires > :maxlifetime";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":maxlifetime", $this->maxlifetime, PDO::PARAM_INT );
$control_var = $statement->execute();
}
catch( PDOException $error ){ die( "Unable to select from database_" ); }
return ( $control_var );
}
public function regenerateId( ){
$this->gc( $this->maxlifetime );
$old_sessid = $this->se_id;
session_regenerate_id( TRUE );
$new_sessid = session_id();
$sql = "UPDATE ". $this->_table_name. " SET se_id = :new_sessid WHERE se_id = :old_sessid";
try{
$statement = $this->db->prepare( $sql );
$statement->bindValue( ":new_sessid", $new_sessid, PDO::PARAM_STR );
$statement->bindValue( ":old_sessid", $old_sessid, PDO::PARAM_STR );
$control_var = $statement->execute();
$this->se_id = $new_sessid;
$this->se_id_old = $old_sessid;
}
catch( PDOException $error ){ die( "Unable to select from database_REGID" ); }
return $new_sessid;
}
//---------------------------------------------------------------------------------------------------
public function destroySession(){
if( ini_get( "session.use_cookies" ) ){
$params = session_get_cookie_params();
setcookie( $this->sessionName, '',
time() - 42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
$_SESSION[ $this->sessionName ] = array();
unset( $_SESSION[ $this->sessionName ] );
session_unset( $this->sessionName );
session_destroy();
}
public function generateSessionName( $brojZnakova ){
return substr( $this->generateId(), 0, $brojZnakova );
}
//---------------------------------------------------------------------------------------------------
public function generateId(){ //private
$salt = 'x7^!bo3p,.$$!$6[&Q.#,//#i"%[X';
$random_number = mt_rand( 0, mt_getrandmax() );
$ip_address_fragment = md5( substr( $_SERVER['REMOTE_ADDR'], 0, 5 ) );
$timestamp = md5( microtime( TRUE ).time() );
$hash_data = $random_number . $ip_address_fragment . $salt . $timestamp;
$hash = hash( 'sha256', $hash_data ); //'sha256', 'haval160,4', 'md5'
return trim( $hash );
}
}
$newSession = new MYSession();
$newSession->setParams();
$newSession->startSession( 'newSession' );
?>
i am having some problem with my code, i try to simple insert some logs when user use search on my site.
Log should contains:
date in unix time -> using function for it
username -> its stored in Session
vin -> its string he post in input field
Top of the class
public $vin = null;
public function __construct( $data = array() )
{
if( isset( $data['vin'] ) )
$this->vin = stripslashes( strip_tags( $data['vin'] ) );
}
public function storeFormValues( $params )
{
$this->__construct( $params );
}
function code:
public function logFromSearch() {
$correct = false;
//$this->username = $_SESSION]['username'];
$date = new DateTime();
try {
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO logs(date, user, vin) VALUES(:date, :user, :vin)";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "date", $date->getTimestamp(), PDO::PARAM_STR );
$stmt->bindValue( "user", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
echo $this->vin;
echo $date->getTimestamp();
$stmt->execute();
return "Everything is OKEY";
} catch( PDOException $e ) {
return $e->getMessage();
}
}
Its not importing anything to database dispite the fact it should in my opinion. I try to debug it so i found out my way of adding username from session is not possible way and also find out that this->vin and $date->getTimestamp() is returning actual data which it should insert to database so can somebody help me to find where is the problem? (in same class i am using other function for database connection and they work find so its not in setting up connecting / db name and host and so on because its in different file)
P.S. Errors : I dont get any errors just single notice Notice: Undefined property: Data::$username which is understandable.
i am using simple code to get some data from DB based on some unique ID called VIN.
i wrote a script which work fine if somebody insert it in form, but now i need to edit to work more automaticly, and use $_GET['vin'] from URL and just display results based on that.
My try of code looks like:
public $vin = null;
public function __construct( $data = array() ) {
if( isset( $data['vin'] ) ) $this->vin = stripslashes( strip_tags( $data['vin'] ) );
}
public function storeFormValues( $params ) {
$this->__construct( $params );
}
public function fetchByVinEvidence($vin) {
$success = false;
try{
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM evidence_vin WHERE vin = :vin LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
$stmt->execute();
echo "<table>";
echo "<th>First Registration</th>";
echo "<th>Validity Until</th>";
echo "<th>Rpm</th>";
echo "<th>Max-Speed</th>";
echo "<th>Action</th>";
while ($row = $stmt->fetch()){
echo "<tr>";
echo "<td>24</td>";
echo "<td>".$row['claim_number']."</td>";
echo "<td>".$row['license']."</td>";
echo "<td>".$row['country']."</td>";
echo "<td>".$row['vin']."</td>";
echo "</tr>";
}
echo "</table>" ;
}catch(PDOExeption $e){
echo $e->getMessage();
echo $con->errorInfo();
}
return $success;
}
and call the function:
$vin = $_GET['vin'];
echo $vin;
$data = new Data;
$data->fetchByVinEvidence($vin);
Can somebody help me with that?
You pass a variable $vin to the function fetchByVinEvidence but then use the class level variable $this->vin instead of the passed one.
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
should be
$stmt->bindValue( "vin", $vin, PDO::PARAM_STR );
OR set the class level variable to the passed one at the start of the function if you need to use it elsehwere:
public function fetchByVinEvidence($vin) {
$this->vin = $vin;
....
public function __construct( $data = array() ) {
if( isset( $data['vin'] ) ) $this->vin = stripslashes( strip_tags( $data['vin'] ) );
}
__construct if waiting for an array, give it your $_GET directly :
$data = new Data($_GET); // and not $_GET['vin'] as it was the case before my edit
$data->fetchByVinEvidence($vin);
It was giving null because you didn't send anything to your constructor, so it used the default value : an empty array.
I need to get username, password etc from the wp-config file to connect to a custom PDO database.
Currently I have another file where I have this info, but I would like to only use the wp-config.
So how can I read the different properties of wp-config?
I have even defined my own constants in in wp-config.php and managed to retrieve them in theme without any includes.
wp-config.php
define('DEFAULT_ACCESS', 'employee');
functions.php
echo "DEFAULT_ACCESS :".DEFAULT_ACCESS;
outputs DEFAULT_ACCESS :employee
Here's some same code.
// ...Call the database connection settings
require( path to /wp-config.php );
// ...Connect to WP database
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if ( !$dbc ) {
die( 'Not Connected: ' . mysql_error());
}
// Select the database
$db = mysql_select_db(DB_NAME);
if (!$db) {
echo "There is no database: " . $db;
}
// ...Formulate the query
$query = "
SELECT *
FROM `wp_posts`
WHERE `post_status` = 'publish'
AND `post_password` = ''
AND `post_type` = 'post'
";
// ...Perform the query
$result = mysql_query( $query );
// ...Check results of the query and terminate the script if invalid results
if ( !$result ) {
$message = '<p>Invalid query.</p>' . "\n";
$message .= '<p>Whole query: ' . $query ."</p> \n";
die ( $message );
}
// Init a variable for the number of rows of results
$num_rows = mysql_num_rows( $result );
// Print the number of posts
echo "$num_rows Posts";
// Free the resources associated with the result set
if ( $result ) {
mysql_free_result( $result );
mysql_close();
}
I would just include the file then I would have access to the variable in it varibales.
<?php
require_once('wp-config.php');
echo DB_NAME;
?>
This is assuming you're on the same server and you can access wp-config.php through the file system.
If you're doing this for a plugin, these values are already available. You won't need to include the file again.
You can get all the global constants from wp-config.php simply echo the const like that:
<?php
echo DB_HOST;
echo DB_NAME;
echo DB_USER;
echo DB_PASSWORD;
Here is a function to read all WP DB defines:
function get_wordpress_data() {
$content = #file_get_contents( '../wp-config.php' );
if( ! $content ) {
return false;
}
$params = [
'db_name' => "/define.+?'DB_NAME'.+?'(.*?)'.+/",
'db_user' => "/define.+?'DB_USER'.+?'(.*?)'.+/",
'db_password' => "/define.+?'DB_PASSWORD'.+?'(.*?)'.+/",
'db_host' => "/define.+?'DB_HOST'.+?'(.*?)'.+/",
'table_prefix' => "/\\\$table_prefix.+?'(.+?)'.+/",
];
$return = [];
foreach( $params as $key => $value ) {
$found = preg_match_all( $value, $content, $result );
if( $found ) {
$return[ $key ] = $result[ 1 ][ 0 ];
} else {
$return[ $key ] = false;
}
}
return $return;
}
this returns an array like this:
array (size=5)
'db_name' => string '.........'
'db_user' => string '.........'
'db_password' => string '.........'
'db_host' => string 'localhost'
'table_prefix' => string 'wp_'
If you want to connect to DB, for current versions of PHP, using mysqli extention is recommended (mysql extention is going to deprecate):
require_once ("../wp-config.php"); // path to wp-config depends on your file locatoin
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Just add required wp-load.php file.
you can use all wordpress functionality like
get_recent_posts() and many more...