Call MySQL stored function : with PHP/PD0
Objective :
  • Calling  MySQL Stored function
  • Using (PDO::FETCH_NUM)

 

Code : 1

<?php
/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'Manas9';

/*** mysql password ***/
$password = 'Manas9237';
//$mysqli = new mysqli("Manas9", "Manas9", "Manas9237", "test");
//$mysqli = new mysqli("localhost", "my_user", "my_password", "world");


try {

$dbconn= new PDO("mysql:host=$hostname;dbname=test", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Retreive of MySQL stored function with PDP <br />';
echo 'Connected to database<br />';
echo " Using (PDO::FETCH_NUM) <br/>";

/*** The SQL SELECT statement ***/
//$sql = "SELECT * FROM emp1 ORDER BY fname";
$sql= "SELECT ctof(29.25)";
/*** fetch into an PDOStatement object ***/
$stmt = $dbconn->query($sql);

/*** echo number of columns ***/
$result = $stmt->fetch(PDO::FETCH_NUM);
//$result = $stmt->fetch(PDO::FETCH_ASSOC);
// PDO::FETCH_NUM returns the row as a numerical array
/*** loop over the object directly ***/

foreach($result as $key=>$val)
{
echo "function Converting (ºC to ºF) row::". $key.' = '.$val.'<sup>0</sup>F<br />';
}

/*** close the database connection ***/
$dbconn= null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

Screen Shot

Code : 2
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'Manas9';
/* dbname */
$db = "test";
/*** mysql password ***/
$password = 'Manas9237';


try {

$dbconn= new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Retreive of MySQL stored function with PDP <br />';
echo 'Connected to database<br />';
echo "Using PDO::FETCH_ASSOC <br/>";
/*** The SQL SELECT statement ***/
//$sql = "SELECT * FROM emp1 ORDER BY fname";
$sql= "SELECT ctof(29.25)";
echo" fetch into an PDOStatement object <br/>";
$stmt = $dbconn->query($sql);

/*** echo number of columns ***/
//$result = $stmt->fetch(PDO::FETCH_NUM);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// PDO::FETCH_NUM returns the row as a numerical array
/*** loop over the object directly ***/

foreach($result as $key=>$val)
{
echo "function Celsius to Fahrenheit (ºC to ºF) ". $key.' = '.$val.'<br />';
}

/*** close the database connection ***/
$dbconn= null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Screenshot: