A function that produces the accurate result in one specific scenario but fails to do so in all other

After conducting tests using the function below, I have come across a strange issue. When testing with the name "admin", it correctly returns an associative array with all the appropriate columns and values. However, for any other name entered, the query seems to return 0, indicating that nothing is being found in the database (the names are being inputted correctly).

I suspect this could be related to a security feature of PDO or something similar, but I am unsure why it is behaving this way.

The database system being used is MySQL.

If anyone has insights into what might be causing this problem and how to resolve it, I would greatly appreciate your help. Thank you!

function getUserDetailsByName($name, $fields = "*")
{   
    $db = connect_db();

    $query = "SELECT $fields FROM UserDetails WHERE userName=:username";
    $result = $db->prepare($query);
    $result->bindParam(":username", $name);

    if (!($result->execute())) {
        sendMessage (1,1,'Query failed',$query);
        $db = null;
        return;
    }
    if (!($result->fetch(PDO::FETCH_NUM) > 0)) {
        $db = null;
        return 0;
    }else{
        $result = $result->fetch();
        $db = null;
        return $result;
    }   
}

EDIT: In response to a request for information on how I call the function:

$user = getUserDetailsByName($_POST['value']);
if($user == 0)
{
  print "user = 0";
}
print_r($user);

Answer №1

function retrieveUserInformation($username, $fields = "*"){
    $database = establishDatabaseConnection();

    $searchQuery = "SELECT {$fields} FROM UserInformation WHERE user_name = :username LIMIT 1;";
    if(!$results = $database->prepare($searchQuery)){
        return null;
    }
    $results->bindParam(":username", $username);
    if(!$results->execute()) {
         sendAlertMessage(1,1,'Query unsuccessful',$searchQuery);
        return null;
    }
    if(!$userData = $results->fetch(PDO::FETCH_NUM)) {
        return false;
    }
    return $userData;
}

Why does it require 2 fetches? Review and compare this with your own code.

Usage example:

if($userInfo = retrieveUserInformation($_POST['data'])){
    // User found!
}else{
    // User not found!
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Number of database rows - PHP prepared statements - querying data

I'm having trouble figuring out how to retrieve the number of rows from the database using my query. Every time I run the query, it just returns zero even though the data is in my database. $username = $_POST['username']; $hashedPassword = ...

Arranging results in elastic search according to user-provided criteria

Is it possible to retrieve products from elastic search in the order of user input? For example, if a user searches for "Z1234", "S1234", and "T2344", can we display the products in that exact sequence with Z1234 as the first record? I have attempted using ...

How can you simultaneously send FormData and String Data using JQuery AJAX?

Is there a way to upload both file and input string data using FormData()? For example, I have several hidden input values that also need to be included in the server request. html, <form action="image.php" method="post" enctype="multipart/form-data"& ...

Having difficulty utilizing WP_Query effectively for accomplishing certain tasks

Currently, I am diving into the world of WordPress theme development by adapting my existing Bootstrap and JavaScript website. My requirements are as follows: 1) Implement a section on the homepage of my WordPress site to display the latest three blog ar ...

Architecture of Zend_Queue database

Currently, my email queuing and sending system utilizes Zend_Queue (http://framework.zend.com/manual/en/zend.queue.adapters.html) I am wondering if there is a method to change the default table names in Zend_Queue_Adapter_Db. The default names "queue" and ...

What are your preferred HTMLPurifier configurations for sanitizing CSS styles?

I'm currently in the process of developing an application that allows users to input their own custom CSS for their profiles, similar to platforms like MySpace, Friendster, and Blogger. However, I'm struggling to find an effective method to prot ...

Issue with adding to lightbox feature when loading content dynamically using AJAX PHP is not functioning as expected

Hey there! I've encountered an interesting issue with my code that adds models to a lightbox. It's functioning perfectly on static pages like this one. $scope.add = function(permalink, post_id) { if (typeof(Storage) !== "undefined") { ...

Attempting to include additional fields in the registration form in Laravel may not function as expected

I've been attempting to include additional fields in my registration form within Laravel, but unfortunately, it's not functioning as expected. Despite receiving no errors, the page simply reloads without saving any data to the database. Initiall ...

Guide on efficiently transferring fetched data from a MySQL database to a php file in JSON format

Trying to retrieve data from a MySQL table and return it as JSON in a PHP file. Below is the code snippet used for connecting to MySQL and fetching data. How can I now convert this data into JSON format? <?php $username = "user"; $password = "* ...

Can you provide more information about resource ID #170?

My goal with this code snippet is to extract data from Joomla's database. The code successfully connects to the database, but when trying to retrieve information using $query1, I receive an output of "resource id #170". Even after testing with differe ...

URL not passing on variable

Here is the code I have for a basic 'change email' script. I'm currently struggling to get it working and can't figure out what's wrong. <?php if (isset($_GET['u'])) { $u = $_GET['u']; } if (isset($_POS ...

Stop jQuery from adding duplicate values to a table

When I make an AJAX call using jQuery and PHP to receive JSON response, I am encountering a problem with duplicate values. The code is functioning correctly, but when selecting an option from the drop-down list, duplicate entries appear. The scenario invol ...

Ensure to verify the user's login status before allowing them to add an item

I'm currently in the process of implementing a "favorite" feature on my website. Users have the ability to browse the entire website without having to log in, but they will need to login if they want to mark any favorites from search results. I&apos ...

JQuery organizing and arranging list with drag and drop functionality

Hey there, I've encountered a little dilemma. I've developed a drag and drop list feature in my WordPress plugin that allows users to rearrange categories. For the most part, it's working smoothly... The table is being populated from a MySQ ...

Modify database record when an eligible token is supplied

I have a question about the efficiency of my code, specifically line 16 (as commented). Would using $row to compare with a variable mentioned above be more efficient than writing another SQL query? When I tried using a variable and $row['field name&a ...

Exploring the Depths of Laravel Eloquent: A Guide to Master

Seeking guidance as a beginner in Laravel, I have encountered an issue with laravel relationships. Could use some assistance from the experts here. Dealing with four tables: 1. Users 2. Teams 3. Games 4. Picks The Picks table serves as my interme ...

Retrieve unique values for each day out of a total of 35 days using PHP

I am working on a project where I need to calculate the daily ROI value for 35 days and save it in the user table. Here is the code snippet that I am using: $total_days = 35; $total_amount = 200; $arr = array(); for($i = 0; $i < $total_days; ++$i) { ...

Encountering the "SQLSTATE[HY000] [2002] php_network_getaddresses" exception during a Laravel migration process

While executing the php artisan migrate command, an error occurs: Illuminate\Database\QueryException SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution (SQL: select * from information_ ...

Can a web page created with OptimizePress 2 utilize a full-width design?

I've adjusted the row to be full width so that the background extends fully, but I also need the content to reach the edges. Is there a way to achieve this? Looking forward to your solution. ...

PHP-based turn-based web game - encountering communication challenges

I am currently developing a PHP5-based turn-based web game. The game itself is quite straightforward, resembling a board game where two players join a session and take turns playing until there is a winner. Here is the issue I'm facing: User A a ...