MySQL连接函数

MySQL快速连接函数

1. 使用原生mysql函数




$config['db'] = array(
	'host'=>'localhost',
	'port'=>'3306',
	'user'=>'root',
	'pwd'=>'',
	'name'=>'test',
	'charset'=>'utf8',
);

mysql_link($config);

function mysql_link($config){

	$con = mysql_connect($config['db']['host'].':'.$config['db']['port'], $config['db']['user'], $config['db']['pwd']);
	mysql_select_db($config['db']['name']);
	mysql_set_charset($config['db']['charset']);

	if (!$con){
		die('Could not connect: ' . mysql_error());
	}

	$sql = "INSERT INTO `wp_express_comments` (`post_id`, `type`) VALUES ('12', 'love')";

	$query = mysql_query($sql, $con);

	if($query === false){
		echo 0;
	}else{
		echo 1;
	}

	mysql_close($con);

}


2. 使用mysqli函数


$mysqli = new mysqli('127.0.0.1', 'mogu_db', '123456', 'mogu_db');

if ($mysqli->connect_errno) {
    printf("Connect failed: %sn", $mysqli->connect_error);
    exit();
}

$query = $mysqli->query( "show tables" );

$result = array();

if ($query) {

    while ($row = $query->fetch_assoc()) {
        $result[] = $row;
    }

    $query->free();

}

$mysqli->close();

var_dump($result);

发表评论