Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner's Question about accessing mysql using OOP

Tags:

php

mysql

I am reading the PHP and mySQL web development book and so far been doing all the PHP and mysql using procedural. But then it talks about accessing mysql with objects.

This works for me:
//I define $db so can connect
$query="select * FROM testing";
$result=mysqli_query($db,$query);
while($row=mysqli_fetch_array($result)){
  //echo the data
}

But when I try to do it with classes, it doesn't
@ $db=new mysqli('localhost','root','','test');
if(mysqli_connect_errno()){
echo "ERROR:";
exit;
}
$query="select * FROM testing";
$result=$db->query($query);
$row=$result->fetch_assoc();

Do I have to write my own class so it defines what query and fetch_assoc does? Or what?

like image 315
jpjp Avatar asked Feb 06 '26 16:02

jpjp


1 Answers

You should be setting up $db something like this:

$db = new mysqli("db_server", "db_username", "db_password", "db_name");
like image 110
John Rasch Avatar answered Feb 08 '26 04:02

John Rasch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!