Recently I have been building my first website and as it is my first time working with PHP and databases I am having trouble. I have been researching for an answer for over three hours now. After following several tutorials I cannot get the databases information to display inside the table on my webpage. The only items that appear are a table header and one blank row. Am I not connecting to the database or is it something else that has to do with my code? Below is the code from the PHP that is inside my html file.
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('jcsavage_initiumjobs');
if(!$conmnection){
die('Could not connect: ' . mysql_error());
}
$result = mysql_query("SELECT name, address, ages FROM companies ORDER BY name");
?>
<table id='company_tables' border='1' align='centre'>
<tr> <th colspan='3'>Companies</th> </tr>
<tr> <th>Name of Company</th> <th>Location</th> <th>Ages Accepted</th> </tr>
<?php
while($row = mysql_fetch_array($result)){
?>
<tr><td> <?php . $row['name'] . ?> </td><td> <?php . $row['address'] . ?> </td><td> <?php . $row['ages'] . ?> </td></tr>
<?php
}
?>
</table>
<?php
mysql_close($connection);
?>
I also had a second question. What do the strings localhost and root mean? And why is the password blank? Any help is appreciated. If you need more information about my database, my website hoster, more code, or anything else, feel free to ask.
Try
<?php
while($row = mysql_fetch_array($result)){
?>
<tr><td> <?php echo $row['name']; ?> </td><td> <?php echo $row['address']; ?> </td><td> <?php echo $row['ages']; ?> </td></tr>
<?php
}
?>
$connection = mysql_connect('localhost', 'root', '');
localhost
is the domain of the server that is hosting the database 'jcsavage_initiumjobs'
root
is the MySQL userid that you are connecting to MySQL server with.
''
is the password, which in this case has not been set. When you set a password on the Userid 'root' you would add that instead of an empty (non existant) password
So for example if you set root's password to 'andBranch' you world code you connect as
$connection = mysql_connect('localhost', 'root', 'andBranch');
Try this code
<?php
$connection = mysqli_connect('localhost', 'root', '','jcsavage_initiumjobs');
if(!$connection){
die("Could not connect:" . mysqli_connect_error());
}
?>
<html>
<body>
<table id='company_tables' border='1' align='centre'>
<tr><th colspan='3'>Companies</th></tr>
<tr><th>Name of Company</th><th>Location</th><th>Ages Accepted</th> </tr>
<?php
$statement = "SELECT name, address, ages FROM companies ORDER BY name";
if($result = mysqli_query($connection, $statement))
{
while($data = mysqli_fetch_object($result))
{
echo "<tr><td>$data->name</td><td>$data->address</td><td>$data->ages</td></tr>";
}
}
?>
</table>
</body>
</html>