0

I'm trying to learn php and I can't read any data from my database!. I know the connection to the server is live and working but this line seem to be giving me problems.

$result = $conn->query($sql);

Where $sql = "SELECT firstName, middleName, lastName FROM Base"; I'm not sure what the problem is but any hints or answer are appreciated .

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My first PHP page</h1>
<?php
// connect to database
$user_name = "superUser";
$password = "";
$database = "Base"$server = "127.0.0.5";
// open connection to the server
$conn = new mysqli($server, $user_name, $password);
// echo "Connection to the server is open";
// check connetion
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
else {
    print "Connection to the server is open";
}
// load the data from the table
$sql = "SELECT firstName, middleName, lastName FROM Base";
// echo $conn->server_info;
$result = $conn->query($sql);
if ($result) {
    echo "Table was found";
}
else echo "no";
/*while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br />";
}
print $result["firstName"];// ": Number of Rows!" ;*/
// if ($result->num_rows > 0) {
// output data of each row
// close server connection
$conn->close();
?>
</body>
</html>
2
  • mysqli($server, $user_name, $password,$database); Commented Sep 27, 2015 at 2:11
  • You didn't select your db. Commented Sep 27, 2015 at 2:13

1 Answer 1

3

The following is a mysqli connect example.

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

You forgot to add your database name. Change this,

$conn = new mysqli($server, $user_name, $password);

to this

$conn = new mysqli($server, $user_name, $password, $database);
Sign up to request clarification or add additional context in comments.

4 Comments

You sir are a GENIUS!!!! Thank you so much!!! Its always the simple things that get us(me)!!!!
You are welcome. PHP is a lot of fun once you get the hang of it. Keep at it! And if you are happy with this answer, please select it as correct :)
Also, I noticed your code, you have "SELECT firstName, middleName, lastName FROM base" and your database name is also "base" is this correct? For your select query, it should be the name of the table you want to retrieve from, not the database name. For example "SELECT firstName, middleName, lastName FROM users";
Yep yep I was just making a sample database and table to try to read data from and just coincidentally gave them the same name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.