查询数据库时出错

时间:2014-07-17 20:11:29

标签: php mysql

我开始从Head First学习PHP和MySql,现在我在第2章学习,并且我正在从书中做一些练习。

    $connection = mysql_connect("127.0.0.1", "root", "", "aliendatabase")
or die ("Oops! Couldn't connect to server because ". mysql_error());



    $sql="INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, how_long, how_many, alien_description, what_they_did, fang_spotted, other, email)
    VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', 'how_many', '$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')";


    mysqli_query($connection, $sql)
    or die('Error querying database.' . mysql_error());

  mysqli_close($connection);

当我写这个部分的时候,我一直在"错误查询数据库"错误。任何人都可以告诉我这段代码中有什么问题吗?

4 个答案:

答案 0 :(得分:6)

从mysql_query开始后,你无法使用mysqli_query。

<?php

$connection = mysql_connect("127.0.0.1", "root", "", "test") or die ("Oops! Couldn't connect to server because ". mysql_error());
mysql_select_db("test");


$sql="INSERT INTO users (id) VALUES (100000)";


mysql_query($sql,$connection) or die('Error querying database.' . mysql_error());

mysql_close($connection);

以下是 Mysqli 的教程:Link

为此目的,这里是mysqli代码:

$db = new mysqli('localhost', 'root', '', 'aliendatabase');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$sql = "INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, how_long, how_many, alien_description, what_they_did, fang_spotted, other, email)
VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', 'how_many', '$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')";

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

$db->close();

答案 1 :(得分:1)

你正在混合mysqli(注意(i))和mysql(注意(i)的缺失)。这两个库不可互换/混合。在一个中建立的连接不能被另一个使用。

请注意您的来电差异:

mysql_connect()
mysqli_query()
mysql_error()
mysqli_close()

答案 2 :(得分:0)

为此目的,这里是mysqli代码:

$db = new mysqli('localhost', 'root', '', 'aliendatabase');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$sql = "INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, how_long, how_many, alien_description, what_they_did, fang_spotted, other, email)
VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', 'how_many', '$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')";

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

$db->close();

答案 3 :(得分:0)

你不应该使用mysql。原因在本文中解释。 http://php.net/manual/en/migration55.deprecated.php 此外,您不能将mysqli与mysql混合使用。这是一个简短的解决方案unsing mysqli

$connection = new mysqli("127.0.0.1", "root", "", "test") 


$sql="INSERT INTO users (id) VALUES (100000)";


if(mysqli_query($sql,$connection))
{
   //message  if everything goes right
}
else
{
   printf("Error: %s\n", mysqli_error($connection)); //will print the errors
}