Connecting to database

I created a database and am trying to test connection with a php file. It gets an error on this line

$dbhandle = mysql_connect($hostname, $username, $password)

and I understand that this may be due to deprecated code

Could you tell me what is the alternative, please’

PDO or MySQLi.

Check this W3schools page out - it cover both PDO and MySQLi - http://www.w3schools.com/php/php_mysql_connect.asp

I’m new to this (as to everything else…)

<?php
$username = "pintotou****";
$password = "******t";
$hostname = "localhost"; 

//connection to the database
$dbhandle = @mysql_connect($hostname, $username, $password) 
 or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

//select a database to work with
$selected = mysql_select_db("Chains",$dbhandle) 
  or die("Could not select examples");

//execute the SQL query and return records
$result = mysql_query("SELECT ID, Chain,Country, City");

//fetch tha data from the database 
while ($row = mysql_fetch_array($result)) {
   echo "ID:".$row{'ID'}."Chain:".$row{'Chain'}."Country ". //display the results
   $row{'Country'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>

the mysql functions are deprecated so you should really use one of the alternatives.

That’s what I am asking. What are thy in this script, in that line?

If you are just starting out, I would recommend going the PDO route.
You will need a new script as PDO is a bit different.
google,
PDO named placeholders

Using named placeholders will be more intuitive if you are beginning.
for starters, you will need to change how you connect to the database,

Hi all

many thanks

I managed to solve it

SOLVED

It is actually highly recommended to switch over. The old mysql_* functions are removed as of PHP 7 and will most likely never exist anymore. I suggest you switch now since you are starting new before your web host actually switches to PHP 5.5 where mysql_* functions have been removed completely. The reason why we are all telling you this is because your snippet you just posted in this topic will actually break as soon as the upgrade of PHP 5.5 hits.

As mentioned by others, you can use either PDO or MySQLi_*
Most use PDO, but if you are starting fresh, I think you can use MySQLi_*

I also suggest using MySQLi_* OOP as well because in the end, you’ll start using OOP and starting with OOP database connections will actually help a lot. Most successful applications use OOP.

I’ll be even nice and give you 2 snippets of your snippet in MySQLi_* OOP

Using regular query

<?php
define('HOST', 'localhost'); // Host
define('USERNAME', 'root'); // Username
define('PASSWORD', 'root'); // Password
define('DATABASE', ''); // Database

// Create a new connection using MySQLi_*
$db = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if($db->connect_errno) {

    // Don't display the actual error.
    // This can allow users to know your database username and password.
    // An example can be when the server is down, but the PHP engine isn't.
    die('Error connecting to the database.');

}

$sql = "SELECT ID, Chain, Country, City FROM location_table"; // SQL string
$mysqli = $db->query($sql); // Query the SQL string

// This part is crucial
// Without $mysqli->num_rows
// If you have no records in the database or a typo, by just having the while loop out in the open
// You'll end up with an infinite loop causing Fatal Error: Allowed Memory Size of ______ Bytes Exhausted
// To avoid this, you will need an error handling which is num_rows
if($mysqli->num_rows) {

    // Throw your results in a while loop
    while($row = $mysqli->fetch_assoc()) {

        // We only are using line breaks and proper spacing to make the results more pretty.
        // You don't have to use line breaks and proper spacing if you don't want to, but it's going to be hard to read.
        // You'll end up with ID:1Chain:NULLCountry:USCity:New York if you don't line break and proper space them
        // With line breaks and proper spacing, you see

        // ID: 1
        // Chain: NULL
        // Country: US
        // City: New York

        print('ID: ' . $row['id']); // Id
        print('<br />'); // Line break
        print('Chain: ' . $row['chain']); // Chain
        print('<br />'); // Line break
        print('Country: ' . $row['country']); // Country
        print('<br />'); // Line break
        print('City: ' . $row['city']); // City
        print('<br /><br />'); // These last line break are important if you want to have a set of records in a block like style

    }

} else {

    print('No records in the location_table'); // No records in the location table

}

Using prepare statements

<?php
define('HOST', 'localhost'); // Host
define('USERNAME', 'root'); // Username
define('PASSWORD', 'root'); // Password
define('DATABASE', ''); // Database

// Create a new connection using MySQLi_*
$db = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if($db->connect_errno) {

    // Don't display the actual error.
    // This can allow users to know your database username and password.
    // An example can be when the server is down, but the PHP engine isn't.
    die('Error connecting to the database.');

}

$sql = "SELECT ID, Chain, Country, City FROM location_table"; // SQL string
$mysqli = $db->prepare($sql); // Query the SQL string
$mysqli->execute(); // Execute the query string
$mysqli->store_result(); // Store the result for later checking

// This part is crucial
// Without $mysqli->num_rows
// If you have no records in the database or a typo, by just having the while loop out in the open
// You'll end up with an infinite loop causing Fatal Error: Allowed Memory Size of ______ Bytes Exhausted
// To avoid this, you will need an error handling which is num_rows
if($mysqli->num_rows) {

    $mysqli->bind_result($id, $chain, $country, $city); // Bind all the columns you specified in the SQL string and assign a specific variable for them

    // Throw your results in a while loop
    while($mysqli->fetch()) {

        // We only are using line breaks and proper spacing to make the results more pretty.
        // You don't have to use line breaks and proper spacing if you don't want to, but it's going to be hard to read.
        // You'll end up with ID:1Chain:NULLCountry:USCity:New York if you don't line break and proper space them
        // With line breaks and proper spacing, you see

        // ID: 1
        // Chain: NULL
        // Country: US
        // City: New York

        print('ID: ' . $id); // Id
        print('<br />'); // Line break
        print('Chain: ' . $chain); // Chain
        print('<br />'); // Line break
        print('Country: ' . $country); // Country
        print('<br />'); // Line break
        print('City: ' . $city); // City
        print('<br /><br />'); // These last line break are important if you want to have a set of records in a block like style

    }

} else {

    print('No records in the location_table'); // No records in the location table

}

You technically don’t need to use prepared statements if you don’t have a WHERE clause. The only time you actually need to use prepared statements is when there’s user inputs. Basically where the WHERE clause is.

1 Like

RESOLVED

Thank you

your mysql connection most be like this for it to work.

$dbhandle = mysql_connect(“$hostname”, “$username”, “$password”) or die(“unable to connect to mysql”);

your mysql connection must NOT be like that or it will not work in a few weeks time.

Your connection statement should look like one of the following two for it to work.

$dbhandle = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if (mysqli_connect_error()) {print 'Connect Error ('.mysqli_connect_errno() .') '. mysqli_connect_error()); die();}

or

try {
$dbh = new PDO('mysqlhost=:'.HOST.';dbname='.DATABASE,  USERNAME, PASSWORD );
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage();
    die();
}

The mysql_connect interface is now effectively dead - it will be removed completely from PHP in the next few days.

1 Like

Hi

Thank you all

In fact, I managed to get it to work and connect to the database at the server. It was only a test to see if the database was working. Now, that I know it does, there will not be any need for the scrip in future.

In any case I will look at your code tomorrow morning when the head is fresh.

Regards

out of curiosity this is how it is working for me

$db_handle = mysql_connect($server, $user_name, $password);

$db_found = mysql_select_db($database, $db_handle);

if ($db_found) {

that connection was deprecated many years ago and is going to be deleted in a few days time.

No new database code written five years ago should have been written like that as by the end of this year it will no longer work.

Hi, thanks felgall

i will amend it.

Hi felgall

Finally I got round to updating the deprectaed code and as usual got terribly confused

Following online instructions II changed my earlier code to

mysqli_connect("localhost","pintotou_*****","*****","pintotou_search" ) or die ("could not connect");

but comparing with your code I see quite a different structure

Are they both valid?

mysqli_connect and new mysqli are kind of the same thing. Just that new mysqli is OOP style and mysqli_connect is procedural style. But both do the same thing.

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