我在声明中的输出出现问题。我正在尝试为以dB为单位的用户名的每个实例加1。我有以下代码:
$username = strtolower($fname . "_" . $lname);
$check_username_query = mysqli_prepare($con, "SELECT username FROM users WHERE username=?");
$check_username_query->bind_param('s', $username);
$check_username_query->execute();
$result = $check_username_query->get_result();
$num_rows = $result->num_rows; //count number of rows in the result
$i = 0;
//if username exists add number to username
while ($num_rows != 0) {
$i++; //Add 1 to i
$username = $username . "_" . $i;
$check_username_query = mysqli_prepare($con, "SELECT username FROM users WHERE username=?");
$check_username_query->bind_param('s', $username);
$check_username_query->execute();
$result = $check_username_query->get_result();
$num_rows = $result->num_rows;
}
这对于前两个工作正常:例如。 $fname
是约翰,$lname
是史密斯。我得到$username
为john_smith
。对于下一个,我得到john_smith_1
但对于下一个,我得到john_smith_1_2
,而在之后的我得到john_smith_1_2_3
,依此类推。我想要的第三种实例是john_smith_3
,john_smith_4
等。
$i
中的$username = $username . "_" . $i;
会继续增加吗?
答案 0 :(得分:2)
使用这段代码:
$username = strtolower($fname . "_" . $lname);
$check_username_query = mysqli_prepare($con, "SELECT username FROM users WHERE username=?");
$check_username_query->bind_param('s', $username);
$check_username_query->execute();
$result = $check_username_query->get_result();
$num_rows = $result->num_rows; //count number of rows in the result
$i = 0;
//if username exists add number to username
while ($num_rows != 0) {
$i++; //Add 1 to i
$new_username = $username . "_" . $i;
$check_username_query = mysqli_prepare($con, "SELECT username FROM users WHERE username=?");
$check_username_query->bind_param('s', $new_username );
$check_username_query->execute();
$result = $check_username_query->get_result();
$num_rows = $result->num_rows;
}
答案 1 :(得分:1)
我最终这样做:
$username = strtolower($fname . "_" . $lname);
$check_username_query = mysqli_prepare($con, "SELECT username FROM users WHERE username=?");
$check_username_query->bind_param('s', $username);
$check_username_query->execute();
$result = $check_username_query->get_result();
$num_rows = $result->num_rows; //count number of rows in the result
$new_username = 1;
$i = 0;
//if username exists add number to username
while ($num_rows != 0) {
$i++; //Add 1 to i
$new_username = $username . "_" . $i;
$check_username_query = mysqli_prepare($con, "SELECT username FROM users WHERE username=?");
$check_username_query->bind_param('s', $new_username);
$check_username_query->execute();
$result = $check_username_query->get_result();
$num_rows = $result->num_rows;
}
if($new_username == 1){
$username = $username;
} else {
$username = $new_username;
}
需要将$new_username
分配为某物(我选择1),然后在$num_rows == 0
和while
循环未参与的情况下,将其放在条件末尾。根据需要工作。感谢您的指导。