简体   繁体   English

为什么这个php代码不允许我连接到数据库?

[英]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. 我正在使用WAMP服务器,并在其上创建了一个数据库和一个表。 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. 我使用简单的代码1行。 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. 我将mysqli_connect更改为mysql_connectmysql_select_db变量。

//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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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