php, problem echo'ing results from mysql table

Associate
Joined
11 Oct 2008
Posts
268
I'm fairly new to php/mysql and I've been following the w3 tutorials.
i am using this code to connect to my database:

PHP:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }

mysql_close($con);
?>

Is there anyway to echo the results without having to use this whole chunk of code every time?. I tried the following with no luck.

PHP:
<?php
echo .$row['FirstName']; 
?>

Does anyone know what I'm doing wrong?
 
Ok, I think i have a basic understanding of it now, apart from I cant seem to close the connection without getting errors.

I have a connection.php file with the following code:

PHP:
<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'username';

/*** mysql password ***/
$password = 'password';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=dbname", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database <br /><br />';
 }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

?>

and i have a settings.php file that runs my query:

PHP:
<?php
    /*** The SQL SELECT statement ***/
    $sql = "SELECT * FROM website_test WHERE id='1'";
    foreach ($dbh->query($sql) as $row)
        {
        $id = $row['id'];
	$name = $row['name'];
        }

 ?>

now that all works fine when I echo my variables, but I cant seem to place the code to close the connection in any part without errors :( Any ideas where I can place it?

Cheers
 
Last edited:
Back
Top Bottom