Alexander
Alexander

Reputation: 727

How to retrieve information from a database

I have the following code to retrieve information from a database. It connect connects to the database, but when I try to display the information I don't see anything. I only get the dash lines. I think the problem is in the while loop, I just can not see where my mistake is. Can anyone help??

 $connection = mysql_connect("127.0.0.1","root","xxxxxxxx");
        if (!$connection)
        {
        printf("Can't connect to MySQL Server.", mysqli_connect_error());

        }


    mysql_select_db('xxxxxx') or die ('Could not select database');
        echo 'You have been connected succesfully to your database';

        $query = "SELECT *FROM testing";
        $result = mysql_query($query) or die("Query fail:".mysql_error());


        while ($row = mysql_fetch_array($result));
        {
            echo $row['age']."--".$row['sex']."--".$row['id']."--".$row['country']."--".$row['sport']." ";
        }

        ?>

Upvotes: 0

Views: 71

Answers (3)

Petr R.
Petr R.

Reputation: 1237

You should remove the semicolon (;) after while(...), so your final code will look like:

while ($row = mysql_fetch_array($result))
{
    echo $row['age']."--".$row['sex']."--".$row['id']."--".$row['country']."--".$row['sport']." ";
}

Whatever is in your while loop (between { and }) will be called as many times as many rows will return your query. For example, if your query will return 4 rows, then your code (echo ...) will be repeated 4 times. In the first run, variables $row["age"], $row["sex"], $row["id"] and $row["country"] will contain the results for the first row. On the second run, these variables will contain the results of the second row...


Also, please, don't use the mysql_* functions, they are deprecated and will be removed in the future versions of PHP. Use MySQLi or PDO instead. See Why shouldn't I use mysql_* functions in PHP? for more details.

Upvotes: 1

Jon Lachonis
Jon Lachonis

Reputation: 931

Use mysqli

$db = new mysqli("localhost","admin","XXXXXX","test");
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$query = "SELECT * FROM `testing`";  

if(!$result = $db->query($query)){
    die('There was an error running the query [' . $db->error . ']');
}

// echo $result->num_rows;  Uncomment to make sure there is data being ruturned

while($row = $result->fetch_assoc()){
    echo $row['age']."--".$row['sex']."--".$row['id']."--".$row['country']."--".$row['sport']." ";   
}

Upvotes: 0

user3604560
user3604560

Reputation: 11

I was having a similar issue, turns out my DB had no information in it, and one of my value names was incorrect. Can you confirm there are valid values in your DB?

Upvotes: 0

Related Questions