Do not retrieve emails from the database if the cell is empty

I created a code that retrieves emails from all users and saves them in a text file. However, there are some users who don't have an email because they registered using their phone number. When I try to fetch the emails, it gets dumped into the text file like shown in this screenshot here.

My goal is to only fetch emails if the cell is not empty or null. Can someone assist me in fixing this issue?

$sql = mysql_query("SELECT * FROM user"); 
while($row = mysql_fetch_array($sql)) {
$email = $row['email'];
if($email != "" && $email != NULL) {
    $fp = fopen("emaillist.txt", "a");
    $savestring = "\n$email";
    fwrite($fp, $savestring);
    fclose($fp);
}
}
echo  "DONE ";

Answer №1

Modify the SQL query to retrieve all records from the "user" table where the email field is not equal to NULL.

SELECT * FROM user WHERE email IS NOT NULL;

Answer №2

Retrieving all records from the user table where email is not empty.

To validate against NULL values, the suitable expressions are:

column IS NULL or column IS NOT NULL.

Answer №3

Here's an alternative approach:

$sql_query = mysql_query("SELECT * FROM user  "); 
while($data_row = mysql_fetch_array($sql_query)) {


    if (strlen($data_row['email'] ) > 0){
        $user_email = $data_row['email'];
        $file_pointer = fopen("emaillist.txt", "a");
        $save_string = "\n$user_email";
        fwrite($file_pointer, $save_string);
        fclose($file_pointer);
    }
}
echo  "Process complete ";

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

Easy PHP navigation options

Creating a basic PHP page with includes is proving challenging when it comes to navigating URLs using '../' to find the correct path to the folder. Is there a straightforward way to set up a simple PHP navigation without involving MySQL or other ...

Ways to prevent ERR_INSUFFICIENT_RESOURCES when making AJAX requests

It's been a while since I dabbled in JavaScript, so please be patient with me. I'm currently developing an application that generates reports on student data using PHP as the backend. Periodically, we need to refresh the database used for these ...

Looking for a secure method to run code from external sources?

Is there a way to enable users to write and run PHP code on my website without using "eval" for security reasons? I've searched online but couldn't find a suitable solution besides call_user_func, which doesn't allow running full PHP scripts ...

PHP Error - Noticed a non-existent constant 'x' being used in the code, assumed it to be 'x

How to Retrieve Data from a Table, Pass it to the Controller in JSON Format, and Display it in a View Using AngularJS I am looking to extract data from a controller's json-encoded variable and showcase it on a view page through angularjs <div cla ...

Symfony2 - Utilizing an Entity repository to encode data into JSON for efficient AJAX calls

I'm currently working on implementing a dynamic text field with AJAX autocomplete functionality. In order to handle the AJAX call, I have created a method in the controller. public function cityAction(Request $request) { $repository = $this-> ...

Using AJAX, SQL and PHP to send data to a separate page for processing

This is the code I use to retrieve questions via ajax from a list of questions stored in a SQL database. <form id="reg-form3"> <ul class="nav nav-list primary push-bottom"> <? $db['db_host']="localhost"; ...

Switch Your PHP Script to Use PDO

Hello, I am new to PHP and seeking some guidance. My goal is to convert the following code to PDO in order to generate a JSON output for an Android app that I am currently working on. I have tried several solutions but encountered issues with the JSON resp ...

Troubleshooting a logout issue involving Ajax requests and header redirection

In order to enhance the security of my system, I am working on a feature that will prevent users from executing functions when they are not logged in. When an unauthorized user tries to do so, a message will pop up indicating that they must be logged in be ...

Capture and store components in Laravel using a method other than the primaryKey

I'm facing a challenge where I need to retrieve an element from the database but using the FIND method isn't working for me. This is because FIND only searches by the primaryKey, and what I require is not based on my primaryKey. Therefore, I appr ...

loop not functioning properly with file type input

Having trouble uploading an image and copying it into a folder named images within a loop. Can you assist with solving this issue? Here's my code: $sql="SELECT * FROM product"; $q=$conn->query($sql); while($r=$q->fetch(PDO::FETCH_ASSOC)) { $cod ...

The autoloading of Laravel phpspec is not working

Currently, I am in the process of setting up phpspec within a Laravel project. After successfully installing phpspec, I have been able to run it within my project without encountering any issues. Within my composer.json file, the relevant lines are as fo ...

Updating databases with the click of a checkbox

Currently, I am developing a program for monitoring cars as part of my thesis. My current focus is on user management, and I have come across an issue where the database needs to be updated when the status of a checkbox changes. To visualize checkboxes, y ...

Reorganizing Array from PHP after Decoding Facebook Open Graph

I'm in the process of creating an app that would greatly benefit from suggesting a user's Facebook friends as they type. However, I've hit a roadblock when it comes to converting the Open Graph result (retrieved by accessing a user's fr ...

Trying to replace apostrophes using preg_replace() and str_replace() turned into a total nightmare! - Re

Can someone assist me in figuring out why this code is not functioning properly? $cssid = preg_replace("/'/", "", $cssid); I am attempting to remove single quote marks from some HTML... Thank you! H EDIT This function is meant to reconstruct the D ...

Unexpected restarts are occurring in a lengthy PHP script

I have a PHP script that I execute using the $.ajax() Javascript function: $.ajax({ type: "POST", url: "/myscript.php", data: $("#my-form").serialize() }); Details of myscript.php class myclass{ public function __construct(){ $i ...

What is the best way to verify HTML using RSS?

Looking to improve my skills in HTML/CSS/PHP development, I'm faced with a challenge when it comes to validating code that contains content beyond my control, such as an RSS feed. For instance, on my home page, which is a .php document containing bot ...

What is the best way to create a link in PHP when a backslash is included in the

I recently received help on adding a forward slash to my URL and redirecting it internally. The solution I found worked well, you can check it out here, but now I've encountered a new issue. After resetting your password, you're required to chan ...

I am looking to eliminate the double quotation marks from a JSON file so that I can properly utilize

How can I successfully save a JSON return into an NSDictionary when there are spaces and double quotes present in the data? Is it possible to parse SBJSON to remove the double quotes before saving to rowsArray? rowsArray: { Rows = ( { ...

Building a table using jQuery and adding elements using JavaScript's append method

Greetings! I've been attempting to add new records from a form that registers or updates student information, but unfortunately it doesn't seem to be functioning correctly. Can anyone point me in the right direction as to why this may be happenin ...

Data from Ajax calls is only available upon refreshing the page

I am working on adding a notification button for inactive articles on my blog. I want to use AJAX so that the admin does not have to reload the page to view newly submitted inactive articles. I am trying to prepend HTML data to: <ul id="menu1" class= ...