PHP无法连接到MySQL

时间:2015-07-26 17:43:50

标签: php mysql

我正在阅读关于PHP和MySQL的第一本书。刚刚开始第2章,他们连接到数据库。但我的脚本没有做任何事情。即使我故意输入错误的连接字符串,并且查询未插入,我也没有收到“或死”的错误。我在Mac上的VM上运行带有PHP 5.6.4和MySQL 5.6.24的Ubuntu服务器14。

我可以远程连接MySQL工作台并执行成功的查询。

这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Aliens Abducted Me - Report an abduction</title>

</head>
<body>
<h2>Aliens Abducted Me - Report an abduction</h2>
<?php

$name = $_POST['firstname'] . ' ' . $_POST['lastname'];
$when_it_happened = $_POST['whenithappened'];
$how_long = $_POST['howlong'];
$how_many = $_POST['howmany'];
$alien_description = $_POST['aliendescription'];
$what_they_did = $_POST['whattheydid'];
$fang_spotted = $_POST['fangspotted'];
$email = $_POST['email'];
$other = $_POST['other'];

echo 'Thanks for submitting the form ' . $name . '<br />';
echo 'You were abducted ' . $when_it_happened;
echo ' and were gone for ' . $how_long . '<br />';
echo 'You saw ' . $how_many . ' of them' . '<br />';
echo 'Describe them: ' . $alien_description . '<br />';
echo 'What the did: ' . $what_they_did . '<br />';
echo 'Was Fang there? ' . $fang_spotted . '<br />';
echo 'Your email address is ' . $email . '<br />';
echo 'Additional information: ' . $other;

$dbc = mysqli_connect('127.0.0.1', 'root', 'password', 'aliendatabase')
or die('Error connecting to server');


$query = "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 ('Sally', 'Jones', '3 days ago', '1 day', 'four', " .
    "'green with 6 tenticles', 'We talked and played with a dog', " .
    "'yes', 'I may have seen your dog', 'sally@gregs-list.net')";

$result = mysqli_query($dbc, $query)
or die ('Error querying DB');

mysqli_close($dbc);


?>
</body>
</html>

我尝试将主机更改为localhost,ip地址,环回地址,无论是否有端口号。但最令人沮丧的是我没有错误。即使我应该。

我甚至已经阅读了使用“if”即

创建连接/错误命令的不同方法
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
没有区别。出了什么问题?

2 个答案:

答案 0 :(得分:0)

尝试这个

 $dbc = mysqli_connect("localhost","root","password",'aliendatabase');

if(!$dbc)
{
   echo "cannot connet to the server";
}
$q = "Your insert query here";
$query=mysqli_query($dbc, $q)
 or die("Error: ".mysqli_error($dbc));
 mysqli_close($dbc);

答案 1 :(得分:0)

感谢您回复我,我很感激。我发现了问题所在。没有显示的错误是由于我的php.ini中没有设置错误(display_errors = off,需要更改为on)。然后我收到了这个错误&#34;致命错误:调用未定义的函数mysqli_connect()&#34;这是因为没有安装mysqli扩展。可以用php -m |检查在linux上使用grep,如果没有返回任何内容则不安装mysqli。安装php5-mysqlnd并重启apache。然后感谢所有的帮助。