0

I am trying to connect to a simple database on XAMPP using php- I know the database exists as I can see it on PHPMyAdmin and have created a table called students and added some data. I have tested that I can run a simple test.php file ( from the htdocs folder on the XAMPP drive) and get a response. I cannot spot what is stopping me connecting to my database- can anyone help?

<?php
// connect to the database
$user_name = "root";
$password = "";
$database = "computing";
$host_name ="localhost";

$con=mysql_connect($host_name,$user_name,$password);
mysql_select_db($database);
//check connection

echo "Connection opened";

mysql_close($con);
?>
user2127168
  • 91
  • 2
  • 11
  • 3
    You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php) – Quentin Jul 24 '14 at 12:50
  • 1
    I don't see any problem with this code. It simple works and don't see any `unexpected syntax error` however you should consider using other methods to connect to database as @Quentin mentioned. – Marcin Nabiałek Jul 24 '14 at 12:52
  • Thanks for the link, I used mysqli which has worked now- cannot see a tick to mark this as the answer? – user2127168 Jul 24 '14 at 13:16

2 Answers2

0

The code above should work. Maybe try mysql_select_db($database, $con);

Fortuna
  • 611
  • 6
  • 18
0

Could you please try the following code if it works?

<?php
// connect to the database
$user_name = "root";
$password = "";
$database = "computing";
$host_name = "localhost";

$con = mysqli_connect($host_name ,$user_name ,$password,$database) or die("Error " .       mysqli_error($con));
//check connection

echo "Connection opened";

mysql_close($con);
?>

mysql commands are not going to be supported in future releases, so it would be best perhaps to use mysqli or PDO connections.

Also PDO uses parameters (the syntax might take a bit to make sense), so it is great to reduce risk from SQL Injections.

Mysqli: http://php.net/manual/en/function.mysqli-connect.php

PDO: http://php.net/manual/en/class.pdo.php

Alex Szabo
  • 3,274
  • 2
  • 18
  • 30