简体   繁体   中英

Can't connect to localhost mysql database

I'm trying to make a simple form that can be stored on mysql database. Whenever I try to connect it won't let me. Here's what I have:

PHP:

<?php

define('DB_NAME', 'forms1');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
    die('Could not connect: ' . mysqli_error());
}

$db_selected = mysqli_select_db(DB_NAME, $link);

if (!$db_selected) {
    die('Can\'t use ' . DB_NAME . ': ' . mysqli_error());
}

$value = $_POST['input1'];
$value2 = $_POST['input2'];

$sql = "INSERT INTO demo (input1, input2) VALUES ('$value', '$value2')";

if (!mysqli_query($sql)) {
    die('Error: ' . mysqli_error());
}

mysqli_close();
?>

HTML:

<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="input1" /></p>
<p>Input 2: <input type="text" name="input2" /></p>
<input type="submit" value="Submit" />
</form>

I the correct credentials, but when I open up my page it says this, "Can't use forms1:"

Doesn't even give me the error.

It will give you an error message if you add the connection variable to the call to mysqli_error()

if (!$db_selected) {
    die('Can\'t use ' . DB_NAME . ': ' . mysqli_error($link));
}

This applied to all calls to mysqli_error($link)

The PHP MYSQLI Manual

This mistake should have generated a PHP error, so if you did not see that I assume you are developing on a LIVE server where error reporting is turned off. In that case you should start all your scripts like this

<?php
error_reporting(E_ALL); 
ini_set('display_errors', 1);

This will ensure that you see these errors on the browser! Once a script is debugged you should probably remove these lines as you dont want a user to see this information should something go wrong while it is a LIVE site

Also the connect should contain the database name,

<?php

define('DB_NAME', 'forms1');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_NAME);

if (!$link) {
    die('Could not connect: ' . mysqli_error());
}

//$db_selected = mysqli_select_db(DB_NAME, $link);
//if (!$db_selected) {
//    die('Can\'t use ' . DB_NAME . ': ' . mysqli_error());
//}

The mysqli_select_db() call is there so you can change to another database on the same connection if you were using 2 databases for some reason.

I assume you are converting from the mysql_ API to mysqli_ API unfortunately the convertion is not a one to one conversion.

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