0

This is for PHP 7 to contact mysql.

I want to query the database called "database1" and for it to print the content of this db in the web browser.

<?php

function check_password($username, $password) {
// Create connection
$db = new mysqli('localhost','<DB-USERNAME>','<USER-PASSWORD>','<DATABASENAME>');

// Check for errors
if($db->connect_errno){
echo $db->connect_error;

}

$query = 'SELECT * FROM `<TABLENAME>`';

$result = mysqli_query($query);

if (!$result) {
    $message = 'Invalid query: ' . mysqli_error() - "\n";
    $message .= 'Whole Query: ' . $query;
    die($message);
}

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];

}

mysqli_free_result($result);
?>
  • you have error ?? .. – ScaisEdge Feb 01 '18 at 10:49
  • 1
    First of all, your connection function isn't correct- Google how to connect to a MySQL database. Also, you've mixing up`mysql` and `mysqli` - you always want to use the `mysqli_*` functions (or `PDO_*`) since `mysql_*` is deprecated and not longer supported in PHP7. – Twinfriends Feb 01 '18 at 10:49
  • Also you're trying to select rows from "database1" ?? you have to provide a Table name (e.g. "users", "workers", "invoices") instead of Database name. In `mysqli` connection you have already this Database in use. – Mateusz Palichleb Feb 01 '18 at 10:51
  • Possible duplicate of [Can I mix MySQL APIs in PHP?](https://stackoverflow.com/questions/17498216/can-i-mix-mysql-apis-in-php) – Nigel Ren Feb 01 '18 at 11:10
  • I also used an example table including example php code an got: Failed to connect to MySQL: Access denied for user ''@'localhost' to database ''. All privileges has been granted to though. –  Feb 01 '18 at 15:03

1 Answers1

3

Initially, you start using the MYSQLI extension, which is an improved version of old MYSQL extension.

$db = new mysqli('localhost','DB-USERNAME','<USER-PASSWORD>','<DATABASE');

And then suddenly you start using old MYSQL extension and that is the error.

$result = mysql_query($query);

Be consistent, use only one type of extension. Don't mix.

I recommended you to use the new and improved MYSQLI extension

Visit the PHP documentation site for more information about the MYSQLI extension

And also the old MYSQL extension is deprecated in PHP version 5.5.0 and removed in PHP version 7.0.0. Click here for more information