Page 1 of 1

Failed database connection

Posted: Thu Sep 16, 2010 5:25 am
by Wikke
Hi, i'm new to php and i'm trying to connect to a database that I've made with phpMyAdmin.
I exported the database as a .sql file en added it to my project folder

when I run my project it always says no rows found.
This is the first time I'm trying to connect to a db with php so i think it's a stupid mistake.

This is my script

Code: Select all

<?php

// set database server access variables:
$host = "127.0.0.1";
$user = "";
$pass = "";
$db = "upload.sql";

// open connection
$connection = mysql_connect($host, $user, $pass);

// select database
mysql_select_db($db);

// create query
$query = "SELECT * FROM tblupload";

// execute query
$result = mysql_query($query);

// see if any rows were returned
if (mysql_num_rows($result) > 0) {
    // yes
    // print them one after another
    echo "<table cellpadding=10 border=1>";
    while($row = mysql_fetch_row($result)) {
        echo "<tr>";
        echo "<td>".$row[0]."</td>";
        echo "<td>" . $row[1]."</td>";
        echo "<td>".$row[2]."</td>";
        echo "</tr>";
    }
    echo "</table>";
}
else {
    // no
    // print status message
    echo "No rows found!";
}

// free result set memory
mysql_free_result($result);

// close connection
mysql_close($connection);

?> 

Re: Failed database connection

Posted: Thu Sep 16, 2010 5:52 am
by stuartr
Firstly you don't need to export the database in order to connect to it. The exported file is simply a text dump of the database and its structure and contents.

You connect directly to the database that you created using phpMyAdmin - this is running under a mySQLd process that will serve the database and make it available for connections. Assuming you are running phpMyAdmin locally and also creating the database on your local host the connection details would be:

Code: Select all

// set database server access variables:
$host = "localhost";  // Server name can found found at the top of the phpMyAdmin page
$user = "";
$pass = "";
$db = "upload"; // Database name as listed in phpMyAdmin (i.e. without the .sql suffix)

// open connection
$connection = mysql_connect($host, $user, $pass);
You may not ever come across the actual database file with MySQL - in most normal circumstances you will never need to. simply connect to the server that is running mySQL and the database will be available to you.

HTH

Stuart

Re: Failed database connection

Posted: Thu Sep 16, 2010 7:00 am
by Wikke
Thank you very much, it's finally working!