简体   繁体   中英

Linking mySQL database on MAMP server with PHP

I'm extremely new at php and I'm trying to test if I can make a connection to my database. I use MAMP, and my MAMP ports are all at 8888 (idk if that makes a difference). To log into the local server with the mysql command lineboth my user and password is root. I am trying to see if the database Engineeringcareers can be connected. The page is stuck trying to load. If I only put echo 'xxx' then xxx shows up so the issue isn't if the php would run. It's the connection.

Is my code wrong here? I've tried many approaches

 <?php $dbhost='localhost:8888'; $dbuser ='root'; $dbpassword ='root'; $dbdatabase= 'Engineeringcareers'; $connection = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbdatabase); if (!$link) { die('could not connect: ' . mysql_error()); } $db_selected = mysqli_select_db($dbdatabase, $connection); if(!db_selected) { die('cant use ' . $dbdatabase . ':' . mysql_error()); } echo ' connected'; 

On a side note. Does anyone have any particular source that they go to to find out how to create a form with html and link it to the mysql database with php? I'm trying to learn how to do this, hopefully after I get the connection working.

Just remove port 8888 and you are done, by default mysql_connect which is an alias of mysqli::__construct() uses port 3306 to connect to mysql, if you are running mysql on another port than 3306 you have to assign it like this:

$connection = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbdatabase, $port); 

EDIT: By default apache uses port 80 and mysql uses 3306, if you are running apache on port 8888 it doesn't mean that your database is available on port 8888 too, that's because each service can only use a unique port to communicate with other services.

Hope this helps

Your dbhost should be localhost, as pointed out by YouneL

$dbhost='localhost';

Here, you can refer to this link for an example on how to create a form with html and link it to the mysql database with php. - https://www.cloudways.com/blog/custom-php-mysql-contact-form/

Give localhost only in $dbhost and connect MYSQLi like below:

$dbhost='localhost';
$dbuser ='root';
$dbpassword ='root';
$dbdatabase= 'Engineeringcareers';

$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbdatabase);

// Check connection
if($mysqli === false){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}

// Print host information
echo "Connect Successfully. Host info: " . $mysqli->host_info;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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