mysql_ *没有连接到DB

时间:2015-02-24 10:53:51

标签: javascript php jquery

$con = mysql_connect("localhost","username","password","db name") or die('not connected');
echo "connected";

$sql = "SELECT id, first_name, last_name FROM reg-users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["first_name"]. " " . $row["last_name"]. "<br>";
    }
}
else 
{
    echo "0 results";
}   

我使用了上面的代码。但不行。 mysql选择查询不起作用。 请给我解决方案。

2 个答案:

答案 0 :(得分:1)

在代码中进行以下更改:

  1. 将mysql_connect()替换为mysqli_connect()
  2. 替换行$ result = $ conn-&gt;查询($ sql); with $ result = $ con&gt; query($ sql); &lt;&lt; - 请注意$ con
  3. 中的拼写错误

    您的代码应为:

    $con = mysqli_connect("localhost","username","password","db name") or die('not connected');
    echo "connected";
    
    $sql = "SELECT id, first_name, last_name FROM reg-users";
    $result = $con->query($sql); // <<-- please note spelling mistake in $con
    
    if ($result->num_rows > 0) {
    // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"]. " - Name: " . $row["first_name"]. " " . $row["last_name"]. "<br>";
        }
    }
    else 
    {
        echo "0 results";
    }   
    

答案 1 :(得分:0)

更改以下代码行

$result = $conn->query($sql);

$result = $con->query($sql);

因为你有$ con作为mysql连接对象。

并尝试从http://www.tutorialspoint.com/

学习基本选择查询