r/PHPhelp • • Aug 14 '20

Getting data from PHPMyAdmin (beginner question)

I've not touched PHP in 15 years or so (and the last time I was a beginner at best) so I'm a bit rusty.

My problem is I have a database (called table1) with a table in that has two data rows and when I try to select the info from the db to a PHP-page it successfully establishes the collection but doesn't seem to pull any data from the db.

I've got some server space through one.com where I have a database.

My issue is that I don't understand why it doesn't process my SQL. I've uploaded the super basic page (as a .txt) where I try this in hope that someone can identify where I go wrong. Username, password etc are changed (connection is successful so the issue doesn't seem to be there).

https://1drv.ms/t/s!AhzkfwJlWNPrhbIKlzv6JoRrXoGQ0w

I've got my page one a server hosted by one.com using PHP 7.4 and PHPMyAdmin if that information is important.

8 Upvotes

7 comments sorted by

4

u/twistdafterdark Aug 14 '20 edited Aug 14 '20

I think you're missing the database name in the conn

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

should be

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

Then $sql = "SELECT * FROM <tablename>"; replace <tablename> with the actual tablename instead of the databasename

Edit:

On a different note, you should look into MVC framework and move the database connections to a separate file instead of directly in your html template.

Here's a Build a PHP MVC Application playlist that gives a decent explanation on it.

1

u/italrose Aug 14 '20

Big thanks! The missing $databasename was the issue it seems because now it works.

Regarding stripping the HTML file of the db connections I do recall doing something like that. Will check out the MVC framework. Thanks for the advice on this as well. Much appreciated.

2

u/Fukutoshin10kATO Aug 14 '20

Thanks for posting that YouTube link, it's something I need to do to. I actually find it annoying that it is that difficult to create a simple CRUD database app where you have more than one table. I've found things that will do it for a single table but not for multiple tables, even where the other tables are just lookup tables for the "main" table. The only one I've found is quite expensive - it is a hobby not something I make money off so I'm happy to pay a small amount but not many hundreds of dollars. A little off-topic, but any comments appreciated.

3

u/greg8872 Aug 14 '20 edited Aug 14 '20

Note on the videos, there are some things done that are outdated (pre v7.x of PHP) and will generate deprecated warnings.

In particular so far, in Part 5 (Controllers) it shows to use this:

call_user_func_array( [ $this->controller, $this->method ], $this->params );

This generates:

PHP Deprecated:  Non-static method Home::index() should not be called statically

A work around is to actually create an object of the class, and then call it's method:

$controller = new $this->controller;
$controller->{$this->method}( $this->params );

(or to go and set all the methods to be static, but I refer the way I gave)

EDIT: oh, then in the controller's method, instead of doing this:

public function index( $name = '', $age = 0 ) {

    // do something with $name and $age...
}

you should do something like:

public function index( $params = [] ) {
    $name = array_key_exists( 0, $params ) ? $params[0] : '';
    $age  = array_key_exists( 1, $params ) ? $params[1] : 0;

    // do something with $name and $age...
}

2

u/greg8872 Aug 15 '20

Just a further note on my workaround with the params, I added a protected variable for params in the parent Controller class, and added a constructor that you pass params into, then also added a method to grab the params:

class Controller {

	protected $params = [];

	public function __construct( $params = [] ) {
		$this->params = $params;
	}

	protected function getParam( $index, $default = false ) {
		return ( array_key_exists( $index, $this->params ) ) ? $this->params[ $index ] : $default;
	}

    // Other methods...

}

And then when initialing of the controller in the App, pass it the array of parameters from the request.

Then inside the methods in the different controller classes I can do this:

public function index() {
	$name = $this->getParam( 0, '' );

    // Rest of code...
}

2

u/twistdafterdark Aug 14 '20

The way I usually do it is to create a model which communicates with the database, that model will then have all the queries I'd need to make with different methods referencing the various different tables in the database. I then call the model from my controllers and call the various methods I need for any given page.

Example: ./models/DBModel.php

<?php


class DatabaseModel
{
    protected $hostname = 'host';
    protected $username = 'user';
    protected $password = 'passwd';
    protected $database = 'dbname';

    function __construct()
    {
        $this->conn = new mysqli($this->hostname, $this->username, $this->password, $this->database);
        if ($this->conn->connect_errno) {
            echo "Connect failed: %s\n" + $this->conn->connect_error;
            exit();
        }
    }

    protected function fetch_data($query)
    {
        if ($result = $this->conn->query($query)) {

            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    yield $row;
                }
            }
        }
    }

    function fetch_users($userlist){
            $query = "SELECT * FROM Users WHERE name in (".$userlist.")";
            $result = $this->fetch_data($query);
            return $result;
    }
}

Then in ./controllers/UserController.php I'd call

<?php
require_once ../models/DBModel.php

Class User {
    function __construct(){
        $this->datamodel = new Database;
    }

    function index($userlist = []){
        
        $user = $this->datamodel->fetch_users($userlist);
        echo $user;
    }
}

1

u/Fukutoshin10kATO Aug 14 '20

Thanks for that. I understand each step so I'll give it a try 🙂