如何用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": TheMysql@prefix is unnecessary; MySQL only needs the raw IP or hostname (like127.0.0.1orlocalhost)$uname = "root@localhost": MySQL usernames don’t include the@hostsuffix when connecting—just useroot$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

