gpt4 book ai didi

php 和 mysqli_num_rows 不检测数据库中是否有内容

转载 作者:行者123 更新时间:2023-11-29 07:08:02 26 4
gpt4 key购买 nike

我在网站上有一个表单,需要在将表单数据输入数据库之前进行验证。

它通过用户 mysql_num_rows 函数检查用户名是否已经存在。但我似乎无法让它工作。测试时,它不允许添加新用户名。

这里是使用的完整代码:

<?php
session_start();

include("databaseConnect.php");
// Insert a row of information into the table "example"


// check if username is already in database
if(mysql_num_rows(mysql_query("SELECT userName FROM registeredUsers WHERE userName = '$_POST[userName]'"))){
echo "Username: ". $_POST[userName]." already exists in the Database<br><br>";
echo "You will be redirect back to the form in 5 seconds";
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 5; url='.$ref);

//check if hemis is already in database
}elseif(mysql_num_rows(mysql_query("SELECT hemis FROM registeredUsers WHERE hemis = '$_POST[hemis]'"))){
echo "Student [Hemis] Number: ". $_POST[hemis]." already exists in the Database<br><br>";
echo "You will be redirect back to the form in 5 seconds";
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 5; url='.$ref);


// if all the conditions above are fine, it will insert the data to MySQL
}else{
mysql_query("INSERT INTO registeredUsers
(firstName, lastName, hemis, userName, MAC) VALUES('$_POST[firstName]', '$_POST[lastName]', '$_POST[hemis]', '$_POST[userName]', '$_POST[mac]' ) ")
or die(mysql_error());

echo "Data Inserted! <br><br>";
}

非常感谢:)

最佳答案

我会完全重写它。它受 SQL 注入(inject)的影响,效率低下并且有点过于简洁。另外,您通常最好使用 PHP mysqli extension

此外,请确保将 $_POST 变量名称括在引号中。您已将它们写成常量,而不是字符串。 (除非您在代码中的其他地方定义了表示字符串值的常量,否则这是一个错误。在您开发时打开 PHP 警告。)

$safe_username = mysqli_real_escape_string($_POST['userName']);
$sql = "SELECT userName FROM registeredUsers WHERE userName='$safe_username' LIMIT 1";
$result = mysqli_query($database_connection, $sql);
if (mysqli_num_rows($result))
{
// username already found code
mysqli_free_result($result);
}
else
{
$safe_hemis = mysqli_real_escape_string($_POST['hemis']);
$sql = "SELECT hemis FROM registeredUsers WHERE hemis='$safe_hemis' LIMIT 1";
// Side note, LIMIT 1 tells the database engine to stop looking after it's found one hit. More efficient as you're only looking for a Boolean value anyway.
$result = mysqli_query($database_connection, $sql);
if (mysqli_num_rows($result))
{
// hemis found code
mysqli_free_result($result);
}
}

剩下的你大概可以从这里算出来。

请验证并转义所有输入。验证包括检查完整性 - 数据是否在范围内(字符串长度、数字范围等)等。所有输入都是错误的!

您真的不想依赖 HTTP_REFERER。用户代理并不总是传递引荐来源网址。

此外,我知道这没什么大不了的,但使用 CSS 而不是 <br> .如果您使用 XHTML 文档类型,则必须正确关闭所有标签,因此 <br>会变成<br /> .无论如何,这是个好主意。

关于php 和 mysqli_num_rows 不检测数据库中是否有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6167269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com