MySQL Cast in PHP

In this article I explain how to use and what is the use of the MySQL cast function in PHP.
  • 2199

CAST Function

The MySQL cast function is used to mutate a value of one type (data type) to another type. In other words, the CAST() function takes a value of one type and produces a value of another type.

Syntax

cast (exp As Type)

The "Type" can have the following values:

  • Binary
  • Char
  • Date
  • DateTime
  • Decimal
  • Signed [integer]
  • Time
  • Unsigned [integer]

Example of CAST Function with PHP

The following is a sample use of the CAST Function with PHP; in the example, the CAST function converts a "DateTime" data type to a "DATE" data type.

<?php

$con=mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

mysql_select_db("mysql", $con);

print "<h2>MySQL: Simple Select statement</h2>";

$result = mysql_query("select * from mcnemployee");

echo "<table border='1'>

<tr>

<th>Firstname</th>

<th>Lastname</th>

<th>EmpId</th>

<th>EmpJoinDate</th>

</tr>";

while($row = mysql_fetch_array($result))

  {

  echo "<tr>";

  echo "<td>" . $row['emp_id'] . "</td>";

  echo "<td>" . $row['Fname'] . "</td>";

  echo "<td>" . $row['Lname'] . "</td>";

  echo "<td>" . $row['emp_JoinDate'] . "</td>";

  echo "</tr>";

  }

  echo "</table>";

 

  print "<h2>MySQL: With Cast Function</h2>";

$result = mysql_query("select CAST(emp_JoinDate as Date) As JoinDate from mcnemployee;");

echo "<table border='1'>

<tr>

<th>EmpJoinDate</th>

</tr>";+-

while($row = mysql_fetch_array($result))

  {

  echo "<td>" . $row['JoinDate'] . "</td>";

  echo "</tr>";

  }

  echo "</table>";

?>

Output 

mysql-cast-function-in-php.jpg

© 2020 DotNetHeaven. All rights reserved.