/////////////////////////////////////////////Task11 /////////////////////////////////////////
ECHO '
Task 11: MySQLi
';
$host = 'localhost';
$uname = 'lunexffg_draad';
$pword = 'draad123';
@ $db = new mysqli($host,$uname,$pword);
$connErr = $db->connect_error;
if($connErr != null){
echo "An error occurred while connecting to the server: $connErr";
die;
}
function setupDB(&$db){
$strSql = 'CREATE DATABASE IF NOT EXISTS lunexffg_main';
Echo 'Check/Create database: ';
//Execute the create check db
if ($db->query($strSql)){
Echo 'Successfull.
';
}else{
Echo 'Failed.
';
die;
}
//Connecto to database
@ $db = new mysqli($GLOBALS['host'],$GLOBALS['uname'],$GLOBALS['pword'],'lunexffg_main');
$connErr = $db->connect_error;
if($connErr != null){
echo "An error occurred while connecting to the database: $connErr";
die;
}
Echo 'Connection to Database Successfull.
';
$strSql = 'CREATE Table IF NOT EXISTS tblTask10(ID int not null Primary key,
GENDER varchar(1) not null,AGE int,EMPLOYED varchar(3) not null)';
Echo 'Check/Create tblTask10: ';
//Execute the create check Table
$db->query($strSql);
$strSql = "SHOW TABLES LIKE 'tblTask10'";
$result = $db->query($strSql);
if ($result == false){
Echo 'an unforseen database error prevented access to the table.
';
die;
}else{
$strSql = "Select * from tblTask10";
$results = $db->query($strSql);
if($results->num_rows == 0){
Echo 'Successfully created the table.
';
$strSql = "INSERT INTO tblTask10 (`ID`, `GENDER`, `AGE`, `EMPLOYED`) values
(1,'M',37,'YES'),(2,'M',63,'YES'),(3,'F',22,'YES'),(4,'F',22,'NO'),
(5,'M',34,'YES'),(6,'F',21,'NO'),(7,'F',25,'YES'),(8,'F',42,'NO'),
(9,'M',33,'NO'),(10,'M',27,'YES'),(11,'F',24,'YES'),(12,'M',39,'NO'),
(13,'M',31,'YES'),(14,'M',28,'YES'),(15,'F',52,'YES'),(16,'F',55,'NO')";
$result = $db->query($strSql);
Echo "Successfully added ". $db->affected_rows ." records.
";
}else{
Echo 'Successfull with '. $results->num_rows .' rows.
';
}
}
Echo '
';
}
setupDB($db);
$strSql = "SELECT * FROM tblTask10";
$result = $db->query($strSql);
Echo '';
Echo 'MySQLi All results Output';
Echo '';
Echo '';
Echo "| ID | GENDER | AGE | EMPLOYED | ";
Echo '
';
Echo '';
for ($i = 0; $i < $result->num_rows; $i++) :
$rowData = $result->fetch_assoc();
Echo '';
Echo "| ". $rowData['ID'] ." | ". $rowData['GENDER'] ." | ". $rowData['AGE'] ." | ". $rowData['EMPLOYED'] ." | ";
Echo '
';
endfor;
Echo '
';
$db->close();