Question 1:
If you're directly using $DbItemName
in the sql statement (SELECT $DbItemName FROM ...
), then an exception is raised:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '$DbItemName'
in 'field list'
Therefore you must use the PHP concatenation operator.
So, the solution is:
$db->query("SELECT " . $DbItemName . " FROM Anagrafica WHERE ID = 1")->fetchArray();
Notice: I discovered this problem because I used exception handling (see down under).
And I think you have a mistake here:
$Db_RECORD = $db->query(..)->fetchArray();
echo $results['name'];
It should be:
$results = $db->query(...)->fetchArray();
echo $results['name'];
The same is available for the code lines for fetching email.
Question 2:
Yes, you can pass PHP variables to the web console. The key lies in converting the PHP variables in a format recognized by Javascript. The common PHP-JS format is JSON. Therefore you must JSON-encode your php variables before sending them to JS, like this:
$varInPHP = array("abc", "def", 456);
$encodedVarToSendToJs = json_encode($varInPHP);
How do you send your vars to JS, in order to print them on the console with console.log(...)
? Well, there are more methods to do it. I don't want to reinvent the wheel, so I give you a very good link with them - including PROs and CONs:
When you have the vars in JS, then you can use them as you wish.
Some recommendations:
I would have some recommendations, if I may:
- Use prepared statements in order to avoid MySQL injection.
- Use exception handling in order to catch all errors and handle them correspondingly. Especially when you're running database operations.
- Enable error reporting on development.
If you are interested, I wrote a complete code - not OOP for current purposes - with prepared statements, exception handling and enabled error reporting. It uses PDO as data access layer, and MySQL. The only difference between sqlite and mysql access is the DSN string. Otherwise PDO is the same abstraction layer for accessing both RDBMS. Actually this is not so relevant, because the code just offers you a model.
Main page (index.php):
<?php
require_once 'Includes/configs.php';
require_once 'Includes/data_access.php';
require_once 'Includes/print.php';
require_once 'Includes/error_reporting.php';
activateErrorReporting(E_ALL, 1);
try {
$arrayItemHeading = array("name", "surname", "email");
$itemSelected = $arrayItemHeading[2];
$id = 1;
// Create db connection.
$connection = createConnection(MYSQL_HOST, MYSQL_DATABASE, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_PORT, MYSQL_CHARSET);
// Define sql statement.
$sql = 'SELECT `' . $itemSelected . '` FROM `Database` WHERE id = :id';
printData($sql, TRUE);
// Prepare and check sql statement (returns PDO statement).
$statement = $connection->prepare($sql);
if (!$statement) {
throw new Exception('The SQL statement can not be prepared!');
}
// Bind values to sql statement parameters.
$statement->bindValue(':id', $id, getInputParameterDataType($id));
// Execute and check PDO statement.
if (!$statement->execute()) {
throw new Exception('The PDO statement can not be executed!');
}
// Fetch person details.
$fetchedData = $statement->fetchAll(PDO::FETCH_ASSOC);
closeConnection($connection);
} catch (PDOException $pdoException) {
printData($pdoException, TRUE);
exit();
} catch (Exception $exception) {
printData($exception, TRUE);
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test code</title>
</head>
<body>
<?php
printData($fetchedData, TRUE);
?>
</body>
</html>
File configs.php:
<?php
/*
* ----------------
* Database configs
* ----------------
*/
define('MYSQL_HOST', '...');
define('MYSQL_PORT', '...');
define('MYSQL_DATABASE', '...');
define('MYSQL_CHARSET', 'utf8');
define('MYSQL_USERNAME', '...');
define('MYSQL_PASSWORD', '...');
File data_access.php:
<?php
/*
* ---------------------
* Data access functions
* ---------------------
*/
/**
* Create a new db connection.
*
* @param string $host Host.
* @param string $dbname Database name.
* @param string $username Username.
* @param string $password Password.
* @param string $port [optional] Port.
* @param array $charset [optional] Character set.
* @param array $options [optional] Driver options.
* @return PDO Db connection.
*/
function createConnection($host, $dbname, $username, $password, $port = '3306', $charset = 'utf8', $options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_PERSISTENT => true,
)) {
$dsn = getDsn($host, $dbname, $port, $charset);
$connection = new PDO($dsn, $username, $password);
foreach ($options as $key => $value) {
$connection->setAttribute($key, $value);
}
return $connection;
}
/**
* Create a mysql DSN string.
*
* @param string $host Host.
* @param string $dbname Database name.
* @param string $port [optional] Port.
* @param array $charset [optional] Character set.
* @return string DSN string.
*/
function getDsn($host, $dbname, $port = '3306', $charset = 'utf8') {
$dsn = sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s'
, $host
, $port
, $dbname
, $charset
);
return $dsn;
}
/**
* Close a db connection.
*
* @param PDO $connection Db connection.
* @return void
*/
function closeConnection($connection) {
$connection = NULL;
}
/**
* Get the data type of a binding value.
*
* @param mixed $value Binding value.
* @return mixed Data type of the binding value.
*/
function getInputParameterDataType($value) {
$dataType = PDO::PARAM_STR;
if (is_int($value)) {
$dataType = PDO::PARAM_INT;
} elseif (is_bool($value)) {
$dataType = PDO::PARAM_BOOL;
}
return $dataType;
}
File print.php:
<?php
/*
* ---------------------
* Print functions
* ---------------------
*/
/**
* Print data on screen.
*
* @param mixed $data Data to print.
* @param bool $preformatted Print preformatted if TRUE, print normal otherwise.
* @return void
*/
function printData($data, $preformatted = FALSE) {
if ($preformatted) {
echo '<pre>' . print_r($data, true) . '</pre>';
} else {
echo $data;
}
}
File error_reporting.php:
<?php
/*
* -------------------------
* Error reporting functions
* -------------------------
*/
/**
* Toggle error reporting.
*
* @param integer $level Error level.
* @param bool $display_errors Display errors if TRUE, hide them otherwise.
* @return void
*/
function activateErrorReporting($level = E_ALL, $display_errors = 1) {
error_reporting($level);
ini_set('display_errors', $display_errors);
}
Good luck!
EDIT 1:
Sorry, I had a typo in the solution sql statement. I corrected it.