php - 查询数据库时出错

标签 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);

当我写那部分时,我不断收到“查询数据库时出错”的错误。谁能告诉我这段代码有什么问题?

最佳答案

从 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();

关于php - 查询数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24812650/

相关文章:

php - 如何设置这个全文索引

mysql - 创建 bash 脚本以自动创建数据库和用户

php - 如何使用 PHP 正确创建此 XML

php - Zend Framework 路由 : unknown number of params

php - PHP for 循环输出中漂亮的 HTML 格式

javascript - 重定向到用户定义的位置

mysql - 远程 mySQL 连接从 XAMPP 抛出 "cannot connect to MySQL 4.1+ using the old insecure authentication"错误

java - JDBC/结果集错误

python - 使用 %s 运算符在 Python 中创建 MySQL 数据库

php - 通过插件向 laravel 添加路由