[英]Creating log-in form in C# with MySQL server (principal issue)?
我在C#Winforms中有一个带有登录按钮的登录表单(如屏幕截图所示)。 我想单击按钮以检查是否存在具有给定名称的用户。 我用下面的代码来做(我只提交必要的代码):
假设数据库中我的users
表的第二个字段是username
那么假设IsDBNull()
的参数为1(如果我们从0开始计数),我想问我在做什么错,因为有这样一个用户,即字段不为null,但我要显示的第二个表单不想打开。 我想问为什么?
如果SQL在Web服务器(甚至XAMPP)上,则建议通过PHP输出信息。 这也使它可以通过webRequest库比较登录密码等。 我不建议在最终版本中使用此代码,而是建议将其用于测试和构建。
为了使代码正常工作,您需要做一些事情:
之后,只需添加以下代码,更新C#代码的var webRequest部分中的链接,然后从那里开始!
在C#的顶部,您将需要包括:using System.Net;
C#loginButton_onClick
// Connects to the website
var webRequest = WebRequest.Create("http://yourwebsite.com/programLogin.php?username=" + textBox1.Text);
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
// This gets all of the info given out by the website
var info = reader.ReadToEnd();
// Comparing to expected outputs
if (info == "User found in the database")
{
MessageBox.Show("Username Exists", "Login Form");
}
else if (info == "Username not found")
{
MessageBox.Show("Username Not Found", "Login Form");
}
else
{
// This will most likely only thow if the website is down OR if there is a HTTP error 500 OR unsuccessful login to the database
MessageBox.Show("Unknown Error", "Login Form");
}
}
programLogin.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$user = $_GET['username'];
if (isset($user))
{
$sql = "SELECT username FROM users WHERE username='$user'";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
// $row['username']; will show the informaiton from the database;
echo "User found in the database";
}
}
else
{
echo "Username not found";
}
}
?>
如果仍然不能解决您的问题,请向我提供有关程序所需内容的更多信息,我将为您提供更多帮助/资源!
此代码未经测试
编辑:添加了必需的用法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.