首页 > 解决方案 > 插入mysql(数据库)时的空白条目

问题描述

我正在尝试使用 php 和 mysql 创建登录和注册页面,但遇到了一些问题。

我参考了这个视频,代码如下(代码不完整,我只是为了注册)。

所以问题是,当我使用注册端提交条目时,我的数据库显示空白记录。我尝试了各种方法,例如

$reg = "INSERT INTO usertable (user,pwd) values ('".$user."','".$pwd."')";

但它没有用,当我这样做时:

$reg = "INSERT INTO usertable (user,pwd) values ('ABC','1234')";

有效。我应该怎么做才能使用输入文本插入条目?

<?php
	session_start();
	$conn = mysqli_connect('localhost', 'root', '1234');
	mysqli_select_db($conn,'registeration');
	
	$user = $_POST["user"];
	$pwd = $_POST["pwd"];
	
	$s = "select * from usertable where user = '$user'";
	$result = mysqli_query($conn,$s);
	
	
	$num = mysqli_num_rows($result);
	
	if($num == 1){
		echo"Username Already Taken";		
	}
	else{
		$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
		mysqli_query($conn,$reg);
	}
?>

<h2> Register Here </h2>
<form action="index.html" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>

标签: phphtmlmysql

解决方案


  1. 一种了解程序或您创建的完整 SQL 查询字符串的简单方法。$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')"; 回声 $reg

  2. 最好使用 {} 来代替 . 将变量插入字符串。$reg = "INSERT INTO usertable (user,pwd) values ('{$user}','{$pwd}')";

  3. 为确保 POST/GET 操作目标正确,对于您当前的代码,我不起诉 index.html 可以处理它,可能应该是 $_SERVER["PHP_SELF"]

  4. 了解 PHP 字符串运算符请参考 https://www.php.net/manual/zh/language.operators.string.php


推荐阅读