简体   繁体   中英

MySQL doesn't connect to the database

I am testing a local login database page on my pc under LAMP. And even though i can connect to mysql from terminal, I cannot do so from a php script. I've looked all over online but every where i go its just the following code in one variation or another

<!DOCTYPE HTML5>
<html>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <link rel="stylesheet" type="text/css" href="style.css">
    <head>
    </head>
    <body>

    <?php

    $username = $_POST['username'];
    $password = $_POST['password'];

    /* connect to the db */
    $connection = mysql_connect('localhost', 'username', 'password') or die ("Connect error");
    mysql_select_db('myDatabase',$connection);
    /* show tables */
    $res = mysql_query("SHOW DATABASES", $connection) or die ("No Show Database");
    while ($row = mysql_fetch_row($res))
    {
        echo $row[0], '<br/>';
    }

    ?>

    </body>
</html>

There is another page that takes username and password and then pass it to this page via POST method, But this page instantly shows me Connect error. I event tried it with an if else instead of the or die but still can't connect.

You have to pass the variables to the connection function and show a meaningful error description:

$username = $_POST['username'];
$password = $_POST['password'];

/* connect to the db */
$connection = mysql_connect('localhost', $username, $password) or die(mysql_error());

Your script is at risk for SQL Injection Attacks. If you can, you should stop using mysql_* functions . These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really not hard .

You really dont want to connect to your database in that fashion though, it leaves too much up to chance. And when you use passwords you really should use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM