如果在DB中找到,则向MySQL值添加一个数字

时间:2013-07-29 05:12:44

标签: php mysql

我正在尝试弄清楚如果已存在,如何在用户名末尾添加1,2或3等。这是我到目前为止所做的,但我不能完全添加一个数字。它只是一遍又一遍地输入用户名。

require_once 'connect_to_mysql.php';

$username = substr($payer_email, 0, strpos($payer_email, '@'));
$sql = mysql_query("SELECT username FROM transactions WHERE username='$username'");
$numRows = mysql_num_rows($sql);
if ($numRows > 0) {
   $i = 0;

   while ($name_arr = mysqli_fetch_assoc($user_query)) {

      $name = $name_arr['username'];       

      $after = substr($name, strlen($username));

      if (ctype_digit($after)) {

         if (($after = (int) $after) > $i) {

            $i = $after;

         }

      }

   }

   if ($i > 0) {
      $username .= $i;
   }

}

修改

我仍然无法找到一种方法来添加一个数字到最后。在我的逻辑中,我能想到的是使用行计数,如果存在重复,则使用该数字附加到用户名。这就是我到目前为止所拥有的。任何帮助深表感谢。我已经被困在这两天了,在我的搜索中找不到任何关于stackoverflow的东西。

require_once 'connect_to_mysql.php';

$username = substr($payer_email, 0, strpos($payer_email, '@'));
$sql = mysql_query("SELECT username FROM transactions WHERE username='$username'");
$numRows = mysql_num_rows($sql);
if ($numRows > 0) {
   $i = 0;

   while ($row = mysqli_fetch_assoc($sql)) {

      $username = "$username";       

        if($counter > 0){
        $username = $usernamename[$count];
        $counter++;
        }
        else {
        $username == "$username";
        }


}
}

再一次编辑:

我想我可能忽略了一个可能的解决方案。只是将id添加到用户名是一个值得思考的解决方案吗?那里不可能有重复,这是有道理的,对吗?

require_once 'connect_to_mysql.php';

$username = substr($payer_email, 0, strpos($payer_email, '@'));
$sql = mysql_query("SELECT username FROM transactions WHERE username='$username'");
$numRows = mysql_num_rows($sql);
if ($numRows > 0) {
   $i = 0;

   while ($row = mysqli_fetch_assoc($sql)) {

      $id = $row["id"];
      $username = $row['username'];       

        if($counter > 0){
        $username = '.$username.''.$id.';

        }
        else 
        $username == "$username";



}
}

下一次更新:

<?php

// Check to see there are posted variables coming into the script
if ($_SERVER['REQUEST_METHOD'] != "POST") die ("No Post Variables");
// Initialize the $req variable and add CMD key value pair
$req = 'cmd=_notify-validate';
// Read the post from PayPal
foreach ($_POST as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}
// Now Post all of that back to PayPal's server using curl, and validate everything with PayPal
// We will use CURL instead of PHP for this for a more universally operable script (fsockopen has issues on some environments)
//$url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
$url = "https://www.paypal.com/cgi-bin/webscr";
$curl_result=$curl_err='';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
curl_setopt($ch, CURLOPT_HEADER , 0);   
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$curl_result = @curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);

$req = str_replace("&", "\n", $req);  // Make it a nice list in case we want to email it to ourselves for reporting

// Check that the result verifies
if (strpos($curl_result, "VERIFIED") !== false) {
    $req .= "\n\nPaypal Verified OK";
} else {
    $req .= "\n\nData NOT verified from Paypal!";
    mail("chris@.com", "IPN interaction not verified", "$req", "From: chris@.com" );
    exit();
}

/* CHECK THESE 4 THINGS BEFORE PROCESSING THE TRANSACTION, HANDLE THEM AS YOU WISH
1. Make sure that business email returned is your business email
2. Make sure that the transaction’s payment status is “completed”
3. Make sure there are no duplicate txn_id
4. Make sure the payment amount matches what you charge for items. (Defeat Price-Jacking) */

// Check Number 1 ------------------------------------------------------------------------------------------------------------
$receiver_email = $_POST['receiver_email'];
if ($receiver_email != "chris@.com") {
    $message = "Investigate why and how receiver email is wrong. Email = " . $_POST['receiver_email'] . "\n\n\n$req";
    mail("chris@.com", "Receiver Email is incorrect", $message, "From: chris@.com" );
    exit(); // exit script
}
// Check number 2 ------------------------------------------------------------------------------------------------------------
if ($_POST['payment_status'] != "Completed") {
    // Handle how you think you should if a payment is not complete yet, a few scenarios can cause a transaction to be incomplete
}
// Connect to database ------------------------------------------------------------------------------------------------------
require_once 'connect_to_mysql.php';
// Check number 3 ------------------------------------------------------------------------------------------------------------
$this_txn = $_POST['txn_id'];
$sql = mysql_query("SELECT id FROM transactions WHERE txn_id='$this_txn' LIMIT 1");
$numRows = mysql_num_rows($sql);
if ($numRows > 0) {
    $message = "Duplicate transaction ID occured so we killed the IPN script. \n\n\n$req";
    mail("chris@.com", "Duplicate txn_id in the IPN system", $message, "From: chris@.com" );
    exit(); // exit script
} 
// Check number 4 ------------------------------------------------------------------------------------------------------------
$product_id_string = $_POST['custom'];
$product_id_string = rtrim($product_id_string, ","); // remove last comma
// Explode the string, make it an array, then query all the prices out, add them up, and make sure they match the payment_gross amount
$id_str_array = explode(",", $product_id_string); // Uses Comma(,) as delimiter(break point)
$fullAmount = 0;
foreach ($id_str_array as $key => $value) {

    $id_quantity_pair = explode("-", $value); // Uses Hyphen(-) as delimiter to separate product ID from its quantity
    $product_id = $id_quantity_pair[0]; // Get the product ID
    $product_quantity = $id_quantity_pair[1]; // Get the quantity
    $sql = mysql_query("SELECT price FROM products WHERE id='$product_id' LIMIT 1");
    while($row = mysql_fetch_array($sql)){
        $product_price = $row["price"];
    }
    $product_price = $product_price * $product_quantity;
    $fullAmount = $fullAmount + $product_price;
}
$fullAmount = number_format($fullAmount, 2);
$grossAmount = $_POST['mc_gross']; 
if ($fullAmount != $grossAmount) {
        $message = "Possible Price Jack: " . $_POST['payment_gross'] . " != $fullAmount \n\n\n$req";
        mail("chris@.com", "Price Jack or Bad Programming", $message, "From: chris@.com" );
        exit(); // exit script
} 

//
//
require_once 'connect_to_mysql.php';

//now to always get unique username
$username = substr($payer_email, 0, strpos($payer_email, '@'));
if ( ! uniqueName($username))
{
    $username = makeUniqueName($username);
}


//function to check if is the existing username
function uniqueName($username)
{
    $sql = mysql_query("SELECT username FROM transactions WHERE username='$username'");
    $numRows = mysql_num_rows($sql);
    if ($numRows > 0)
    {
        return false;
    }

    return true;
}


//function to generate new unique username
function makeUniqueName($username)
{
    //serch username string for number at the end
    //regexp makes sure all preceeding zeroes go to first match group
    if (preg_match('/^(\S*?0*)?(\d+?)$/', $username, $match))
    {
        //we got digit from the end of string, just add 1 to the digit
        $username = $match[1] . ($match[2] + 1);
    }
    else
    {
        //no digit at the end of string, just add digit 1 at the end
        $username = $username . 1;
    }

if (uniqueName($username))
{
    return $username;
}

    return makeUniqueName($username);
}

// END ALL SECURITY CHECKS NOW IN THE DATABASE IT GOES ------------------------------------
////////////////////////////////////////////////////
// Homework - Examples of assigning local variables from the POST variables
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
$custom = $_POST['custom'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$payment_date = $_POST['payment_date'];
$mc_gross = $_POST['mc_gross'];
$payment_currency = $_POST['payment_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payment_type = $_POST['payment_type'];
$payment_status = $_POST['payment_status'];
$txn_type = $_POST['txn_type'];
$payer_status = $_POST['payer_status'];
$address_street = $_POST['address_street'];
$address_city = $_POST['address_city'];
$address_state = $_POST['address_state'];
$address_zip = $_POST['address_zip'];
$address_country = $_POST['address_country'];
$address_status = $_POST['address_status'];
$notify_version = $_POST['notify_version'];
$verify_sign = $_POST['verify_sign'];
$payer_id = $_POST['payer_id'];
$mc_currency = $_POST['mc_currency'];
$mc_fee = $_POST['mc_fee'];
$password = mt_rand(1000, 9999); 
$p_hash = md5($password);
$username = $_POST['makeUniqueName'];
 //

// Place the transaction into the database
$sql = mysql_query("INSERT INTO transactions (product_id_array, payer_email, first_name, last_name, payment_date, mc_gross, payment_currency, txn_id, receiver_email, payment_type, payment_status, txn_type, payer_status, address_street, address_city, address_state, address_zip, address_country, address_status, notify_version, verify_sign, payer_id, mc_currency, mc_fee, password, ip, username) 
   VALUES('$custom','$payer_email','$first_name','$last_name','$payment_date','$mc_gross','$payment_currency','$txn_id','$receiver_email','$payment_type','$payment_status','$txn_type','$payer_status','$address_street','$address_city','$address_state','$address_zip','$address_country','$address_status','$notify_version','$verify_sign','$payer_id','$mc_currency','$mc_fee','$p_hash','$ip','$username')") or die ("unable to execute the query");
$to      = $payer_email;  
$subject = ' | Login Credentials';  
$message = ' 

Your officially all ready to go. To login use the information below.

Your account login information 
------------------------- 
Email: '.$payer_email.' 
Password: '.$password.' 
------------------------- 

You can now login at https://www..com/signin.php';  
$headers = 'From:noreply@.com' . "\r\n";  

mail($to, $subject, $message, $headers);  
mysql_close();
// Mail yourself the details
mail("chris@.com", "NORMAL IPN RESULT YAY MONEY!", $req, "From: chris@.com");

?>

3 个答案:

答案 0 :(得分:1)

如果我理解正确,你可以在MySql端一次性使用这样的查询

SELECT COALESCE(CONCAT('$username', SUBSTRING(MAX(username), CHAR_LENGTH('$username') + 1) * 1 + 1), '$username') username
  FROM transactions
 WHERE username REGEXP '$username([0-9]+)?$'

这是 SQLFiddle 演示

旁注:在您的代码中,您混合了mysql_*mysqli_*个分机号码。首先进行mysql_query()通话,然后执行mysqli_fetch_assoc()。坚持一个。自mysqli_*弃用以来mysql_*最好。

答案 1 :(得分:0)

未选中Psudo-PHP:

// insert code before determining if the desired $userName $isTaken
$newName = "";
if ($isTaken) {
    $i = 1;
    do {
        $newName = $userName . $i;
        $query = "SELECT username FROM transactions WHERE username='$newName'";
        $result = mysql_query($query);
        $numRows = mysql_num_rows($result);
        if ($numRows == 0) $i = 0;
    } while ($i != 0)
}

如果您想避免多次查询,请搜索每个用户名并自行排序,但根据比例,可能不会那么昂贵。

答案 2 :(得分:0)

始终获得唯一用户名的解决方案。如果字符串末尾有数字以使其唯一,则会添加+1,并重新检查是否唯一,如果不是,它会一次又一次地执行,直到找到唯一名称。如果最后没有数字,它将在结尾添加1并像之前一样重新检查,直到找到唯一的不存在的名称。

$dbConn = new mysqli($host, $dbUser, $dbPass, $dbName);

//now to always get unique username
$username = substr($payer_email, 0, strpos($payer_email, '@'));
if ( ! isUniqueName($username))
{
    $username = makeUniqueName($username);
}


//function to check if is the existing username
function isUniqueName($username)
{
    global $dbConn;

    $sql = mysqli_query($dbConn, "SELECT username FROM transactions WHERE username='$username'");
    $numRows = mysqli_num_rows($sql);
    if ($numRows > 0)
    {
        return false;
    }

    return true;
}


//function to generate new unique username
function makeUniqueName($username)
{
    //serch username string for number at the end
    //regexp makes sure all preceeding zeroes go to first match group
    if (preg_match('/^(\S*?0*)?(\d+?)$/', $username, $match))
    {
        //we got digit from the end of string, just add 1 to the digit
        $username = $match[1] . ($match[2] + 1);
    }
    else
    {
        //no digit at the end of string, just add digit 1 at the end
        $username = $username . 1;
    }

    if (isUniqueName($username))
    {
        return $username;
    }

    return makeUniqueName($username);
}