Проблемы с обработкой результатов запроса SELECT с MySQLI

Основная структура управления, которую я пытаюсь заставить работать, состоит в том, чтобы запросить БД с именем пользователя и адресом электронной почты, оба из которых являются уникальными ключами, и если они есть в БД, сообщите пользователю, что они были приняты, и пожалуйста, выберите что-то другое. Проблема, с которой я сталкиваюсь, заключается в том, чтобы получить данные результатов в пригодной для использования форме, с которой я могу затем сравнить данные, предоставленные пользователем.

Я вырезал из фрагмента подготовленные операторы для вставки, а также процедуры проверки, так как они оба работают нормально.

DB connection snippit

try {
    if(!($dbc = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME))){      // Creates the $dbc variable object so we can
                                                                           // have a connection to the database.
                                                                           // uses mysqli functions.
    throw new Exception;
    }

}
catch (Exception $e) {
    echo '<p>Could not connect to the database. Please contact the system administrator.</p>';
} 

Фрагмент скрипта регистрации

//before this was validation routines, if anything was wrong the script generated something into $reg_errors which is an array.
if(empty($reg_errors))
{
//queries database if there are any matches for username or email from user input.
if($stmt = $dbc->prepare("SELECT `email`, `username` FROM `users` WHERE `email` = ? OR `username` = ?"))
{
    $stmt->bind_param("ss", $e, $u);
    $stmt->execute();
    $stmt->store_result();
    $rows = $stmt->num_rows;                   //gives the number of rows returned from SELECT query. 0 means no dupes, 1 means one record has BOTH email and username, 2 means two different records (one with email, one with username)

 ##THIS IS WHERE I'M RUNNING INTO TROUBLE GETTING THE DATA IN A USABLE FORM##

    $stmt->close();
} else {
    echo "<p>Can't talk to database right now. Try again later, please.</p>";
}

        if($rows==0)            //no dupes of username or email, so let's try and add them into the DB
        {
            //prepared statement for insertion into DB
            //also get's the count of affected rows. 1 means record inserted correctly. 

        //asks DB if a new row was created, and if so, thanks user for 
        //registration on the site & sends an email to their email.
        //if query doesnt work, an error is triggered
        if($count==1) {
            //constructs a thank you note and emails it to the user, using the email they supplied.
            exit(); 
            } else {
                echo "<p>Unable to process your registration at this time. Please try again later..</p>";
            }
    } else {                    // both username and email might be already used in DB, and error msgs are generated for array.
        if($rows==2) {          // this checks to make sure both entries are dupes        
            $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
            $reg_errors['username'] = 'This username has already been registered. Please try another.';
        } else {                //this checks to see which of the two (email or username) is already in DB if both arent dupes.

            if((__NEED SOMETHING HERE FROM DB QUERY___ == $_POST['email']) && (__NEED SOMETHING HERE FROM DB QUERY___ == $_POST['username'])) {   //both match entries in DB
                $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
                $reg_errors['username'] = 'This username has already been registered with this email address. If you have forgotten your password, use the link to the right to have your password sent to you.';
            } elseif(__NEED SOMETHING HERE FROM DB QUERY___==$_POST['email']) {        // email match
                    $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
            } elseif(__NEED SOMETHING HERE FROM DB QUERY___==$_POST['username']) {     // username match
                $reg_errors['username'] = 'This username has already been registered. Please try another one.';
            }
        }       // end of $rows==2 ELSE
    }           // end of $rows == 0 IF

    } else {           // end of empty reg_errors conditional
        //do something if the reg_error array isnt empty..
    }  

я почти уверен, что ответ заключается в итерациях и использовании метаданных из результирующего объекта mysqli, но после того, как я пару дней бил головой о стену и пролистывал страницы руководства mysqli php, как маньяк, я все еще не приблизился к выясняя, что я должен делать. Может ли кто-нибудь указать мне в правильном направлении?


person alephalpha0    schedule 27.08.2013    source источник
comment
Знаешь, твоя идея использовать исключения довольно ошибочна... оригинальна.   -  person Your Common Sense    schedule 27.08.2013
comment
И я попытался прочитать ваш код, но сдался. СЛИШКОМ МНОГО прокрутки для моей бедной мышки.   -  person Your Common Sense    schedule 27.08.2013
comment
Если говорить о вашей проблеме - это только ваше нетерпение. Прежде чем получить какой-либо регистрационный код, вы должны выполнить простые примеры mysqli, ознакомиться с основными операциями.   -  person Your Common Sense    schedule 27.08.2013
comment
Как насчет bind_result? php.net/manual/en/mysqli-stmt.bind- результат.php   -  person Sergiu Paraschiv    schedule 27.08.2013
comment
Извините, я знаю, что я все еще новичок, и да, именно нетерпение заставило меня задать этот вопрос, но я чувствовал, что это может помочь любому другому, у кого могут быть те же проблемы, что и у меня.   -  person alephalpha0    schedule 28.08.2013


Ответы (1)


Начиная со сценария регистрации, вы пробовали это:

if($stmt = $dbc->prepare("SELECT `email`, `username` FROM `users` WHERE `email` = ? OR `username` = ?"))
{
    $stmt->bind_param("ss", $e, $u);
    $stmt->execute();
    $stmt->bind_result($email, $username);
    $rows = $stmt->num_rows;

    //Move Conditionals Up a Little
    if( $rows == 0 ) {    //If No Records are Found

        //Continue Registration
    }
    else if( $rows == 1 ) { //If One Record is Found

        $stmt->fetch();

        //Do Something With $email and $username from DB Here

    }
    else { //If More than One Record is Found

        while( $stmt->fetch() ) {  //Iterate Through Records

            //Do Something With $email and $username from DB Here
        }
    }
}
person Jason    schedule 27.08.2013
comment
ваша логика прохождения набора результатов удивительна. спасибо, это немного помогло. если бы у меня был представитель, я бы проголосовал за это. это не полный ответ, но определенно больше, чем шаг в правильном направлении. благодарю вас. - person alephalpha0; 28.08.2013
comment
В таком случае, где мой ответ обрывается? - person Jason; 28.08.2013