SlideShare a Scribd company logo
PHP - MySQL For Beginners Author : Priti Solanki A tutorial only for beginners !!
PHP - MySQL Agenda INTRODUCTION   PREDEFINED CONSTANTS   EXPLORE PHP-MYSQL FUNCTION   REFERENCES Author : Priti Solanki
INTRODUCTION What is MySQL.         MySQL is an  open source SQL relational database          management system. How MySQL is related to PHP ?        Mysql acts as a back-end database server and helps in data  storage and manipulation of data stored at MySQL database server.   php.ini default setting for MYSQL extension is mysqli which is design to support mysql versions 4.1.3 and above php.ini setting for MySQL for version older than 4.1.3 Locate and Open php.ini. Search php_mysql.dll Uncomment - ;extension=php_mysql.dll" i.e. remove ";“ from front . Restart your http server. [What is php.ini please follow this link - http://www.slideshare.net/pritisolanki/understanding-phpini-presentation]
PREDEFINED CONSTANTS   Before exploring the mysql funtions one has to understand the predefined constants provided by the extension. MYSQL_CLIENT_COMPRESS  - This flag tells the client application to enable compression in the network protocol when talking to mysqld. MYSQL_CLIENT_IGNORE_SPACE  - Allow space after function names [http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html]. MYSQL_CLIENT_INTERACTIVE  - Allow interactive_timeout in seconds . interactive_timeout is a Mysql server system variabled which decide upon how many seconds the server waits for activity on an interactive connection before closing it.
PREDEFINED CONSTANT   MySQL fetch constants. MYSQL_ASSOC  - Columns are returned into the array having the fieldname as the array index.  MYSQL_BOTH  - Columns are returned into the array having both a numerical index and the fieldname as the array index.  MYSQL_NUM  - Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.  Now let us explore PHP-MySQL related funtions..........
PHP-MYSQL FUNCTION In "PHP MySQL Function" section I have tried to explore the commonly used functions and have also tried to answer some of the very basic questions which beginner developers might counter.   Question 1:  How to connect to mysql via php? Function name  : mysql_connect() Description : Open a connection to a MySQL server.On successful connection returns a MySQL link identifier and on failure will return FALSE. Syntax : resource mysql_connect  ([ string $server = ini_get("mysql.default_host")  [, string $username = ini_get("mysql.default_user")  [, string $password = ini_get("mysql.default_password")  [, bool $new_link = false  [, int $client_flags = 0  ]]]]] )
<?php /* Author Notes: Change $host,$user,$password as per you DB*/ $host='localhost'; $user='root'; $password='xxxx'; //get connect to mysql $link = mysql_connect($host,$user,$password); //check for connection if (!$link) {     die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; //close the DB connection mysql_close($link); ?> Save the code in testdb.php [in root folder]  and run http://localhost/testdb.php in the browser .If the string displays 'Connected successfully' on browser it means you are connected with the database succesfully.
If you have defined default host,username and password in php.ini then you can do get those variables as shown below. $host=ini_get(&quot;mysql.default_host&quot;); $username=ini_get(&quot;mysql.default_user&quot;); $password= ini_get(&quot;mysql.default_password&quot;); ini_get() is the php funtion to get the value of a configuration value.Setting ini value refer section [INTRODUCTION] above.
Question 2 : How to select table in database? Function name : mysql_select_db() Description : Select a MySQL database.Returns TRUE on success or FALSE on failure.  Syntax : bool mysql_select_db(string $database_name  [, resource $link_identifier]) Example : <?php /*Author's Notes - Get default setting from php.ini*/   $host=ini_get(&quot;mysql.default_host&quot;); $username=ini_get(&quot;mysql.default_user&quot;); $password= ini_get(&quot;mysql.default_password&quot;);
//get connect to mysql $link = mysql_connect($host,$username,$password); //check for connection if (!$link) {    die('Could not connect: ' . mysql_error());} echo 'Connected successfully <br/>'; $database='learndb'; if(mysql_select_db($database)) { echo &quot;we are working with database: &quot;.$database;} else {  echo &quot;There is some error: &quot;.mysql_error(); die();} //close the DB connection mysql_close($link); ?> Output: Connected successfully we are working with database: learndb
Question 3 : How to select values from MySQL tables?. Function : mysql_query($sql) Description :Send a MySQL query Syntax :resource mysql_query  ( string $query  [, resource $link_identifier  ] ) Example : Add following code before mysql_close($link) statement. //Start Querying table $selectSQL='select * from employee'; $resultSet=mysql_query($selectSQL); echo &quot;<table border='1'>&quot;; echo &quot;<tr><td><b>Name</b></td><td><b>Department</b></td><td><b>Designation</b></td></tr>&quot;;
while($recordSet= mysql_fetch_array($resultSet,MYSQL_ASSOC)) {     echo '<tr><td>'.$recordSet['EmployeeFirstName'].' '.$recordSet['EmployeeLastName'].'</td><td>'.$recordSet['Department'].'</td><td>'.$recordSet['Designation'].'</td></tr>'; } Output: Connected successfully we are working with database: learndb we are working with database: learndb Name            Department    Designation Kiba Inuzuka    IT        SE Naruto Uzamaki    IT        SSE . .
Function : mysql_fetch_assoc Description : Fetch a result row as an associative array.mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC. Syntax : array mysql_fetch_assoc  ( resource $result  ) Example : while($recordSet= mysql_fetch_array($resultSet,MYSQL_ASSOC)) {     echo '<tr><td>'.$recordSet['EmployeeFirstName'].' '.$recordSet['EmployeeLastName'].'</td><td>'.$recordSet['Department'].'</td><td>'.$recordSet['Designation'].'</td></tr>'; } Can be replaced like while($recordSet= mysql_fetch_assoc($resultSet)) {     echo '<tr><td>'.$recordSet['EmployeeFirstName'].' '.$recordSet['EmployeeLastName'].'</td><td>'.$recordSet['Department'].'</td><td>'.$recordSet['Designation'].'</td></tr>'; }
Function : mysql_fetch_row Description : Get a result row as an enumerated array.mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier   Syntax : array mysql_fetch_row  ( resource $result  )   Example : while($recordSet= mysql_fetch_row($resultSet)) {     echo '<tr><td>'.$recordSet[1].' '.$recordSet[2].'</td><td>'.$recordSet[3].'</td><td>'.$recordSet[4].'</td></tr>'; }
Function  : mysql_fetch_object Description : Fetch a result row as an object.Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows.  Syntax : object mysql_fetch_object  ( resource $result  [, string $class_name  [, array $params  ]] ) Example : while($recordSet= mysql_fetch_object($resultSet)) {     echo '<tr><td>'.$recordSet->EmployeeFirstName.' '.$recordSet->EmployeeLastName.'</td><td>'.$recordSet->Department.'</td><td>'.$recordSet->Designation.'</td></tr>'; }
Question : How to get the meta data of MySQL table? Function : mysql_fetch_field  Syntax : object mysql_fetch_field  ( resource $result  [, int $field_offset = 0  ] )   Description : Get column information from a result and return as an object.   Example :   /* get column metadata */ $i = 0; while ($i < mysql_num_fields($resultSet)) {     echo &quot;Information for column $i:<br />\n&quot;;     $meta = mysql_fetch_field($resultSet, $i);     if (!$meta) {         echo &quot;No information available<br />\n&quot;;     }      Program Contd..... Program Contd.....
echo &quot;<pre>     blob:         $meta->blob     max_length:   $meta->max_length     multiple_key: $meta->multiple_key     name:         $meta->name     not_null:     $meta->not_null     numeric:      $meta->numeric     primary_key:  $meta->primary_key     table:        $meta->table     type:         $meta->type     default:      $meta->def     unique_key:   $meta->unique_key     unsigned:     $meta->unsigned     zerofill:     $meta->zerofill     </pre>&quot;;     $i++; } mysql_fetch_field - Get number of fields in result.
So.... It seems by now we have done a pretty good job in understanding the basic of DB programming in PHP.  But how to perform DML statements ??? update ,insert or delete!!!! To insert,Update and Delete SQL Statement you simply have to write your query and send to Mysql to execute. //Create your query $selectSQL='INSERT INTO `learndb`.`employee` (`EmployeeId` ,`EmployeeFirstName` ,`EmployeeLastName` ,`Department` ,`Designation`)VALUES (NULL , 'Masashi', 'Kishimoto ', 'IS', 'SA')'; //Send  the query to mysql server to execut $resultSet=mysql_query($selectSQL); Similar for the Update and Delete statements.
DATABASE SCRIPT   CREATE DATABASE `LearnDB` ;  CREATE TABLE `learndb`.`Employee` ( `EmployeeId` TINYINT( 11 ) NOT NULL , `EmployeeFirstName` VARCHAR( 25 ) NOT NULL , `EmployeeLastName` VARCHAR( 25 ) NOT NULL , `Department` ENUM( 'IT', 'Admin', 'HR', 'IS' ) NOT NULL , `Designation` ENUM( 'SE', 'SSE', 'APM', 'DM', 'PM', 'SA','HR','TL' ) NOT NULL , PRIMARY KEY ( `EmployeeId` ) ) ENGINE = MYISAM ;
DATABASE SCRIPT INSERT INTO `employee` (`EmployeeId`, `EmployeeFirstName`, `EmployeeLastName`, `Department`, `Designation`) VALUES (1, 'Kiba', 'Inuzuka', 'IT', 'SE'), (2, 'Naruto', 'Uzamaki', 'IT', 'SSE'), (3, 'Sakura', 'Chan', 'HR', 'HR'), (4, 'Kakashi', 'Hatake ', 'IT', 'PM'), (5, 'Minato', 'Namikaze', 'IT', 'DM'), (6, 'Gai ', 'sensi', 'IS', 'TL'), (7, 'Sasuke', 'uchiha', 'Admin', 'APM'), (8, 'Hinata', 'Hyuuga ', 'IT', 'PM'), (9, ' Shino ', 'Aburame', 'Admin', 'HR'), (10, ' Kurenai ', 'Yuhi', 'IT', 'TL'), (11, ' Choji ', 'Akimichi', 'IT', 'SSE'), (12, 'Shikamaru', 'Nara', 'IT', 'APM'), (13, ' Ino ', 'Yamanaka', 'Admin', 'PM'), (14, ' Asuma ', 'Sarutobi', 'IT', 'TL'), (15, ' Neji ', 'Hyuga', 'IT', 'PM'), (16, ' Iruka ', 'Umino', 'Admin', 'SA'), (17, 'Konohamaru ', 'Sarutobi', 'IT', 'SE');
REFERENCES Author : Priti Solanki http://php.net/ http://www.mysql.com/ Explore more php-mysql funtions :http://in3.php.net/manual/en/ref.mysql.php So here I finish my attempt to make you understand the basics of database programming with PHP-MySQL.I believe by now you must be confident enough to implement these functions in your project as per your requirement. Spend great time with php-mysql funtions. I request readers to drop in their comments to modify and improve this presentation for total beginners. If there are questions or any example is not clear please write to me at. [email_address]

More Related Content

What's hot (20)

Short Intro to PHP and MySQL
Short Intro to PHP and MySQLShort Intro to PHP and MySQL
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
Bradley Holt
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
Azharul Haque Shohan
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
php
phpphp
php
ajeetjhajharia
 
Sah
SahSah
Sah
sahul azzez m.i
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
Fabien Potencier
 
Php mysql
Php mysqlPhp mysql
Php mysql
Manish Jain
 
PHP Function
PHP Function PHP Function
PHP Function
Reber Novanta
 
New: Two Methods of Installing Drupal on Windows XP with XAMPP
New: Two Methods of Installing Drupal on Windows XP with XAMPPNew: Two Methods of Installing Drupal on Windows XP with XAMPP
New: Two Methods of Installing Drupal on Windows XP with XAMPP
Rupesh Kumar
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
Shashank Skills Academy
 
Introduction to php web programming - get and post
Introduction to php  web programming - get and postIntroduction to php  web programming - get and post
Introduction to php web programming - get and post
baabtra.com - No. 1 supplier of quality freshers
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
Santhiya Grace
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
Tom Praison Praison
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
Arjun Shanka
 
Short Intro to PHP and MySQL
Short Intro to PHP and MySQLShort Intro to PHP and MySQL
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
Bradley Holt
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
Azharul Haque Shohan
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
Fabien Potencier
 
New: Two Methods of Installing Drupal on Windows XP with XAMPP
New: Two Methods of Installing Drupal on Windows XP with XAMPPNew: Two Methods of Installing Drupal on Windows XP with XAMPP
New: Two Methods of Installing Drupal on Windows XP with XAMPP
Rupesh Kumar
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
Santhiya Grace
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
Arjun Shanka
 

Similar to Php MySql For Beginners (20)

Php verses my sql
Php verses my sqlPhp verses my sql
Php verses my sql
SEO Training in Chandigarh
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
CBitss Technologies
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
CBitss Technologies
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
Information Technology
 
PHP 5 + MySQL 5 = A Perfect 10
PHP 5 + MySQL 5 = A Perfect 10PHP 5 + MySQL 5 = A Perfect 10
PHP 5 + MySQL 5 = A Perfect 10
Adam Trachtenberg
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian
phelios
 
Introtodatabase 1
Introtodatabase 1Introtodatabase 1
Introtodatabase 1
Digital Insights - Digital Marketing Agency
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
natesanp1234
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
NIRMAL FELIX
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
Amit Kumar Singh
 
chapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptxchapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptx
Getawu
 
MYSQL
MYSQLMYSQL
MYSQL
ARJUN
 
lab56_db
lab56_dblab56_db
lab56_db
tutorialsruby
 
lab56_db
lab56_dblab56_db
lab56_db
tutorialsruby
 
Mysql
MysqlMysql
Mysql
lotlot
 
My sql.ppt
My sql.pptMy sql.ppt
My sql.ppt
MAGNA COLLEGE OF ENGINEERING
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
wahidullah mudaser
 
MYSQL-Database
MYSQL-DatabaseMYSQL-Database
MYSQL-Database
V.V.Vanniaperumal College for Women
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
Ad

Recently uploaded (20)

Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Ad

Php MySql For Beginners

  • 1. PHP - MySQL For Beginners Author : Priti Solanki A tutorial only for beginners !!
  • 2. PHP - MySQL Agenda INTRODUCTION   PREDEFINED CONSTANTS   EXPLORE PHP-MYSQL FUNCTION   REFERENCES Author : Priti Solanki
  • 3. INTRODUCTION What is MySQL.        MySQL is an  open source SQL relational database         management system. How MySQL is related to PHP ?       Mysql acts as a back-end database server and helps in data storage and manipulation of data stored at MySQL database server.   php.ini default setting for MYSQL extension is mysqli which is design to support mysql versions 4.1.3 and above php.ini setting for MySQL for version older than 4.1.3 Locate and Open php.ini. Search php_mysql.dll Uncomment - ;extension=php_mysql.dll&quot; i.e. remove &quot;;“ from front . Restart your http server. [What is php.ini please follow this link - http://www.slideshare.net/pritisolanki/understanding-phpini-presentation]
  • 4. PREDEFINED CONSTANTS   Before exploring the mysql funtions one has to understand the predefined constants provided by the extension. MYSQL_CLIENT_COMPRESS - This flag tells the client application to enable compression in the network protocol when talking to mysqld. MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names [http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html]. MYSQL_CLIENT_INTERACTIVE - Allow interactive_timeout in seconds . interactive_timeout is a Mysql server system variabled which decide upon how many seconds the server waits for activity on an interactive connection before closing it.
  • 5. PREDEFINED CONSTANT   MySQL fetch constants. MYSQL_ASSOC - Columns are returned into the array having the fieldname as the array index. MYSQL_BOTH - Columns are returned into the array having both a numerical index and the fieldname as the array index. MYSQL_NUM - Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result. Now let us explore PHP-MySQL related funtions..........
  • 6. PHP-MYSQL FUNCTION In &quot;PHP MySQL Function&quot; section I have tried to explore the commonly used functions and have also tried to answer some of the very basic questions which beginner developers might counter.   Question 1:  How to connect to mysql via php? Function name : mysql_connect() Description : Open a connection to a MySQL server.On successful connection returns a MySQL link identifier and on failure will return FALSE. Syntax : resource mysql_connect  ([ string $server = ini_get(&quot;mysql.default_host&quot;)  [, string $username = ini_get(&quot;mysql.default_user&quot;)  [, string $password = ini_get(&quot;mysql.default_password&quot;)  [, bool $new_link = false  [, int $client_flags = 0  ]]]]] )
  • 7. <?php /* Author Notes: Change $host,$user,$password as per you DB*/ $host='localhost'; $user='root'; $password='xxxx'; //get connect to mysql $link = mysql_connect($host,$user,$password); //check for connection if (!$link) {     die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; //close the DB connection mysql_close($link); ?> Save the code in testdb.php [in root folder]  and run http://localhost/testdb.php in the browser .If the string displays 'Connected successfully' on browser it means you are connected with the database succesfully.
  • 8. If you have defined default host,username and password in php.ini then you can do get those variables as shown below. $host=ini_get(&quot;mysql.default_host&quot;); $username=ini_get(&quot;mysql.default_user&quot;); $password= ini_get(&quot;mysql.default_password&quot;); ini_get() is the php funtion to get the value of a configuration value.Setting ini value refer section [INTRODUCTION] above.
  • 9. Question 2 : How to select table in database? Function name : mysql_select_db() Description : Select a MySQL database.Returns TRUE on success or FALSE on failure. Syntax : bool mysql_select_db(string $database_name  [, resource $link_identifier]) Example : <?php /*Author's Notes - Get default setting from php.ini*/   $host=ini_get(&quot;mysql.default_host&quot;); $username=ini_get(&quot;mysql.default_user&quot;); $password= ini_get(&quot;mysql.default_password&quot;);
  • 10. //get connect to mysql $link = mysql_connect($host,$username,$password); //check for connection if (!$link) {    die('Could not connect: ' . mysql_error());} echo 'Connected successfully <br/>'; $database='learndb'; if(mysql_select_db($database)) { echo &quot;we are working with database: &quot;.$database;} else {  echo &quot;There is some error: &quot;.mysql_error(); die();} //close the DB connection mysql_close($link); ?> Output: Connected successfully we are working with database: learndb
  • 11. Question 3 : How to select values from MySQL tables?. Function : mysql_query($sql) Description :Send a MySQL query Syntax :resource mysql_query  ( string $query  [, resource $link_identifier  ] ) Example : Add following code before mysql_close($link) statement. //Start Querying table $selectSQL='select * from employee'; $resultSet=mysql_query($selectSQL); echo &quot;<table border='1'>&quot;; echo &quot;<tr><td><b>Name</b></td><td><b>Department</b></td><td><b>Designation</b></td></tr>&quot;;
  • 12. while($recordSet= mysql_fetch_array($resultSet,MYSQL_ASSOC)) {     echo '<tr><td>'.$recordSet['EmployeeFirstName'].' '.$recordSet['EmployeeLastName'].'</td><td>'.$recordSet['Department'].'</td><td>'.$recordSet['Designation'].'</td></tr>'; } Output: Connected successfully we are working with database: learndb we are working with database: learndb Name            Department    Designation Kiba Inuzuka    IT        SE Naruto Uzamaki    IT        SSE . .
  • 13. Function : mysql_fetch_assoc Description : Fetch a result row as an associative array.mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC. Syntax : array mysql_fetch_assoc  ( resource $result  ) Example : while($recordSet= mysql_fetch_array($resultSet,MYSQL_ASSOC)) {     echo '<tr><td>'.$recordSet['EmployeeFirstName'].' '.$recordSet['EmployeeLastName'].'</td><td>'.$recordSet['Department'].'</td><td>'.$recordSet['Designation'].'</td></tr>'; } Can be replaced like while($recordSet= mysql_fetch_assoc($resultSet)) {     echo '<tr><td>'.$recordSet['EmployeeFirstName'].' '.$recordSet['EmployeeLastName'].'</td><td>'.$recordSet['Department'].'</td><td>'.$recordSet['Designation'].'</td></tr>'; }
  • 14. Function : mysql_fetch_row Description : Get a result row as an enumerated array.mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier   Syntax : array mysql_fetch_row  ( resource $result  )   Example : while($recordSet= mysql_fetch_row($resultSet)) {     echo '<tr><td>'.$recordSet[1].' '.$recordSet[2].'</td><td>'.$recordSet[3].'</td><td>'.$recordSet[4].'</td></tr>'; }
  • 15. Function : mysql_fetch_object Description : Fetch a result row as an object.Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows. Syntax : object mysql_fetch_object  ( resource $result  [, string $class_name  [, array $params  ]] ) Example : while($recordSet= mysql_fetch_object($resultSet)) {     echo '<tr><td>'.$recordSet->EmployeeFirstName.' '.$recordSet->EmployeeLastName.'</td><td>'.$recordSet->Department.'</td><td>'.$recordSet->Designation.'</td></tr>'; }
  • 16. Question : How to get the meta data of MySQL table? Function : mysql_fetch_field Syntax : object mysql_fetch_field  ( resource $result  [, int $field_offset = 0  ] )   Description : Get column information from a result and return as an object.   Example :   /* get column metadata */ $i = 0; while ($i < mysql_num_fields($resultSet)) {     echo &quot;Information for column $i:<br />\n&quot;;     $meta = mysql_fetch_field($resultSet, $i);     if (!$meta) {         echo &quot;No information available<br />\n&quot;;     }     Program Contd..... Program Contd.....
  • 17. echo &quot;<pre>     blob:         $meta->blob     max_length:   $meta->max_length     multiple_key: $meta->multiple_key     name:         $meta->name     not_null:     $meta->not_null     numeric:      $meta->numeric     primary_key:  $meta->primary_key     table:        $meta->table     type:         $meta->type     default:      $meta->def     unique_key:   $meta->unique_key     unsigned:     $meta->unsigned     zerofill:     $meta->zerofill     </pre>&quot;;     $i++; } mysql_fetch_field - Get number of fields in result.
  • 18. So.... It seems by now we have done a pretty good job in understanding the basic of DB programming in PHP. But how to perform DML statements ??? update ,insert or delete!!!! To insert,Update and Delete SQL Statement you simply have to write your query and send to Mysql to execute. //Create your query $selectSQL='INSERT INTO `learndb`.`employee` (`EmployeeId` ,`EmployeeFirstName` ,`EmployeeLastName` ,`Department` ,`Designation`)VALUES (NULL , 'Masashi', 'Kishimoto ', 'IS', 'SA')'; //Send  the query to mysql server to execut $resultSet=mysql_query($selectSQL); Similar for the Update and Delete statements.
  • 19. DATABASE SCRIPT   CREATE DATABASE `LearnDB` ;  CREATE TABLE `learndb`.`Employee` ( `EmployeeId` TINYINT( 11 ) NOT NULL , `EmployeeFirstName` VARCHAR( 25 ) NOT NULL , `EmployeeLastName` VARCHAR( 25 ) NOT NULL , `Department` ENUM( 'IT', 'Admin', 'HR', 'IS' ) NOT NULL , `Designation` ENUM( 'SE', 'SSE', 'APM', 'DM', 'PM', 'SA','HR','TL' ) NOT NULL , PRIMARY KEY ( `EmployeeId` ) ) ENGINE = MYISAM ;
  • 20. DATABASE SCRIPT INSERT INTO `employee` (`EmployeeId`, `EmployeeFirstName`, `EmployeeLastName`, `Department`, `Designation`) VALUES (1, 'Kiba', 'Inuzuka', 'IT', 'SE'), (2, 'Naruto', 'Uzamaki', 'IT', 'SSE'), (3, 'Sakura', 'Chan', 'HR', 'HR'), (4, 'Kakashi', 'Hatake ', 'IT', 'PM'), (5, 'Minato', 'Namikaze', 'IT', 'DM'), (6, 'Gai ', 'sensi', 'IS', 'TL'), (7, 'Sasuke', 'uchiha', 'Admin', 'APM'), (8, 'Hinata', 'Hyuuga ', 'IT', 'PM'), (9, ' Shino ', 'Aburame', 'Admin', 'HR'), (10, ' Kurenai ', 'Yuhi', 'IT', 'TL'), (11, ' Choji ', 'Akimichi', 'IT', 'SSE'), (12, 'Shikamaru', 'Nara', 'IT', 'APM'), (13, ' Ino ', 'Yamanaka', 'Admin', 'PM'), (14, ' Asuma ', 'Sarutobi', 'IT', 'TL'), (15, ' Neji ', 'Hyuga', 'IT', 'PM'), (16, ' Iruka ', 'Umino', 'Admin', 'SA'), (17, 'Konohamaru ', 'Sarutobi', 'IT', 'SE');
  • 21. REFERENCES Author : Priti Solanki http://php.net/ http://www.mysql.com/ Explore more php-mysql funtions :http://in3.php.net/manual/en/ref.mysql.php So here I finish my attempt to make you understand the basics of database programming with PHP-MySQL.I believe by now you must be confident enough to implement these functions in your project as per your requirement. Spend great time with php-mysql funtions. I request readers to drop in their comments to modify and improve this presentation for total beginners. If there are questions or any example is not clear please write to me at. [email_address]