0

I am trying to select data from a database. I do have a successful connection, but it seems like the query doesn't work even though I know for sure that the query is right. What am I doing wrong?

If I execute the code below, the result I get is: "Connected successfullyBad query". The 'Bad query' should mean that the query is wrong, but I checked it and it isn't wrong...

<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>    

I expect to only see "connected successfully"

  • 1
    Don't forget to change your password – Strawberry May 31 '19 at 22:38
  • Instead of just dying with a string, you could die with an useful error message by using [mysqli_error](https://www.php.net/manual/en/mysqli.error.php) like so: `die(mysqli_error($conn));` – KIKO Software May 31 '19 at 22:38
  • 1
    [How to enable MySQLi exception mode?](https://stackoverflow.com/questions/22662488/how-to-get-mysqli-error-information-in-different-environments/22662582#22662582) – Dharman May 31 '19 at 22:49

3 Answers3

2

You are missing your database name. You can do it two ways, or in the connect statement:

$conn = new mysqli($servername, $username, $password,$database);

Or you can do it in your select statement:

$sql ="SELECT * FROM  `yourdatabase`.`producten`";

If you don´t set your database your query is wrong

nacho
  • 5,280
  • 2
  • 25
  • 34
0

Your query is right just write your database name in mysqli constructor.

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

Visit: https://www.php.net/manual/en/mysqli.construct.php

0

Please give database name also, check below code.

<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = "";      //Enter database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>    
  • Welcome to Stack Overflow. While your code may provide the answer to the question, please add context around it so others will have some idea what it does and why it is there. – Theo Jun 01 '19 at 08:07