Welcome to WebmasterWorld Guest from 35.172.195.49

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

PHP with MySQLi Object-Oriented Programming (OOP)

MySQLi, OOP

     
12:30 am on May 10, 2016 (gmt 0)

Junior Member from US 

5+ Year Member

joined:Dec 1, 2012
posts: 90
votes: 0


I need to convert my website to MySQLi with OOP:
Below works. Is there anything I've missed or need to do better or differently?
I really need to get this done so any help would be appreciated.

<?php
// OOP way at very top of page
$db = new mysqli('localhost','username','password','database');

if ($db->connect_error) {
trigger_error('Database connection failed: ' . $db->connect_error, E_USER_ERROR);
exit();
}
?>

BUNCH OF website stuff/then my SELECT:

<?php
// Set up query
$query = "SELECT pagename, image, name FROM table";

// OOP way
$result = $db->query($query);
while ($row = $result->fetch_assoc())
{
?>

<figure>
<a href="<?php echo ($row["pagename"]); ?>">
<img src="<?php echo ($row["image"]); ?>"></a>
<figcaption>
<a href="<?php echo ($row["pagename"]); ?>">
<h2><?php echo ($row["name"]); ?></h2></a>
</figcaption></figure>

<?php
}
// OOP way
$result->free();
$db->close();
?>
2:29 pm on May 25, 2016 (gmt 0)

Administrator

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
posts:12555
votes: 3


Just looking for confirmation? Well, it looks like you are handling things as expected -- open connection, check for errors, query, fetch, free and close. One habit you may want to consider is whether or not you want to use parentheses in your echo. echo is not actually a function (it is a language construct), so you are not required to use parentheses with it.

[php.net...]
2:28 pm on May 31, 2016 (gmt 0)

Junior Member from US 

5+ Year Member

joined:Dec 1, 2012
posts: 90
votes: 0


Thank you for responding.