0

I have a tutorial with the following code. A simple connector to MySQL server

$conn = new mysqli($servername, $username, $password);

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

What I do not understand is how the $conn object accesses connect_error. I thought an object has to access properties via class methods and so should be $conn->connect_error().

I am assuming connect_error is a class method. Can someone please also explain to me what the -> really means and does in OOP?

yivi
  • 42,438
  • 18
  • 116
  • 138
  • _I am assuming connect_error is a class method._ It’s not. It’s a property. Method calls in PHP end with parentheses (`()`); property calls do not. But as this is a question about PHP syntax, it’s not a programming problem and therefore not suited for Stack Overflow. A few PHP tutorials would be more appropriate. – Martin Bean Aug 24 '21 at 10:47
  • 1
    Please note that the tutorial you found and the piece of code that you shared is an example of code that you should never learn to write. Never check manually for connection errors. Instead enable mysqli error reporting. [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/questions/58808332/should-we-ever-check-for-mysqli-connect-errors-manually) – Dharman Aug 24 '21 at 10:52
  • @Dharman Thank you. I will look into that later. I think that's on another level. I am just working my way through the W3Schools PHP course. Unfortunately they don't have a tutor led discussion/support forum. This script is just to test each test connection you make. – BlackBeardie Aug 24 '21 at 11:07
  • Please don't learn PHP from W3Schools. They are well-known for having terrible tutorials. If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection – Dharman Aug 24 '21 at 11:08

0 Answers0