php实现登录和注册(超详细)

登录的实现

<?php
$mysql_conf = array(
    'host'    =>'127.0.0.1:3306',
    'db'      =>'learn',
    'db_user'=>'root',
    'db_pwd' =>'root',
);
	//session_start();
	header('Content-Type:application/json; charset=utf-8');
	$myname = $_POST['login_name']; 
	$mypass = $_POST['login_pass'];
	 
	if($myname!=''&&$mypass!='')
	{
		$conn = new mysqli("127.0.0.1:3306", "root", "root");
		if($conn->connect_errno){
    		die("could not connect to the database:\n" . $mysqli->connect_errno);//诊断连接错误
		}
		$conn->query("set names 'utf8';");//编码转换
		$select_db = $conn->select_db($mysql_conf['db']);//连接的数据库
	
		if ($conn != null) //连接成功
		{
			$sql = "select * FROM users where username='$myname' and password = '$mypass' ";
			$res =$conn->query($sql);//发送sql请求
	  		$result = array();
			while ($row = $res->fetch_assoc()){
    			//var_dump($row);
			array_push($result,$row);
			}
			if($result){$result_array[0] = ['code'=>'1','msg'=>'登陆成功'];
				echo json_encode($result_array);//返回给前端
			}
			else{
			$result_array[0] = ['code'=>'0','msg'=>'用户名或密码输入错误'];
				echo json_encode($result_array);
	  		}
			$conn->close();

				
		}
	}
	else
	{
		$result_array[0] = ['code'=>'0','msg'=>'请输入用户名或密码'];
		echo json_encode($result_array);
	}
	?>
	

注册的实现

<?php
$mysql_conf = array(
    'host'    =>'127.0.0.1:3306',
    'db'      =>'learn',
    'db_user'=>'root',
    'db_pwd' =>'root',
);
	//session_start();
	header('Content-Type:application/json; charset=utf-8');
	//前端传来的数据,你也可以输入字符串来测试一下
	$myname = $_POST['reg_name'];
	$mypass = $_POST['reg_pass'];
	$myphone = $_POST['reg_phone'];
	$myemail = $_POST['reg_email'];
	 
	if($myname!=''&& $mypass!='' && $myemail!=''&& $myphone!='')
	{
		$conn = new mysqli("127.0.0.1:3306", "root", "root");
		if($conn->connect_errno){
    		die("could not connect to the database:\n" . $mysqli->connect_errno);//诊断连接错误
		}
		$conn->query("set names 'utf8';");//编码转换
		$select_db = $conn->select_db($mysql_conf['db']);//连接的数据库
	
		if ($conn != null) //连接成功
		{
			$sql = "select * from users";
			$res = $conn->query($sql);	
			$flag=false;
			while($row=$res->fetch_assoc())
			{
				if($myname==$row['username'])
				{$result_array[0] = ['code'=>'0','msg'=>'该用户已存在'];
				//这两条是我返回给前端的数据
				echo json_encode($result_array);
				$flag=true;//俺设置一个flag来判断用户存不存在
				}
			}
			if($flag==false)
			{$sql2="insert into users(username,password,phone,email) values('$myname','$mypass','$myphone','$myemail')";
			$conn->query($sql2);
			
			$result_array[0] = ['code'=>'1','msg'=>'注册成功了'];
				echo json_encode($result_array);}
				
		}

				
		
	}

?>

	

	

你可能感兴趣的:(php)