mrkody/php-jsondb

简单的JSON文件数据库PHP库

dev-master 2018-02-27 08:47 UTC

This package is not auto-updated.

Last update: 2024-09-15 05:02:45 UTC


README

一个PHP类,可以将JSON文件作为数据库读取。适用于示例数据库。

用法

包含文件:<?php include( 'JSONDB.Class.php' );?>

初始化

	<?php 
	$json_db = new JSONDB();

插入

将数据插入到新的JSON文件中。以下以users.json为例

注意: 首先插入的列将是后续插入中唯一允许的列

	<?php
		$json_db->insert( 'users.json', 
		[ 
			'name' => 'Thomas', 
			'state' => 'Nigeria', 
			'age' => 22 
		]);

获取

获取数据,就像在PHP中使用MySQL一样

所有列
	<?php
	$users = $json_db->select( '*' )
		->from( 'users.json' )
		->get();
	print_r( $users );
自定义列
	<?php 
	$users = $json_db->select( 'name, state'  )
		->from( 'users.json' )
		->get();
	print_r( $users );
	
WHERE语句

目前这个WHERE语句作为AND操作符使用,或OR

	<?php 
	$users = $json_db->select( 'name, state'  )
		->from( 'users.json' )
		->where( [ 'name' => 'Thomas' ] )
		->get();
	print_r( $users );
	
	// Defaults to Thomas OR Nigeria 
	$users = $json_db->select( 'name, state'  )
		->from( 'users.json' )
		->where( [ 'name' => 'Thomas', 'state' => 'Nigeria' ] )
		->get();
	print_r( $users );  
	
	// Now is THOMAS AND Nigeria 
	$users = $json_db->select( 'name, state'  )
		->from( 'users.json' )
		->where( [ 'name' => 'Thomas', 'state' => 'Nigeria' ], 'AND' )
		->get();
	print_r( $users );  	
	
	
排序

感谢Tarun Shanker提供此功能。通过传递order_by()方法,结果将按照列名和排序方法(JSONDB::ASCJSONDB::DESC)排序

	<?php 
	$users = $json_db->select( 'name, state'  )
		->from( 'users.json' )
		->where( [ 'name' => 'Thomas' ] )
		->order_by( 'age', JSONDB::ASC )
		->get();
	print_r( $users );

更新行

您也可以使用这些方法更新同一个JSON文件

	<?php 
	$json_db->update( [ 'name' => 'Oji', 'age' => 10 ] )
		->from( 'users.json' )
		->where( [ 'name' => 'Thomas' ] )
		->trigger();
	

如果没有使用where()方法,则会更新所有行

删除行

	<?php
	$json_db->delete()
		->from( 'users.json' )
		->where( [ 'name' => 'Thomas' ] )
		->trigger();

如果没有使用where()方法,则会删除所有行

导出到MySQL

您可以使用此方法并将输出提供给输出文件,将JSON数据导出到SQL文件

        <?php 
        $json_db->to_mysql( 'users.json', 'users.sql' );

禁用CREATE TABLE

        <?php 
        $json_db->to_mysql( 'users.json', 'users.sql', false );

导出到XML

Tarun Shanker还提供了一个功能,可以将数据导出到XML文件

	<?php 
	if( $json_db->to_xml( 'users.json', 'users.xml' ) ) {
		echo 'Saved!';
	}