Php-mysql Course

When you perform a SELECT SQL query with PDO prepare() - execute() statements, the values of the columns in the result set are string type. Even if the columns in MySQL table contain numeric type values: integer (INT), or float (FLOAT /DECIMAL /DOUBLE), the values in the result set returned by PDO are string.
- The following example shows the data type and values of a SELECT query executed with PDO prepare() and execute().
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'root';
$passdb = 'pass';

try {
  // Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

  // Define the SQL statement that will be applied in prepare()
  $sql = "SELECT `id`, `name` FROM `users` WHERE `name`= :name LIMIT 1";
  $sqlprep = $conn->prepare($sql);        // Prepares and stores the SQL statement in $sqlprep

  $name = array('name'=>'admin');             // the value for ":name"
  // If the prepared SQL is succesfully executed, store the result set into a variable
  if($sqlprep->execute($name)) {
    $row = $sqlprep->fetchAll(PDO::FETCH_ASSOC);
  }
}
catch(PDOException $e) {
  $row = $e->getMessage();
}

var_dump($row);          // debug /show the result
?>
Debugged with var_dump(), shows this result:
array(1) { [0]=> array(2) { ["id"]=> string(1) "5" ["name"]=> string(5) "admin" } }
- As you can notice, the "id" value is returned as a string ("5"), but in the MySQL table, the "id" column is INT().

This conversion (numeric to string) in the result set can cause problems if we want to perform some PHP instructions according to exact value and data type of the "id" (when the equality is checked with three equal signs "===").
Example:
if($row[0]['id'] === 5) echo 'ID correct';
else echo 'The ID - '.$row[0]['id'].' not equal to 5';
- Because the value of the if($row[0]['id'] is "5" (not numeric 5), the code above will output:
The ID - 5 not equal to 5

If the equality is checked using two equal signs (==), it result: ID correct , because the "==" checks only the value, not data type.
But sometimes we must check data using the "===", especially when checks 0 against empty or null value.
So, the correct way is to have the numbers stored in numeric data type variables.

• Here's how you can have the numbers in the PDO result set returned as numeric type.
The following function (executeSQL()) receives a PDO object with the connection to MySQL database ($conn), and the SQL command ($sql). Stores each row into an array. Uses a foreach() loop, and the is_numeric() function to check the value of each column, if it's a number (integer, or float) adds 0, this will convert the string value into an integer, or float, without to modify the value.
This function returns the result set with the correct data type.
<?php
// execute SQL command and return the result set ( https://coursesweb.net )
function executeSQL($conn, $sql) {
  // prepare and execute the $sql query
  try {
    $reout = array();
    $sqlprep = $conn->prepare($sql);

    if($sqlprep->execute()) {
      // if fetch() returns at least one row (not false), adds the rows in $reout for return
      if(($row = $sqlprep->fetch(PDO::FETCH_ASSOC)) !== false){
        do {
          // check each column if it has numeric value, to cenvert it from "string"
          foreach($row AS $k=>$v) {
            if(is_numeric($v)) $row[$k] = $v + 0;
          }
          $reout[] = $row;
        }
        while($row = $sqlprep->fetch(PDO::FETCH_ASSOC));
      }
    } else {
      $eror = $conn->errorInfo();
      $reout[] = 'Error: '. $eror[2];
    }
  }
  catch(PDOException $e) {
    $reout[] = $e->getMessage();
  }

  return $reout;
}

// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'root';
$passdb = 'pass';

// Connect and create the PDO object
try {
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8
}
catch(PDOException $e) {
  $row = $e->getMessage();
}
// define the Select query, and calls the executeSQL() to get the selected rows
$sql = "SELECT `id`, `name` FROM `users` WHERE `name`='admin' LIMIT 1";
$rows = executeSQL($conn, $sql);

var_dump($rows);              // debug /show the result
?>
Result:
array(1) { [0]=> array(2) { ["id"]=> int(5) ["name"]=> string(5) "admin" } }
- As you can notice, this time the "id" is stored as integer (5).

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Integer and Float value in Select with PDO from string to numeric

Last accessed pages

  1. Get Mime Type of file or string content in PHP (6230)
  2. Countdown Timer with starting time added into a form (11533)
  3. Disable button and Enable it after specified time (17533)
  4. JpGraph - Create Graph, Charts, Plots in PHP (3933)
  5. Simple Admin Login PHP Script (10999)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (477)
  2. CSS cursor property - Custom Cursors (81)
  3. The Mastery of Love (71)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (64)
  5. CSS3 2D transforms (46)