Not understanding how PHP works when connecting using MySQL?

Hey, I was reading a document regarding why the old mysql is deprecated and the new improved mysqli is desirable. I understand the differences between PDO and MySQLi, i’ve chosen the path of the new and improved mysql. I have 3 questions, i’ll ask them here for simplicity.

That being said, i’ve created a simple connect.php file in atom. The file itself is only for testing purposes (no HTML attached to it). The next piece of code would be the OO implementation.

$host = "/*Location for server*/";
$username = "/*Username*/";
$password = "/*Password to connect*/";
$dbname = "/*The default database*/";

$connect = new mysqli($host, $username, $password, $dbname);
``
Now i want to fully understand the code above (at least a certain portion). Everything is understandable except the dbname parameter. I understand its optional, but for the sake of this thread, lets assume its mandatory. If we are creating a brand new **"_connect.php_"** file, how would that statement **"_$connect = new mysqli($host, $username, $password, $dbname);_"** be able to connect to a default database it i have not created a database at all? Am i to assume that if their is no database by the name specified, that the PHP engine will automatically create one?

2nd question, what is PHPMYADMIN? I understand it is a GUI that is embedded within PHP that will simplify my life with databases, etc. However, if i so wish, can i simply never use it? What i mean is, can't i just create, edit, update and delete database rows/columns within **"_<?php ?>_"** without using the GUI? 

3rd question, if i have a **"_connect.php_"**, should i simply use **"_required once("connect");_"** (THE UNDERSCORE BETWEEN REQUIRED AND ONCE DID NOT WORK HERE) whenever i want to run the connect portion of the project. I say once, because we don't want the file to constantly connect every few seconds, etc. Or would it be fine to not worry about how many times the file will be called? What about the close() portion of mysql? Will the php file run once then execute the close statement, closing down the database connectivity? Or is it something were we need to tell the file that it should only close() whenever something big happens? How would be translate that into code? 


APOLOGIES FOR THE LONG QUESTION, thank you so much. Want me to clarify more? Whenever i get the chance, i'll be sure to provide more information. Anything is well appreciated! Thanks.

To answer your question, $dbname is the database you want to connect to. It is mandatory otherwise the server wouldn’t know which database to connect to. I would even suggest it’s the most important parameter!! I’m not sure that I understand what you mean by a default database.

1 Like

I just checked and it is not mandatory.

As you can see from the connection script below an error is not returned and a database can be selected using mysqli_select_db(…)

http://php.net/manual/en/mysqli.select-db.php

Below is part of a DEBBUG script for testing database connection.

function fred($val)
{
echo '<pre>';
  print_r($va;);
echo '</pre>';

}

$dbh =  mysqli_connect
(
  $db['default']['hostname'],
  $db['default']['username'],
  $db['default']['password'],
  $db['default']['database']
);
fred($dbh, '$dbh');

$dbh =  mysqli_connect
(
  $db['default']['hostname'],
  $db['default']['username'],
  $db['default']['password']
);

fred( mysqli_info($dbh), 'mysqli_info()',1 );
fred($dbh, '$dbh');
$ok = mysqli_select_db($dbh, $db['default']['database']);
fred($ok, '$ok');
/* check connection */
if ($dbh->connect_errno) {
  fred($dbh, 'ERROR: ' .__LINE__); 
  $msg = sprintf(xxx, __LINE__, mysqli_error());
}     

// get results
$sql = 'SELECT xrl, date from jokes LIMIT 0,11';
$obj = $dbh->query($sql, MYSQLI_USE_RESULT);
if($obj):
  echo '$sql: <b>' .$sql .'</b>';
  while ($row = mysqli_fetch_object($obj)):
    echo jj, "&nbsp;&nbsp;" .$row->date ,js,js,js, $row->xrl;
  endwhile;
else:         
  fred($obj, 'ERROR: could not get $dbh->query($sql) ' .__LINE__); 
endif;  
break;

1 Like

PhpMyAdmin() is not mandatory but it is a very useful tool. Databases can be quickly created, copied, deleted, uploaded, downloaded. SQL statements can be quickly tested, checked, verified, etc,

1 Like

A leading and trailing ` is required to ensure the underscore and various other scripts display correctly. The ` is usually top left hand key on most keyboards. For lengthy scripts three leading and trailing ``` are required on their own line.

Usually only a single require_once() is necessary to connect but the connection result may be required in some of the database functions;

A useful list of database functions and comparisons:

http://php.net/manual/en/mysqli.summary.php

1 Like

Let me nail it straight to the point

i’ve chosen the path of the new and improved mysql

This decision is wrong. You should choose PDO instead. mysqli is so complex for a newcomer that you’d waste a lot of your and our time, but in the end will switch to PDO anyway.

how would that statement be able to connect to a default database it i have not created a database at all?

well, it wouldn’t then. as simple as that.

Am i to assume that if their is no database by the name specified, that the PHP engine will automatically create one?

Surely no. For a multitude of reasons. A database server is another state, and it will be considered an aggression at the very least

what is PHPMYADMIN?

It’s a gui tool designed to help newcomers like you to deal with a database. Of course it is not mandatory but many PHP users just can’t do a single step without it. So I suppose you will stick to it as well.

However, if i so wish, can i simply never use it?

Yes, of course. In this case you’ll have to use a mysql console that will scare you more than 10 Phpmyadmins. Yet it will be a good experience. Personally i prefer a console over phpmyadmin.

should i simply use “required once(“connect”);” whenever i want to run the connect portion of the project.

This file should be included once per script execution.

we don’t want the file to constantly connect every few seconds

dunno what you mean here but on a heavily loaded site we connect a hundred of times per second.

What about the close()

Just forget about this function, you don’t need it

3 Likes

With respect to the database name being optional, the key concept to understand is that you are connecting to a database server and not an actual database. The server may contain multiple databases. The same connection can be used to access any of them that the user has access to.

Specifying the database name is merely a convenience.

Suppose the server has two databases named db1 and db2 and you connect without specifying a database name.

// Both of these will work assuming each database has a table called users
SELECT * FROM db1.users;
SELECT * FROM db2.users;
// But this will error out since no default database was specified
SELECT * FROM users;

Most of the time the database name will be specified thus eliminating the need to prefix your table with the database name.

It is also interesting to note that as long as both databases are on the same server, mysql allows you to join across databases:
SELECT * FROM db1.users LEFT JOIN db2.userProfiles ON …

And yes, if you are just starting out, use PDO. Don’t be put off by the fact that the interface uses objects. You don’t need to use objects for the rest of your code if you don’t want to.

4 Likes

My bad. I was looking in the wrong part of the PHP manual.

2 Likes

Thank You all for the information provided. So far from my understanding, PHPMyAdmin is merely a tool to simplified databases and sql. Which grants me the way to either use it within the GUI or merely avoid it an use it within my code (connect.php).

The reason why i state why i should use a require_once() over include is because a require will be interrupted if their is an error in code and present me with the issue while an ‘include’ will simply continue running. I also choose the path of using (once) because well i’m assuming we only need to call the connection once? My plan is to have use ‘connect.php’ to connect to the database, create a table, select the table, and very that all went accordingly (error detection). Should that php file only contain a connection to a database an no SQL codes, etc. As @colshrapnel mentioned, ‘This file should be included once per script execution’, am i to assume that every php file needs to include a connect.php to be able to process?

I choose MySQLi for the visual simplicity. PDO simply looks overwhelming and that is why i avoided it. I will however that a deeper look at it right now since PDO supports more databases that MySQLi which is only for MySQL database. Once i get off work, i’ll go ahead an take a look at PDO. If you have any links or information that would make it easier, i’d appreciate it! Thanks again for all the help.

1 Like

Any script that has to access a database will need the connection.

When I abandoned mysql, I first chose mysqli for similar reasons. I thought the syntax looked more familiar and pdo looked complex and strange to me.
But when I did try pdo, I was surprised how easy I found it to make the transition and I much prefer using pdo now.

@colshrapnel has written a tutorial on pdo.

1 Like

Last I knew the PHP documentation stated that mysqli was preferred over PDO.

AFAIK this is because PDO can not do some MySQL-specific stuff.
Though in my use of PDO (which is my preference) I have not run into any snafus yet.

Re phpMyAdmin, it is not part of PHP but often is part of packages like XAMPP. It is an application.

I used it for a long time way back when. I gave Workbench a try for a while, but now I much prefer using the CLI.
As colshrapnel posted, using a CLI can be a bit scary for those accustomed to using graphic interfaces but once you know what you’re doing you don’t need all the inputs, buttons etc.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.