简体   繁体   中英

Why isn't this php code allowing me to connect to my database?

I'm using a WAMP server and on it I created a database and a table. All the names are correct and the user has full access to everything. When I run the code, it prints out "Unable to select database". Thanks.

<?php

if(isset($_POST["Submit"])){  
        print_r ($_POST["nutrient"]);
}




session_start();

//establish connection
$server = "localhost";
$db_username = "root";
$db_password = "";
$database = "gainlife_cavin";
$table = "cavintable"; 


//connect PHP script to database
$connection = mysqli_connect($server, $db_username, $db_password, $database);


//select database to use
@mysql_select_db($database) or die( "Unable to select database");

//$query = "INSERT INTO $table VALUES("")"
//mysql_query($query)

mysql_close();



?>

<body>
</form> 

Try something like the following.

<?php
//establish connection
$server = "localhost";
$db_username = "root";
$db_password = "";
$database = "gainlife_cavin";
$table = "cavintable"; 

    //connect PHP script to database
    $connection =mysqli_connect("$server","$db_username","$db_password","$database");

    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    //Your query here

    mysqli_close($connection);
?>

I use simple code 1 line. here is my code that i'm using.

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}

您从MySQLI转变为在选择数据库以及其余代码时不使用MySQLI。

Try this. I have change mysqli_connect to mysql_connect and mysql_select_db variable.

//connect PHP script to database
$connection = mysql_connect($server, $db_username, $db_password, $database);


//select database to use
$select  = mysql_select_db($connection) or die( "Unable to select database");

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