0

The code below successfully queries the value of an item called "name" from my database called Anagrafica.

$Db_RECORD = $db->query("SELECT name FROM Anagrafica WHERE ID=1")->fetchArray();
echo $results['name'];

Now I want to do the same but with an item called "email" which is in position 2 of an array called $arrayTextAreasNames[];.

I have tried with the code below but it doesn't work. It returns a void result.

$arrayTextAreasNames = array("name","surname","email");
$DbItemName = $arrayTextAreasNames[2];   

$Db_RECORD = $db->query("SELECT $DbItemName FROM Anagrafica WHERE ID=1")->fetchArray();
echo $results['email']; //Doesn't work (returns void)

Any idea why? Also, I don't manage to log the PHP variables on the web console! I am developing on Firefox and I even have Firefly's plugs in enabled. Thanks

jeddi
  • 651
  • 1
  • 12
  • 21

3 Answers3

0

$arrayItemHeading[2] = "email". So there isn't any result for name.

0

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.

  • I have edited the question with the actual names that I used in the code for the database and for its items. I used incorrect names ("database" and "ItemSelected") only formulating the answer but not in the code, so this is not the problem. – jeddi Jul 14 '17 at 07:33
  • @jeddi Ok. Why are you using `$Db_RECORD = $db->query...` and then `echo $results['name'];`? –  Jul 14 '17 at 07:38
  • Then you'll have to post the whole db connection/query code. It seems that there are errors/warnings/exceptions raised, which you are not displaying/catching. –  Jul 14 '17 at 09:09
0

Solved!

$Db_RECORD = $db->query("SELECT \"$DbItemName\" FROM Anagrafica WHERE ID=1")->fetchArray();

Many thanks for your help and useful suggestions anyway.

jeddi
  • 651
  • 1
  • 12
  • 21