简体   繁体   中英

How to display a message if empty string found using num_rows, Object-Oriented procedural, in mysql table?

Ok, I have a MySQL table with 3 columns (city, color, votes). I have an HTML table with colors, some of these colors don't exist in the MySQL table. I am trying to display "0" if there is not a match. I receive "" in the console when the color doesn't exist, but I want to display "0" in the HTML table for these colors. Any idea?

I have this php so far:

$co = $_REQUEST['color'];

$sql = "SELECT SUM(votes) AS sum FROM Votes WHERE color = '$co'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["sum"];
    }
} else {
    echo 0;
}

and this is the ajax call:

<script>
$(document).ready(function(){
    $('#red').on('click', function() {
        var colorId = $(this).attr("id");

        $.ajax({
            "url": "tables.php", 
            "data": {"color" : colorId}, 
            success: function(response) {
                $("#redr").html(response);
                console.log(response);
            }
        });
    });

    $('#orange').on('click', function() {
        var colorId = $(this).attr("id");

        $.ajax({
            "url": "tables.php", 
            "data": {"color" : colorId}, 
            success: function(response) {
                $("#oranger").html(response);
                console.log(response);
            }
        });
    });

    $('#green').on('click', function() {
        var colorId = $(this).attr("id");
        $.ajax({
            "url": "tables.php", 
            "data": {"color" : colorId}, 
            success: function(response) {
                $("#greenr").html(response);
                console.log(response);
            }
        });
    });

    $('#indigo').on('click', function() {
        var colorId = $(this).attr("id");
        $.ajax({
            "url": "tables.php", 
            "data": {"color" : colorId}, 
            success: function(response) {
                $("#indigor").html(response);
                console.log(response);
            }
        });
    });


    $('#yellow').on('click', function() {
        var colorId = $(this).attr("id");
        $.ajax({
            "url": "tables.php", 
            "data": {"color" : colorId},
            success: function(response) {
                $("#yellowr").html(response);
                console.log(response);
            }
        });
    });

    $('#blue').on('click', function() {
        var colorId = $(this).attr("id");

        $.ajax({
            "url": "tables.php", 
            "data": {"color" : colorId}, 
            success: function(response) {
                $("#bluer").html(response);
                console.log(response);
            }
        });
    });

    $('#total').on('click', function() {
        var sumofval = 0;
        $(".val").each(function () {
            if ($(this).text() !== '') {
                sumofval = sumofval + parseInt($(this).text());
            }
            $('#totalr').text(sumofval);
            console.log(sumofval);
        });
    });

});
</script>

Simply check the result of your query before passing back a value.

A SUM() query will Always return a row and only one row, so you have to check the result and then if it is null (no value for the sum) echo a zero otherwise echo the number from the sum()

$sql = "SELECT SUM(votes) AS sum FROM Votes WHERE color = ?";
$stmt = $conn->prepare($sql);
// assumed `color` was a string column, 
// if its integer is `'i'` instead of `'s'`
$stmt->bind_param('s', $_REQUEST['color']);
$stmt->execute();

$res = $stmt->get_result();

$row = $res->fetch_assoc();

echo $row['sum'] == '' ? 0 : $row['sum'];

Note: I also changed your code to use a prepared query with bound values. This is far more secure than the concatenated value mechanism you were using to avoid SQL Injection Attack

Try using this.

$('#red').on('click', function() {
  var colorId = $(this).attr("id");

  $.ajax({"url": "tables.php", "data": {"color" : colorId}, success: function(response) {
    response = Number(response)
    response = response.toFixed(0)
    $("#redr").text(response);
    console.log(response);
  });
});

It uses .text() rather than .html() . And it turns a possible blank response from your php web endpoint into an actual number.

I used two lines of code to do that because of the Redmond Middle School Science Project known as Internet Explorer. Here's what those lines do:

It's possible coming in to the ajax callback that response is an actual number, or a text string containing a number, or an empty text string, or a null value. response = Number(response) forces it to be a number. In the empty or null cases, the number comes out zero.

The second line response = response.toFixed(0) converts the number back to a text string, with zero digits after the decimal point.

Then giving that text string to .text(response) puts it into your web page at the appropriate place.

If it weren't for Internet Explorer you could do

... .text(Number(response).toFixed(0)) 

all in one line. But IE can't cope with using the .toFixed() method on anything but an actual declared variable. Plus, the extra lines are slightly easier to explain.

Pro tip Always indent your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM