繁体   English   中英

PHP无法连接到MySQL

[英]PHP cannot connect to 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());
}

没有不同。 怎么了?

试试这个

 $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.ini中未设置错误(display_errors = off,需要更改为on),因此无法显示错误。 然后我收到此错误“致命错误:未定义函数mysqli_connect()的调用”,这是因为未安装mysqli扩展名。 可以用php -m检查 Linux上的grep,如果未返回任何内容,则未安装mysqli。 安装php5-mysqlnd并重新启动apache。 然后修复,感谢您的所有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM