SJOM
SJOM

Reputation: 3

PHP code will not connect to database

I can connect to MySQL server but not the DB. So on my webpage it shows "Connected to MySQL" but then underneath that I get "Could not select examples which tells me it didn't connect to the database". Could anyone help?

<?php
$username = "user_admin";
$password = "Password";
$hostname = "localhost:3306"; 

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

**<?php
//select a database to work with
$selected = mysql_select_db ("my_dbname", $dbhandle)
  or die("Could not select examples");  
?>**

<?php
$sql = "SELECT * FROM `company` WHERE \'companyname\' like \'%a%\' LIMIT 0, 30 "; 

 while($row = mysqli_fetch_array($sql))
   {
   echo $row['companyname'];
   echo "<br>";
   }

 mysql_close($con);
?>

Upvotes: 0

Views: 162

Answers (2)

Tosx
Tosx

Reputation: 606

As Lincb said, maybe the database doesn't exist.

Try to display the error to have more information :

$selected = mysql_select_db('my_dbname', $dbhandle);
if (!$selected ) {
   die ('Error database : ' . mysql_error());
} 

Upvotes: 2

lincb
lincb

Reputation: 632

THe most likely cause is that the database "my_dbname" doesn't exist. Also, use mysqli or PDO. mysql is deprecated and insecure.

Upvotes: 1

Related Questions