我一直试图让这个脚本完成一段时间 - 我是一种新的php和mysql,但我一直试图让它检查数据库的用户名,然后如果用户名存在 - 停止检查db并且如果它不存在则将其添加到db。
这是我的代码:
//input from application
$test = "wheelsmanx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "User Name Already In Use.";
}if($row["mainusername"] !== $test){
echo "this statement";
[code that inserts into db i can do this part myself]
}
}
$conn->close();
} else {
echo "0 results";
}
$conn->close();
答案 0 :(得分:1)
您的代码存在的问题是您在已确认该用户存在的INSERT
语句中执行了新名称的if
。此外,我认为你通过选择所有用户搞砸了你的SELECT
声明。
查看INSERT ON DUPLICATE以获得更好的方法,或修改您的代码,如下所示。
$sql = "SELECT mainusername FROM CCCpro_test WHERE mainusername = $test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "User Name Already In Use.";
}
else{ //no rows selected therefore the user doesn't exist
[code that inserts into db i can do this part myself]
}
$conn->close();
请阅读我有一个地方可以去,所以我很懒,所以我没有绑定$test
变量,因此请勿复制并粘贴此代码而不更新它以绑定{{ 1}}变量。请阅读有关PDO和变量绑定的this post以防止SQL注入。
答案 1 :(得分:0)
这是我的完整工作代码,如果有人需要它 - 它使用post方法 - 从html表单....如果有人需要将其破解成其他东西
好吧,伙计们,我很感谢你们所有的帮助:D但是我已经找到了答案或解决方法我想 - 我一整天都想着它如何让它发挥作用我想出了这个 $servername = "127.0.0.1";
$username = "TESTUSER";
$password = "TESTPASS";
$dbname = "TESTDB";
$testusername = $_POST['mainusername'];
$testpassword = $_POST['mainpassword'];
//input from application
$test = $_POST['mainusername'];
$test2 = "0";
//Count switch
$countswitch = "0";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "INSERT INTO CCCpro_test ( mainusername, mainpassword ) VALUES ('$testusername','$testpassword' )";
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "Im Sorry Username Already In Use";
$countswitch ++;
}
}
if($countswitch == $test2){
echo "User Name Registered";
$db_handle = mysql_connect($servername, $username, $password);
$db_found = mysql_select_db($dbname, $db_handle);
if ($db_found) {
$result1 = mysql_query($sql1);
mysql_close($db_handle);
}
}
if ($countswitch == 3){
echo "this";
}
} else {
echo "0 results";
}
$conn->close();