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