PHP Handy notes the PHP script and Java connection MySQL database _php instance

Source: Internet
Author: User
Tags php script java web phpmyadmin

Environment

Development package: appserv-win32-2.5.10

Server: Apache2.2

Database: phpMyAdmin

Language: Php5,java

Platform: Windows 10

Java Driver: mysql-connector-java-5.1.37

Demand

Write a PHP scripting language that connects to the test library of the phpMyAdmin database

Write a Java Web server that connects to the test library of the phpMyAdmin database

Code

PHP connection mode

mysql.php

<?php
/*****************************
* Database connection
*****************************/
$conn = @mysql_ Connect ("localhost", "root", "123");
if (! $conn) {
  die ("Connection Database failed:". Mysql_error ());
}
mysql_select_db ("Test", $conn);
Character conversion, read library
mysql_query ("Set character set UTF8");
mysql_query ("Set names UTF8");
? >

test.php Test

<?php 
  error_reporting (0);     Prevent error
  include (' mysql.php ');
  $result =mysql_query ("SELECT * from user"); According to the previous calculation of the starting record and record number
  //cycle to take out the record
  $six;
  while ($row =mysql_fetch_row ($result))
  {  
  echo $row [0];
  echo $row [1];
  }
? >

Run Screenshots:

Java Connection method

1. Create a new Java project for Mysqltest

2. Load JDBC Driver, mysql-connector-java-5.1.37

Mysqlconnection.java

Package com.mysqltest;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.SQLException; * * * **MYSQL Connection * * * parameter: * conn connection * URL MySQL database connection address * User Database login account * Password Database login Password * Method: * Conn Get connection */PU
  Blic class Mysqlconnection {public static Connection conn = null;
  public static String Driver = "Com.mysql.jdbc.Driver";
  public static String URL = "Jdbc:mysql://127.0.0.1:3306/post";
  public static String user = "root";
  public static String password = "123";
   * * Create MySQL data connection The first step: Load driver Class.forName (Driver) Step two: Create connection * drivermanager.getconnection (URL, user, password);
    * * PUBLIC Connection Conn () {try {class.forname (driver);
      catch (ClassNotFoundException e) {System.out.println ("Driver load Error");
    E.printstacktrace ();
    try {conn = drivermanager.getconnection (URL, user, password);
      catch (SQLException e) {System.out.println ("Database link error");
    E.printstacktrace ();
  Return conn; }
} 

Work.java

Package com.mysqltest;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException; * * MySQL Add and delete change check/public class Work {* * * insert Increase * * public static int insert () {mysqlconnection Conne
    ction = new Mysqlconnection (); Connection Conns; Gets the connection PreparedStatement PST;
    Execute SQL statement int i = 0;
    String sql = "INSERT into user (Username,password) VALUES (?,?)";
      try {Conns = Connection.conn ();
      PST = conns.preparestatement (SQL);
      Pst.setstring (1, "Lizi");
      Pst.setstring (2, "123");
      i = Pst.executeupdate ();
      Pst.close ();
    Conns.close ();
      catch (SQLException e) {System.out.println ("Data write Failed");
    E.printstacktrace ();
  return i;
    /* * Select write/public static void Select () {mysqlconnection connection = new Mysqlconnection (); Connection Conns; Gets the connection PreparedStatement PST; Execute SQL statement (Statement) ResultSet rs; BeenFetch returns the result String sql = "SELECT * from user";
      try {Conns = Connection.conn ();
      PST = conns.preparestatement (SQL);
      rs = pst.executequery (sql);//Execute SQL statement System.out.println ("---------------------------------------");    System.out.println ("name |
      Password ");    while (Rs.next ()) {System.out.println (rs.getstring ("username") + |
      "+ rs.getstring (" password "));
      } System.out.println ("---------------------------------------");
      Conns.close ();
      Pst.close ();
    Rs.close ();
      catch (SQLException e) {System.out.println ("Data query failed");
    E.printstacktrace ();
    }/* Update modify */public static int update () {mysqlconnection connection = new Mysqlconnection (); Connection Conns; Gets the connection PreparedStatement PST;
    Execute SQL statement (Statement) int i = 0; String sql = "Update user set password =?"
    where username =? ";
      try {Conns = Connection.conn (); PST = conns.preparestatement (sqL);
      Pst.setstring (1, "123");
      Pst.setstring (2, "Lizi");
      i = Pst.executeupdate ();
      Pst.close ();
    Conns.close ();
      catch (SQLException e) {System.out.println ("Data modification failed");
    E.printstacktrace ();
  return i;
    }/* Delete deletion */public static int Delete () {mysqlconnection connection = new Mysqlconnection (); Connection Conns; Gets the connection PreparedStatement PST;
    Execute SQL statement (Statement) int i = 0;
    String sql = "Delete from user where username =?";
      try {Conns = Connection.conn ();
      PST = conns.preparestatement (SQL);
      Pst.setstring (1, "Lizi");
      i = Pst.executeupdate ();
      Pst.close ();
    Conns.close ();
      catch (SQLException e) {System.out.println ("Data deletion failed");
    E.printstacktrace ();
  return i;
     } * * Test/public static void main (string[] args) {//SYSTEM.OUT.PRINTLN (insert ());
    Select ();
    SYSTEM.OUT.PRINTLN (update ()); System.out.println (delete ());

 }
}

Test screenshot

Ps:php manipulate the statements in the MySQL database

We often use the conn.php file to establish a link to the database and then invoke it in the required files using include. This effectively prevents changes to database properties that cause other related file calls to the data to be wrong.

Now look at a conn.php file with the following code:

<?php
 $conn = @mysql_connect ("localhost", "root", "") or Die ("Database connection Error");//Linked database server
 mysql_select_db (" Messageboard ", $conn);//Select database name messageboard
 mysql_query (" Set names ' utf ');//Use UTF code, this cannot be written in utf-otherwise it will display garbled, But UTF is case-insensitive
 ?>

Learn to accumulate, collect a few basic functions of PHP operation MySQL:

Use the mysql_connect () function to connect to the MySQL server: mysql_connect ("hostname", "username", "password");
For example, $link = mysql_connect ("localhost", "root", "") or Die ("Cannot connect to the database server!"). The database server may not be started, or the username password is incorrect! ". Mysql_error ());

Select the database file using the mysql_select_db () function: mysql_query ("Use database name", $link);

For example, $db _selected=mysql_query ("Use example", $link);

Execute the SQL statement using the mysql_query () function: mysql_query (SQL statement), $link);

Such as:

Add Member: $result =mysql_query ("INSERT into tb_member values (' A ', ')", $link);

Modified member: $result =mysql_query ("Update tb_member setuser= ' B ', pwd= ' where user= ' a '", $link);

Delete Member: $result =mysql_query ("Delecte from Tb_member where user= ' B '", $link);

Inquiry member: $sql =mysql_query ("SELECT * from Tb_book");

Fuzzy query: $sql =mysql_query ("select * from Tb_book where bookname like '%". Trim ($txt _book). " %'");

A common character% represents 0 or any number of characters.

Display table structure: $result =mysql_query ("DESC tb_member");

. Use the Mysql_fetch_array () function to obtain information from an array result set:

Syntax structure: Array mysql_fetch_array (Resource Result[,int result_type])

Parameter result resource type parameter, shape parameter, the data pointer that is returned by the mysql_fetch_array () function;

Parameter result_type: Optional, PHP operation MYSQL Database statement Base integer parameters, to be passed to the MYSQL_ASSOC (Association Index), Mysql_num (digital Index) Mysql_both (including the first two, the default value)

Such as:

<> $sql =mysql_query ("SELECT * from Tb_book");
$info =mysql_fetch_object ($sql);
<> $sql =mysql_query ("select * from Tb_book where bookname like '%". Trim ($txt _book). " % ' ");
$info =mysql_fetch_object ($sql);

Use the Mysql_fetch_object () function to get a row from the result set as an object:

Grammatical structure: Object Mysql_fetch_object (resource result);

Such as:

<> $sql =mysql_query ("SELECT * from Tb_book");
$info =mysql_fetch_object ($sql);
<> $sql =mysql_query ("select * from Tb_book where bookname like '%". Trim ($txt _book). " %'");
$info =mysql_fetch_object ($sql);

The Mysql_fetch_object () function is similar to the mysql_fetch_array () function, with the distinction of returning an object instead of an array, which can only be accessed through the word Chinalai. Syntax structure to access the elements of a row in the result set: $row->col_name (column name)

. Use the Mysql_fetch_row () function to get each record in the result set one line at a row:

Syntax structure: Array mysql_fetch_row (resource result)

Such as:

<> $sql =mysql_query ("SELECT * from Tb_book");
$row =mysql_fetch_row ($sql);
<> $sql =mysql_query ("select * from Tb_book where bookname like '%". Trim ($txt _book). " %'");
$row =mysql_fetch_row ($sql);

. Use the Mysql_num_rows () function to get the number of records in the result set:

Syntax structure: int mysql_num_rows (resource result)

Such as:

$sql =mysql_query ("SELECT * from Tb_book");
......
<?php $nums =mysql_num_rows ($sql), Echo $nums;? >

Note: To get the data that is affected by the INSERT, UPDATE, and DELETE statements, you must use the Mysql_affected_rows () function to implement it.

. mysql_query ("Set names GB");//Set the encoding format for MySQL to be a GB type to mask garbled characters.

. Close the Recordset: Mysql_free_result ($sql);

. Close MySQL Database server: mysql_close ($conn);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.