Allenph Allenph - 6 months ago 13
SQL Question

Simple MySQL call to select an integer at a specific key not working?

I have this PHP:

<?php

$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");

if ($connection->connect_error) {
die("Connection failed: " . $Connection->connect_error);
}

$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
$check_emails_sent_result = $connection->query($check_emails_sent_query);

echo $check_emails_sent_result;

?>


This is a small piece of a much larger function on my site. This snippet is simply intended to get the value of the "emails" column (Which is an
int
column if that makes a difference) of my table where the IP matches the client's IP.

I added a fake entry for 11.111.111.111 in my database, and used the exact same query on PHPmyAdmin's SQL console. I got a result on the PHPmyAdmin console, but nothing is echoed here.

I have also checked that the connection is good, as you can see in my code. Additionally, I pasted another query from another part of my function, which retrieved its data just fine.

AS stupid or obvious as it may be, I can't seem to figure out why this particular query out of almost twenty won't retrieve its data?

Answer

Mysqli query() returns and object. Using the object:

<?php

$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");

if ($connection->connect_error) 
{
    die("Connection failed: " . $Connection->connect_error);
}

$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";

if ($check_emails_sent_result = $connection->query($check_emails_sent_query)) 
{ 
    while($obj = $check_emails_sent_result->fetch_object())
    { 
        $echo $obj->emails; 
    } 
} 

?>

You could use fetch_row() instead of fetch_object().

Documentation for the object is here:

http://php.net/manual/en/class.mysqli-result.php