Your SlideShare is downloading. ×

Using php with my sql

384

Published on

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
384
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Connecting to MySQL and Selecting the Database Pengaturcaraan PHPPengaturcaraan PHPThe first step when dealing with the MySQL client and connecting to theserver requires the appropriately named mysql_connect() function: 1
  • 2. Pengaturcaraan PHPOnce you have connected to MySQL, you will need to select the databasewith which you want to work. This is the equivalent of saying USEdatabasename within the mysql client and is accomplished with themysql_select_ db() function:Lets start the demonstration of connecting to MySQL by creating a specialfile just for that purpose. Other PHP scripts that require a MySQL connectioncan include this file. Well also make use of the mysql_error() function.Pengaturcaraan PHPTo connect to and select a database, first create a new PHP document inyour text editor, mysql_connect.php.Connect PHP with mySQL<?$dbhost = "localhost";$dbname = “pentadbiran";$dbuser = “admin";$dbpass = “123456";mysql_connect("$dbhost","$dbuser","$dbpass");@mysql_select_db($dbname) or die( "Unable to select database");?> 2
  • 3. Pengaturcaraan PHPSince this file contains information thatmust be kept private, well use a .phpextension. By doing so, even ifmalicious users ran this script in theirWeb browser, they would not see thepages actual content. Be sure to savethe file as mysql_connect.php.Upload the file to your server, outsideof the Web document root. Becausethe file contains sensitive MySQLaccess information, it ought to bestored securely. If you can, place it inthe directory immediately above, orotherwise outside, of the Webdirectory. This way the file will not beaccessible from a Web browser.Pengaturcaraan PHPTemporarily place a copy of thescript within the Web documentroot and run the script in your Webbrowser. In order to test the script,youll want to place a copy on theserver so that its accessible fromthe Web browser (which means itmust be in the Web directory).If the script works properly, theresult should be a blank page. Ifyou see an "Access denied..." orsimilar message, it means that thecombination of username,password, and host does not havepermission to access the particulardatabase. 3
  • 4. Executing Simple QueriesPengaturcaraan PHPPengaturcaraan PHP The following is a simple PHP function for executing a query:For simple queries like INSERT, UPDATE, DELETE, etc. (which do notreturn records), the $result variable will be either TRUE or FALSEdepending upon whether the query executed successfully. For complexqueries that do return records (SELECT, SHOW, DESCRIBE, CREATE,and EXPLAIN), the $result variable will be a resource link to the resultsof the query if it worked, or be FALSE if it did not. 4
  • 5. Pengaturcaraan PHPRetrieve data with mySQL+PHPExample :$query="SELECT * FROM member where nokp=‘123456";$result=mysql_query($query);while ($myrow = mysql_fetch_array($result)){ $id=$myrow["id"]; $login=$myrow["login"]; print “$id - $login<br>”;}Pengaturcaraan PHPRetrieve data with mySQL+PHPContoh :$query="SELECT * FROM member where nokp=‘$nokp’";$result=mysql_query($query);while ($myrow = mysql_fetch_rows($result)){ $id=$myrow[0]; $login=$myrow[1];}print “$id - $login”; 5
  • 6. Pengaturcaraan PHPOne final, albeit optional, step in your script would be to close the existingMySQL connection once youre finished with it:This function is not required, because PHP will automatically close theconnection at the end of a script, but it does make for good programmingform to incorporate it. Retrieving Query Results Pengaturcaraan PHP 6
  • 7. Pengaturcaraan PHPThe primary tool for handling SELECT query results is mysql_fetch_array(),which takes the query result variable and returns one row of data at a time inan array format. Youll want to use this function within a loop that will continueto access every returned row as long as there are more to be read.The mysql_fetch_array() function takes an optional parameter specifying whattype of array is returned: associative, indexed, or both. An associative arrayallows you to refer to column values by name, whereas an indexed arrayrequires you to use only numbers (starting at 0 for the first column returned).Pengaturcaraan PHPEach parameter is defined by a constant. The MYSQL_NUM setting ismarginally faster (and uses less memory) than the other options. Conversely,MYSQL_ASSOC is more specific ($row[column] rather than $row[3]) and willcontinue to work even if the table structure or query changes.The table below lists the basic construction for reading every record from aquery. Adding one of these constants as an optional parameter to themysql_fetch_array() function dictates how you can access the values returned.The default setting of the function is MYSQL_BOTH. Constant Example MYSQL_ASSOC $row[0] or $row[column] MYSQL_NUM $row[0] MYSQL_BOTH $row[column] 7
  • 8. Pengaturcaraan PHPAn optional step you can take when using mysql_fetch_array() would beto free up the query result resources once you are done using them: Counting Returned Records Pengaturcaraan PHP 8
  • 9. Pengaturcaraan PHP The logical function mysql_num_rows()returns the number of rows retrieved by a SELECT query, taking the query result as a parameter.Pengaturcaraan PHPCount data with mysql+PHPExample :$names = mysql_query("SELECT * FROM member WHERE login=$login");$num = mysql_num_rows($names);Or$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROMmember where login=‘$login"),0);$total_pages = ceil($total_results); 9
  • 10. Updating Records with PHP Pengaturcaraan PHPPengaturcaraan PHPUpdate (single data) with mySQL+PHPContoh :mysql_db_query($dbname, “update table setnama=“ahmad” where nokp=‘123456");Ormysql_db_query($dbname, “update table setnama=“$nama” where nokp=‘$nokp"); 10
  • 11. Pengaturcaraan PHPUpdate (multiple data) with mySQL+PHPExample :mysql_db_query($dbname, “update table setnama=“ahmad”, jantina=“lelaki” where nokp=‘123456");Ormysql_db_query($dbname, “update table setnama=“$nama”, jantina=‘$jantina’ where nokp=‘$nokp"); Inserting Records Pengaturcaraan PHP 11
  • 12. Pengaturcaraan PHPInsert data with mySQL+PHPExamplemysql_db_query($dbname, "insert into $table values(,$nama,$nokp,$jantina)");Ormysql_db_query($dbname, "insert into membersvalues (,$nama,$nokp,$jantina)"); Deleting Records Pengaturcaraan PHP 12
  • 13. Pengaturcaraan PHPDelete Record with mySQL+PHPExample :mysql_db_query($dbname, "delete from $table wherenama=‘ahmad");Ormysql_db_query($dbname, "delete from $table wherenama=‘$nama"); End Pengaturcaraan PHP 13

×