-2

When I try to retrieve data from mysql database, it gives me an error "No database selected" This is query:

$safe_brand_drug_name = strtoupper($drug_name);
$query = "SELECT * FROM brand_drug where brand_drug_name = {$safe_brand_drug_name}";
$result = mysql_query($query);
echo "<h1>User result</h1>";

if($result === FALSE) {
    die(mysql_error()); // TODO: better error handling
}
while($row = mysqli_fetch_array($result))
{
    echo $row['brand_drug_name'] ." - " .$row["manufacturers"] . " - " . $row["type"] . " - " . $row["price"];
    echo "<br>";
}

and this is my db connection:

define("DB_SERVER", 'localhost');
define("DB_USER", 'root');
define("DB_PASS", '1234');
define("DB_NAME", 'brand_generic');

brand_generic is my db name.

Igor Jerosimić
  • 13,621
  • 6
  • 44
  • 53
Changez Khan
  • 51
  • 1
  • 9

2 Answers2

1

The problem with your code's failure to properly execute is, you are mixing MySQL APIs using mysql_query($query) mysql_error() along with mysqli_fetch_array()

They do not mix together, being mysql_ and mysqli_ functions.

Change it to mysqli_query($con,$query) (passing DB connection variable first, then the query) while using:

or die(mysqli_error($con)) instead of mysql_error().

and

$DB_SERVER = "localhost";
$DB_USER = "root";
$DB_PASS = "1234";
$DB_NAME = "brand_generic";

in conjunction with:

$con = new mysqli($DB_SERVER, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

or, as you have it using define, defining them as constants:

define("DB_SERVER", 'localhost');
define("DB_USER", 'root');
define("DB_PASS", '1234');
define("DB_NAME", 'brand_generic');

$con = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

Since there isn't a variable to stitch it all together as shown above $con = ..., then MySQL/PHP doesn't know what to fetch as part of being the connection code. Constants alone without the whole being assigned to a variable, cannot distinguish what it is to use.

Also, make sure there are no other instances of mysql_ in the rest of your code, should there be any.

Add error reporting to the top of your file(s) immediately following your opening <?php tag.

error_reporting(E_ALL);
ini_set('display_errors', 1);

as well as or die(mysqli_error($con)) to mysqli_query() which will signal any errors found.


Sidenote:

Your present code is open to SQL injection.

Do use mysqli_ prepared statements, or PDO with prepared statements - it's safer.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
-1

Try to use database "brand_generic" in the Query in following way:

$query = "SELECT * FROM brand_generic.brand_drug where brand_drug_name = {$safe_brand_drug_name}";

Hopefully it will solve the issue.

I Bajwa PHD
  • 1,708
  • 1
  • 20
  • 42