0

I want to connect to mysql database using php and following is my configuration file.

<?php

$host = "localhost";
$db = "payroll"
$username ="root";
$password = "";

mysql_connect ($host,$username,$password);

mysql_select_db($db,$username);
?>

but when I run my program it gives me this error:

SQL error: No database selected SQL errno: 1046

SQL: select language, admin from user where username='admin' and password='abc123'

What's wrong with my code?

Community
  • 1
  • 1
user3116267
  • 33
  • 2
  • 12

3 Answers3

3

You forgot a semicolon here

$db = "payroll";
               ^--- Here 

Don't forget to enable error reporting on your code. This is how you do it.

This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !


Switch to Prepared Statements..

A kickstart example..

<?php
$dsn = 'mysql:dbname=payroll;host=localhost';
$user = 'root';
$password = '';

try
{
    $dbh = new PDO($dsn, $user, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
    echo 'Connection failed: ' . $e->getMessage();
}

Read more here on PHP Manual

Community
  • 1
  • 1
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
1
$mysqlhost="localhost"; // MySQL-Host
$mysqluser="user"; // MySQL-User
$mysqlpwd="password"; // Password

$connection=mysql_connect($mysqlhost, $mysqluser, $mysqlpwd) or die
("Couldn“t connect");
$mysqldb="database"; // Your Database
mysql_select_db($mysqldb, $connection) or die("Couldnt select database");

I always use this. Here you get every errormessage you need to find your error.

Top Questions
  • 1,862
  • 4
  • 26
  • 38
1

Try this

<?php
$host = "localhost";
$db = "payroll"
$username ="root";
$password = "";
$con = mysql_connect ($host,$username,$password);
mysql_select_db($db,$con);
?>
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122