使用PHP(Mac)插入mySQL表时出错

时间:2018-11-14 17:18:10

标签: php mysql sql

当前,我正在尝试生成一些代码以将值插入表中

<?php
    error_reporting(E_ALL);
ini_set('display_errors', 'on');

$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
$sock = "/tmp/mysql.sock";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, $sock);
// Check connection
if ($conn->connect_error) {
    echo ("Connection failed: ");
} 

$sql = "INSERT INTO table (firstname, surname)
VALUES ('John', 'Doe')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>";
}
?>

(某些名称已更改),但是当我运行它(显示错误显示!)时,它说:

  

警告:mysqli :: mysqli()期望参数5长,字符串在/www/sites/545/473/www.example.co.uk/web/page.php中的第180行给出

并且:

  

警告:mysqli :: query():无法在第189行的/www/sites/545/473/www.example.co.uk/web/page.php中获取mysqli。   错误:INSERT INTO表(名字,姓氏)为VALUES(“ John”,“ Doe”)

在启用PHP的实时页面上。我不知道为什么会这样?

1 个答案:

答案 0 :(得分:3)

好吧,如果您读到错误并查看构造函数,就会发现:

mysqli::__construct ([ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]] )

您将套接字作为第5个参数发送,而端口是第5个参数。