PHP无法连接到MySQL

标签 php mysql

我正在阅读有关 PHP 和 MySQL 的第一本书。刚刚开始他们连接到数据库的第 2 章。但是我的脚本没有做任何事情。即使我故意输入不正确的连接字符串,我也没有从“or die”中得到任何错误,并且查询没有插入。我在我的 Mac 上的虚拟机上运行 Ubuntu 服务器 14 和 PHP 5.6.4 和 MySQL 5.6.24。

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

这是我的代码:

<!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>

我已经尝试将主机更改为本地主机、IP 地址、环回地址,所有这些都带有和不带有端口号。但最令人沮丧的是我没有得到任何错误。即使在我应该的时候。

我什至阅读了使用“if”创建连接/错误命令的不同方法,即

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

没有区别。出了什么问题?

最佳答案

试试这个

 $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);

关于PHP无法连接到MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640043/

相关文章:

php - 我怎样才能保护我的 Paypal 表格

php - 将数据插入 laravel 中的数据透视表

php - wordpress:将导航元素的类设置为元素的内容

mysql - 如何加入 2 个查询

mysql日期时间范围选择

mysql - 在 mysql 中选择数字、数字和 str

php - Google map javascript api 无法从 mysql 数据库加载标记

php - 隔离多维数组中的单个列

php - 同一张表上的 SQL JOIN 返回重复结果

mysql - Ubuntu - 12.04 中的 Mysql 安装错误