-1

I'm having a bit of a weird problem. I'm trying to read data of my database, the connection works but the instruction doesn't.

I try with code that should work, query("show tables"); but this also doesn't show anything.

Application is another php in which I make the connection and configuration with the database.

use Aplication as App;

class Company {

public static function login($username, $password) {

      $app = App::getSingleton();
      $conn = $app->conexionBd();

// Check connection

      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
        }
echo "Connected successfully";

      $query = sprintf("SELECT * FROM company E WHERE E.Name= %s", $conn->real_escape_string($username));

      $rs = $conn->query($query);



      if ($rs)
      {

        $row = $rs->fetch_assoc();
        $c = new Company($row['id'], $row['Name'],$row['Password']);
        $rs->free();

        return $c;
      }
      return false;
  }
}

What is wrong?

Thanks in advance!

Nick
  • 138,499
  • 22
  • 57
  • 95
  • 1
    should `use Aplication as App;` be `use Application as App;`? – Nick Apr 27 '19 at 02:41
  • In what way is it "not working"? Is `$rs` false? If so, what was the error from the database? – David Apr 27 '19 at 02:43
  • 1
    You haven't placed quotes around the search string in your SQL query, but you'd already know you have a syntax error if you checked the return status of call to mysqli::query. Further, you'd be better using a prepared statement for this: it's less susceptible to SQL jnjection –  Apr 27 '19 at 02:43
  • @yourcommonsense I'm not questioning the value of prepared statements but I don't see that the question you've identified as a duplicate is related to the problem here. –  Apr 27 '19 at 05:21

1 Answers1

0

Best way to troubleshoot such problems is to print the query and run on mysql command prompt.

E.Name= %s should be changed to E.Name= '%s' as strings should be enclosed by quotes.

Akash Sharma
  • 721
  • 3
  • 6
  • 3
    Actually, the best way to troubleshoot this is to write code that checks the return value for any errors and reports the error message. That will trap far more than simple syntax errors. –  Apr 27 '19 at 02:45
  • After `$rs = $conn->query($query);` check for `$conn->connect_error` if error then handle that situation. – Akash Sharma Apr 27 '19 at 02:49
  • 1
    @ReddHerring actually, [mysqli can report errors on its own](https://phpdelusions.net/mysqli/error_reporting), so no need to check every return value ;) – Your Common Sense Apr 27 '19 at 04:31
  • @YourCommonSense I didn't know about that method, but whether the OP checks the return value or relies on exceptions, the important thing is that he looks at the error message. –  Apr 27 '19 at 05:18