


PHP casual notes organization PHP script and JAVA connect to mysql database, javamysql_PHP tutorial
PHP casual notes organized PHP script and JAVA to connect mysql database, javamysql
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 script language and connect to the test library of phpMyAdmin database
Write a java web server and connect to the test library of phpMyAdmin database
Code
php connection method
mysql.php
<?php /***************************** *数据库连接 *****************************/ $conn = @mysql_connect("localhost","root","123"); if (!$conn){ die("连接数据库失败:" . mysql_error()); } mysql_select_db("test", $conn); //字符转换,读库 mysql_query("set character set utf8"); mysql_query("set names utf8"); ?>
test.php test
<?php error_reporting(0); //防止报错 include('mysql.php'); $result=mysql_query("select * from user"); //根据前面的计算出开始的记录和记录数 // 循环取出记录 $six; while($row=mysql_fetch_row($result)) { echo $row[0]; echo $row[1]; } ?>
Running screenshot:
java connection method
1. Create a new java project as 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连接** * * 参数: * conn 连接 * url mysql数据库连接地址 * user 数据库登陆账号 * password 数据库登陆密码 * 方法: * conn 获取连接 */ public 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"; /* * 创建Mysql数据连接 第一步:加载驱动 Class.forName(Driver) 第二步:创建连接 * DriverManager.getConnection(url, user, password); */ public Connection conn() { try { Class.forName(driver); } catch (ClassNotFoundException e) { System.out.println("驱动加载错误"); e.printStackTrace(); } try { conn = DriverManager.getConnection(url, user, password); } catch (SQLException e) { System.out.println("数据库链接错误"); 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增删改查 */ public class Work { /* * insert 增加 */ public static int insert() { MySQLConnection connection = new MySQLConnection(); Connection conns; // 获取连接 PreparedStatement pst; // 执行Sql语句 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("数据写入失败"); e.printStackTrace(); } return i; } /* * select 写入 */ public static void select() { MySQLConnection connection = new MySQLConnection(); Connection conns; // 获取连接 PreparedStatement pst; // 执行Sql语句(Statement) ResultSet rs; // 获取返回结果 String sql = "select * from user"; try { conns = connection.conn(); pst = conns.prepareStatement(sql); rs = pst.executeQuery(sql);// 执行sql语句 System.out.println("---------------------------------------"); System.out.println("名字 | 密码"); 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("数据查询失败"); e.printStackTrace(); } } /* * update 修改 */ public static int update() { MySQLConnection connection = new MySQLConnection(); Connection conns; // 获取连接 PreparedStatement pst; // 执行Sql语句(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("数据修改失败"); e.printStackTrace(); } return i; } /* * delete 删除 */ public static int delete() { MySQLConnection connection = new MySQLConnection(); Connection conns; // 获取连接 PreparedStatement pst; // 执行Sql语句(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("数据删除失败"); 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 operates statements in the MySQL database
We often use the conn.php file to establish a link with the database, and then use include to call it in the required files. This effectively prevents changes to database attributes from causing errors in data calls from other related files.
Now look at a conn.php file, the code is as follows:
<?php $conn=@mysql_connect("localhost","root","")or die("数据库连接错误");//链接数据库服务器 mysql_select_db("messageboard",$conn);//选择数据库名为messageboard mysql_query("set names 'utf'");//使用utf编码,这里不能写成utf-否则将显示乱码,但UTF不区分大小写 ?>
Accumulation of learning and collection of several basic functions for PHP to operate 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 and password are incorrect!".mysql_error());
. Use the mysql_select_db() function to select the database file: mysql_query("use database name",$link);
For example, $db_selected=mysql_query("use example",$link);
. Use the mysql_query() function to execute SQL statements: mysql_query(string query(SQL statement),$link);
For example:
Add member: $result=mysql_query("insert into tb_member values('a','')",$link);
Modify 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);
Query members: $sql=mysql_query("select * from tb_book");
Fuzzy query: $sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");
//The universal character % represents zero or any more characters.
Display table structure: $result=mysql_query("DESC tb_member");
. Use the mysql_fetch_array() function to obtain information from the array result set:
Syntax structure: array mysql_fetch_array(resource result[,int result_type])
The parameter result resource type is an integer parameter. The data pointer to be passed in is the data pointer returned by the mysql_fetch_array() function;
Parameter result_type: optional, the basic integer parameter for PHP to operate the MySQL database statement. The parameters to be passed in are MYSQL_ASSOC (associative index), MYSQL_NUM (numeric index) MYSQL_BOTH (including the first two, default value)
For example:
<>$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:
Syntax structure: object mysql_fetch_object(resource result);
For example:
<>$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 one difference, that is, it returns an object instead of an array. This function can only access the array through the field name. Syntax structure for accessing row elements in a result set: $row->col_name(column name)
. Use the mysql_fetch_row() function to obtain each record in the result set row by row:
Syntax structure: array mysql_fetch_row(resource result)
For example:
<>$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 obtain the number of records in the result set:
Syntax structure: int mysql_num_rows(resource result)
For example:
$sql=mysql_query("select * from tb_book"); ...... <?php $nums=mysql_num_rows($sql);echo $nums;?>
Note: To obtain the data affected by insert, update, and delete statements, you must use the mysql_affected_rows() function.
.mysql_query("set names gb");//Set the encoding format of MySQL to gb type to block garbled characters.
. Close the record set: mysql_free_result($sql);
. Close the MySQL database server: mysql_close($conn);

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools
