You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP连接本地MySQL数据库及解决mysqli_connect参数报错

Hey there, let's work through your MySQL connection issue together!

What's Causing the Error?

That mysqli_connect() expects parameter 5 to be long, string given warning boils down to wrong parameter order and invalid values in your connection call. Let's break it down clearly:

The official signature for mysqli_connect() is:

mysqli_connect(host, username, password, database, port, socket);

In your code, you’re passing $port as the second parameter, $uname as the third, $pword as the fourth, and $dbname as the fifth. The fifth parameter is supposed to be an integer port number, but you’re passing a string database name instead—hence the type mismatch error.

You also have a couple of invalid values cluttering your variables:

  • $servername = "Mysql@127.0.0.1": The Mysql@ prefix is unnecessary; MySQL only needs the raw IP or hostname (like 127.0.0.1 or localhost)
  • $uname = "root@localhost": MySQL usernames don’t include the @host suffix when connecting—just use root
  • $port = "3306": Port numbers should be integers, not strings

Fixed Code & Step-by-Step Fixes

Here’s the corrected version of your PHP code, with comments explaining each tweak:

<?php 
// 1. Remove the invalid "Mysql@" prefix from the host address
$servername = "127.0.0.1"; 
// 2. Use an integer for the port (no quotes required)
$port = 3306; 
// 3. Simplify the username to just "root" (drop the @localhost suffix)
$uname = "root"; 
// 4. Match your config.php's empty password (set to empty string "")
$pword = ""; 
$dbname = "database"; 

// 5. Fix the parameter order to match mysqli_connect's official signature
$conn = mysqli_connect($servername, $uname, $pword, $dbname, $port); 

// 6. Use procedural-style error handling (since we're using mysqli_connect(), not the object constructor)
if (!$conn) { 
    die("Connection failed: " . mysqli_connect_error()); 
} 
echo "Connected successfully!";
?>

Quick Note on Empty Passwords

Leaving the password empty is technically allowed (which aligns with your config.php setting), but this is extremely insecure. It’s acceptable for local, closed-environment testing, but never use an empty password for a production database—anyone with access to your server could take over your database instantly.

内容的提问来源于stack exchange,提问作者Sara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:17:20