简体   繁体   English

PHP:连接到数据库,但mysql_query失败

[英]PHP: connected to database, but mysql_query fails

I have very strange problem with PHP which I am starting to learn .. I have created tables in MySQL database with some data, and now I want to show them in webpage. 我有一个非常奇怪的PHP问题,我开始学习..我已经在MySQL数据库中创建了一些数据表,现在我想在网页中显示它们。

This is my source where I have this problem: 这是我有这个问题的来源:

<?php
    // Here I open connection
    $con = mysql_connect("localhost","root","aaaaaa");
    // set the mysql database
    $db = mysql_select_db("infs", $con);

    // I check the connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    else {
        // It always goes here
        echo "Connected to database!";
    }

    // I am testing very simple SQL query.. there should be no problem
    $result = mysql_query("SELECT * FROM cathegories", $con, $db);

    if (!$result) {
        // but it always dies
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $query;
        die($message);
    }

    mysql_close($con);
?>

What is wrong? 怎么了?

Thanks in advance! 提前致谢!

// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $connection);

change to 改成

// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);

You are mixing mysql and mysqli. 你正在混合mysql和mysqli。 Try something like: 尝试类似的东西:

<?php   
    $con= new mysqli("localhost","user","passwd","database");
    if ($con->connect_errno){
      echo "could not connect";
    }

    $select = "SELECT * FROM tablename";

    if($result = $con->query($select)){
        while($row = $result->fetch_object()){
            echo $row->rowname."<br>";
        }
    }
    else { echo 'no result'; }
    $con->close();  
?>

mysql_query only takes two parameters - the actual SQL and then the link identifier (I assume in your case that's stored in $con; therefore remove $db from the third parameter). mysql_query只接受两个参数 - 实际的SQL然后是链接标识符(我假设在你的情况下存储在$ con中;因此从第三个参数中删除$ db)。

You don't even need the second $con parameter really. 你甚至不需要第二个$ con参数。

Where's the actual logic to connect to the database initially? 最初连接数据库的实际逻辑在哪里? Just because mysqli_connect_errno() doesn't return an error it doesn't mean the connection actually exists and that $con is available in the current scope. 仅仅因为mysqli_connect_errno()没有返回错误,这并不意味着连接实际存在,并且$ con在当前范围内可用。

I'd var_dump($con) before the mysql query to make sure it's a valid connection. 我在mysql查询之前使用var_dump($ con)来确保它是一个有效的连接。

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

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