A self-written function for php to operate MYSQL database.

<?PHP
//return array result
//$a=array('connection address','login name','login password','database name','port');
//$a=array('127.0.0.1','root','123','mysql','3306');
//sqlrun($a,"select now();");
//sqlrun();
function sqlrun($cto=array('127.0.0.1','root','123','mysql','3306'),$sql="select now();")
{
	//1-connect
	$con=@mysqli_connect($cto[0], $cto[1], $cto[2], $cto[3], $cto[4]);
	//an examination
	if(!$con)
	{
		echo "<br>Connection failed!!!".mysqli_connect_error();
		return false;
	}

	//2-Set the connection character set
	mysqli_set_charset($con,"utf8");

	//3-Select/replace/open (USE) the specified database
	mysqli_select_db($con,$cto[3]);

	//4-Execute the SQL command
	//$sql="show databases;";
	$re=@mysqli_query($con,$sql);
	//Check if the command fails
	if(!$re)
	{
		echo "<br>SQL command execution failure/error command".mysql_error();
		//5-Close the connection
		mysqli_close($con);
		return false;
	}
			
	//5-Close the connection
	mysqli_close($con);
	//View the result set type
	//echo "<pre>";
	//var_dump($re);
	//echo "</pre>";

	//check the data type of the result set
	//The returned result is the object object type.
	//The return result of commands such as select is object
	//No return result is boolean boolean type
	//insert and other non-returned results are boolean
	if(gettype($re)!='object')
	{
		echo "<br>The SQL command was executed successfully, but no result was returned, so let's go here";
		// release the result set
		mysqli_free_result($re);
		return true;
	}


	// Dump the execution result as a two-dimensional array and return it
	//Get the field name and store it in the first row of the array
	foreach(mysqli_fetch_fields($re) as $v)
	{
		$rearr[0][]=$v->name;
	}
	//Get the result, this function automatically organizes the result set into an array,
	// Equivalent to appending the following data after the above field name record.
	//array_merge() merges two arrays
	$rearr=array_merge($rearr,mysqli_fetch_all($re));
			
	// release the result set
	mysqli_free_result($re);
	// view the returned array
	//echo "<pre>";
	//print_r($rearr);
	//echo "</pre>";
	//echo "<br>成功!!!";

	return $rearr;
}
?>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325565621&siteId=291194637